package com.fdkankan.common.realm;

import cn.hutool.core.util.StrUtil;
import com.fdkankan.common.exception.JwtAuthenticationException;
import com.fdkankan.common.jwt.JwtToken;
import com.fdkankan.common.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class AppJwtRealm extends AuthorizingRealm {
    private static Logger log = LoggerFactory.getLogger("programLog");

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        log.info("Step 2: Agent进行用户名正确与否验证");
        String token = (String) auth.getCredentials();
        log.info("doGetAuthenticationInfo - step3 :" + token);
        if (StrUtil.isEmpty(token)){
            throw new JwtAuthenticationException(3004, "无token，请重新登录");
        }
        // 获取 token 中的 userName
        String userName = JwtUtil.getUsername(token);
        if (StrUtil.isEmpty(userName)){
            throw new JwtAuthenticationException(3004, "访问异常！");
        }
        String regex = "^-?\\d+(\\.\\d+)?$";
        if(userName.matches(regex)){
            // TODO: 2021/12/21
//            if (!JedisUtil.exists(SsoUtil.PREFIX_CACHE_CAMERA + userName)){
//                throw new JwtAuthenticationException(3004, "用户未登录");
//            }
//            if (!JedisUtil.getStringValue(SsoUtil.PREFIX_CACHE_CAMERA + userName).contains(token)){
//                throw new JwtAuthenticationException(3004, "用户未登录");
//            }
        }
// TODO: 2021/12/21
//        JedisUtil.expire(SsoUtil.PREFIX_CACHE_CAMERA + userName, 21600);

        return new SimpleAuthenticationInfo(token, token, "jwt_realm");
    }
}
