package com.kiisoo.ic.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.common.utils.MD5FileUtil;
import com.kiisoo.ic.constants.Constants;
import com.kiisoo.ic.system.entity.PrivilageAccountDO;
import com.kiisoo.ic.system.mapper.PrivilageAccountDOMapper;
import org.apache.shiro.authc.*;
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.apache.shiro.subject.SimplePrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

/**
 * Shiro认证
 * @author Arvin
 * 
 */
public class AuthorizationRealm extends AuthorizingRealm {
	
	/**
	 * 用户服务
	 */
    @Resource
    private PrivilageAccountDOMapper privilageAccountDOMapper;
    
    /**
     * 菜单权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 登陆认证
     * @param authcToken 要认证的token信息
     * @return authenticationInfo
     * @throws AuthenticationException 认证异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        QueryWrapper<PrivilageAccountDO> wrapper = new QueryWrapper<>();
        wrapper.eq("login",token.getUsername()).last("limit 1");
        PrivilageAccountDO userInfo = privilageAccountDOMapper.selectOne(wrapper);
        if(userInfo == null){
            throw new UnknownAccountException("用户不存在");
        }
        if (Constants.ACCOUNT_STATUS_UNABLE != userInfo.getStatus()) {
            throw new LockedAccountException("无效账号");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo.getLogin(), userInfo.getPassword(), "");
        return info;
    }

    /**
     * 清除认证信息
     * @param principal 主体
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

}