package cn.estsh.i3plus.core.apiservice.auth.realm;

import cn.estsh.i3plus.core.apiservice.controller.DemoAuthController;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.shirotoken.AdminToken;
import cn.estsh.i3plus.pojo.base.shirotoken.SaAdminToken;
import cn.estsh.i3plus.pojo.base.shirotoken.UserToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;

/**
 * @Description : 验证规则模块封装
 * @Reference :
 * @Author : alwaysfrin
 * @CreateDate : 2018-10-13 18:37
 * @Modify:
 **/
public class DefaultModularRealm extends ModularRealmAuthenticator {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoAuthController.class);
    private Map<String, Realm> definedRealms;

    public DefaultModularRealm(Map<String, Realm> definedRealms) {
        this.definedRealms = definedRealms;
    }

    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        return super.doMultiRealmAuthentication(realms, token);
    }

    public Map<String, Realm> getDefinedRealms() {
        return this.definedRealms;
    }

    public void setDefinedRealms(Map<String, Realm> definedRealms) {
        this.definedRealms = definedRealms;
    }

    protected AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException {
        Realm realm;
        if (token instanceof SaAdminToken) {
            //超级管理员
            realm = (Realm)this.definedRealms.get(CommonEnumUtil.USER_TYPE.SA.getCode());
        } else if (token instanceof AdminToken) {
            //管理员
            realm = (Realm)this.definedRealms.get(CommonEnumUtil.USER_TYPE.ADMIN.getCode());
        } else if (token instanceof UserToken) {
            //用户
            realm = (Realm)this.definedRealms.get(CommonEnumUtil.USER_TYPE.USER.getCode());
        } else {
            throw new AuthenticationException("不存在TOKEN，请联系管理员（"+token+"）");
        }

        return this.doSingleRealmAuthentication(realm, token);
    }

    protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
        if (!realm.supports(token)) {
            throw new AuthenticationException("TOKEN类型异常，请联系管理员");
        } else {
            return realm.getAuthenticationInfo(token);
        }
    }
}
