package com.ho.user.config.shiro;


import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.util.RedisCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * desc: 判断token是否有效 从缓存中获取,没有获取到说明无效
 *
 */
@Slf4j
public class CustomHashedCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private RedisCommon redisCommon;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        CustomPasswordToken customPasswordToken= (CustomPasswordToken) token;
        String accessToken = (String) customPasswordToken.getPrincipal();
        //String userId= JwtTokenUtil.getUserId(accessToken);
        String tokenKey = RedisKeyConstant.User.TOKEN + accessToken;
        //判断系统是否含有key,含有则
        if(redisCommon.hasKey(tokenKey)){
            //延长时间
            redisCommon.extendUserCachePair(accessToken ,null);
        }else{
            log.info("token is invalid!! {}" , accessToken);
            return false;
            //throw new BusinessException(BaseResponseCode.TOKEN_PAST_DUE);
        }

        /*if(redisService.hasKey(Constant.JWT_REFRESH_KEY+userId)&&redisService.getExpire(Constant.JWT_REFRESH_KEY+userId, TimeUnit.MILLISECONDS)>JwtTokenUtil.getRemainingTime(accessToken)){
            if(!redisService.hasKey(Constant.JWT_REFRESH_IDENTIFICATION+accessToken)){
                throw new BusinessException(BaseResponseCode.TOKEN_PAST_DUE);
            }
        }*/
        return true;
    }
}
