package xyz.luxnk.lproject.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.nutz.dao.Dao;
import org.nutz.integration.shiro.SimpleShiroToken;
import org.nutz.mvc.Mvcs;
import xyz.luxnk.lproject.bean.Permission;
import xyz.luxnk.lproject.bean.Role;
import xyz.luxnk.lproject.bean.UserInfo;

public class SimpleAuthorizingRealm extends AuthorizingRealm {

    protected Dao dao;  // ShiroFilter先于NutFilter初始化，所以无法使用注入功能

    public Dao dao() {
        if (dao == null) {
            dao = Mvcs.ctx().getDefaultIoc().get(Dao.class, "dao");
            return dao;
        }
        return dao;
    }

    public void setDao(Dao dao) {
        this.dao = dao;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        if (principalCollection == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        String userId = (String) principalCollection.getPrimaryPrincipal();
        UserInfo userInfo = dao().fetch(UserInfo.class, userId);
        if (userInfo == null)
            return null;
        if (userInfo.isLocked())
            throw new LockedAccountException("Account [" + userInfo.getUsername() + "] is locked.");

        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        userInfo = dao().fetchLinks(userInfo, null);
        if (userInfo.getRoles() != null) {
            dao().fetchLinks(userInfo.getRoles(), null);
            for (Role role : userInfo.getRoles()) {
                auth.addRole(role.getName());
                if (role.getPermissions() != null) {
                    for (Permission p : role.getPermissions()) {
                        auth.addStringPermission(p.getName());
                    }
                }
            }
        }
        if (userInfo.getPermissions() != null) {    // 特许、临时分配的权限
            for (Permission p : userInfo.getPermissions()) {
                auth.addStringPermission(p.getName());
            }
        }

        return auth;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        SimpleShiroToken upToken = (SimpleShiroToken) authenticationToken;

        // upToken.getPrincipal()的返回值就是SimpleShiroToken构造方法传入的值
        // 可以是int也可以是UserInfo类实例，或任何你希望的值，自行处理一下就好了
        UserInfo userInfo = dao().fetch(UserInfo.class, (String)upToken.getPrincipal());
        if (userInfo == null)
            return null;
        if (userInfo.isLocked())
            throw new LockedAccountException("Account [" + userInfo.getUsername() + "] is locked.");
        return new SimpleAccount(userInfo.getId(), userInfo.getPassword(), getName());
    }

    /**
     * 覆盖父类的验证，直接pass
     * 在Shiro内做验证的话，出错了都不知道哪里错
     * @param token
     * @param info
     * @throws AuthenticationException
     */
    @Override
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException { }

    public SimpleAuthorizingRealm() {
        this(null, null);
    }

    public SimpleAuthorizingRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
        super(cacheManager, matcher);
        setAuthenticationTokenClass(SimpleShiroToken.class);    // 非常非常重要，与SecurityUtils.getSubject().login是对应关系!!!
    }

    public SimpleAuthorizingRealm(CacheManager cacheManager) {
        this(cacheManager, null);
    }

    public SimpleAuthorizingRealm(CredentialsMatcher matcher) {
        this(null, matcher);
    }

}
