package org.jeecg.config.shiro;

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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jeecg.common.system.vo.PartnerUserLoginUser;
import org.jeecg.config.shiro.util.ShopTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class PartnerShiroRealm extends AuthorizingRealm {
    
    @Autowired
    private ShopTokenUtil shopTokenUtil;
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

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

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        boolean verified = shopTokenUtil.verifyPartnerCustomerUserToken(token);
        if (!verified) {
            return null;
        }
        Boolean hasKey = redisTemplate.hasKey("shop:user:invalid-token:" + token);
        if (Boolean.TRUE.equals(hasKey)) {
            return null;
        }
        PartnerUserLoginUser customerLoginUser = new PartnerUserLoginUser();
        customerLoginUser.setId(shopTokenUtil.getUid(token));
        return new SimpleAuthenticationInfo(customerLoginUser, token, getName());
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    @Override
    public boolean isAuthorizationCachingEnabled() {
        return false;
    }

}
