package com.fdkankan.web.realm;

import cn.hutool.core.util.StrUtil;
import com.fdkankan.common.util.JwtUtil;
import com.fdkankan.web.exception.JwtAuthenticationException;
import com.fdkankan.web.jwt.JwtToken;
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 AgentJwtRealm 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();
        if (StrUtil.isEmpty(token)){
            throw new JwtAuthenticationException(3004, "无token，请重新登录");
        }
        // 获取 token 中的 userName
        String userName = JwtUtil.getUsername(token);
        if (StrUtil.isEmpty(userName)){
            throw new JwtAuthenticationException(3004, "访问异常！");
        }
//        if (!userName.contains(SsoUtil.PREFIX_CACHE_AGENT)){
//            throw new JwtAuthenticationException(3004, "用户未登录");
//        }
        if (!JwtUtil.isVerify(token, userName)) {
            throw new JwtAuthenticationException(3004, "非法访问！");
        }
//        // 防止重复登陆， redisToken是最新登录获取的token
//        String redisToken = JedisUtil.getStringValue(userName);
//        if (StrUtil.isEmpty(redisToken) || !redisToken.equals(token)){
//            throw new JwtAuthenticationException(3004, "用户未登录");
//        }

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