package com.nuliji.tools.shiro;

import com.nuliji.tools.shiro.inter.RealmAuthenticationToken;
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.ArrayList;
import java.util.Collection;

/**
 * Created by GaoJie on 2017/11/3.
 */
public class RealmAuthenticator extends ModularRealmAuthenticator {

    private static final Logger logger = LoggerFactory.getLogger(RealmAuthenticator.class);
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();

        RealmAuthenticationToken customizedToken = (RealmAuthenticationToken) authenticationToken;
        // 登录类型
        Class realmCls = customizedToken.getRealm();
//        logger.info("need realms:"+realmCls);
        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        Collection<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
//            logger.info("now realms:"+realm.getClass());
//            logger.info("valid realms:"+realmCls.isAssignableFrom(realm.getClass()));
            if (realmCls.isAssignableFrom(realm.getClass()))
                typeRealms.add(realm);
        }
//        logger.info("realms:"+typeRealms);
        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1)
            return doSingleRealmAuthentication(typeRealms.iterator().next(), authenticationToken);
        else
            return doMultiRealmAuthentication(typeRealms, authenticationToken);
    }

}
