package com.pannk.mms.common.oauth2;

import com.pannk.mms.common.base.Constant;
import com.pannk.mms.common.exception.BaseException;
import com.pannk.mms.common.utils.RedisUtil;
import com.pannk.mms.modules.sys.entity.SysUserEntity;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * Created by wolf on 20-11-6.
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private RedisUtil redisUtil;

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

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUserEntity sysUserEntity = (SysUserEntity) principalCollection.getPrimaryPrincipal();
        Set<String> perms = redisUtil.getEntity(Constant.PERMS_CAHCE + sysUserEntity.getId(), Set.class);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }

    /**
     * 登录认证
     *
     * @param authenticationToken token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        SysUserEntity sysUserEntity = redisUtil.getEntity(Constant.USER_CACHE + token, SysUserEntity.class);
        if (sysUserEntity == null) {
            throw new BaseException("token失效,请重新登录");
        }
        if (sysUserEntity.getStatus() == 1) {
            throw new LockedAccountException("账号被锁定,清联系管理员处理");
        }
        return new SimpleAuthenticationInfo(sysUserEntity, token, getName());
    }
}
