package cn.wisenergy.shiro.util;

import cn.wisenergy.mapper.WorkUserMapper;
import cn.wisenergy.model.app.WorkUser;
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.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @description:
 * @author: nh
 * @create: 2021-04-05 18:04
 **/
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private WorkUserMapper workUserMapper;

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

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        WorkUser user = workUserMapper.getUserByLoginName(principal);
        if (user != null) {
            return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        }
        return null;
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        // 存入redis中的认证信息是以"Authentication"+loginName为key
        // 在认证信息中中存入的主体信息为WorkUser对象，需要将loginName取出为删除认证信息使用
        WorkUser user = (WorkUser)principals.getPrimaryPrincipal();
        SimplePrincipalCollection newPrincipals = new SimplePrincipalCollection(user.getLoginName(), this.getName());
        super.clearCachedAuthenticationInfo(newPrincipals);
    }



}
