package com.xmomen.module.account.realm;

import com.xmomen.module.account.service.UserService;
import com.xmomen.module.core.web.token.SysUserToken;
import com.xmomen.module.user.entity.SysUsers;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
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.util.ByteSource;

import java.util.Set;


/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
public class UserRealm extends AuthorizingRealm {

    // 注入UserService
    private UserService userService;

    // 设置UserService
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    // 获取用户的授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取用户名
        String username = (String)principals.getPrimaryPrincipal();
        // 获取用户的角色
        Set<String> roles = userService.findRoles(username);
        // 获取用户的权限
        Set<String> realmNames = principals.getRealmNames();
        for(String realmName: realmNames) {
        	if(realmName.contains("UserRealm")) {
        		roles.add("user");
        	}
        }
        // 创建SimpleAuthorizationInfo对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 设置用户的角色
        authorizationInfo.setRoles(roles);
        // 设置用户的权限
        authorizationInfo.setStringPermissions(userService.findPermissions(username));
        return authorizationInfo;
    }

    
    // 判断是否支持该类型的token
    @Override
	public boolean supports(AuthenticationToken token) {
		if(token instanceof SysUserToken) {
			return super.supports(token);
		}
		return false;
	}

	// 获取用户的认证信息
	@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 获取用户名
        String username = (String)token.getPrincipal();

        // 根据用户名获取用户信息
        SysUsers user = userService.findByUsername(username);

        // 如果用户不存在，抛出UnknownAccountException异常
        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        // 如果用户被锁定，抛出LockedAccountException异常
        if(Boolean.TRUE.equals(user.getLocked())) {
            throw new LockedAccountException(); //帐号锁定
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        // 创建SimpleAuthenticationInfo对象
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username, //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getSalt()),//salt=salt
                getName()  //realm name
        );
        return authenticationInfo;
    }

    // 清除用户的授权信息
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    // 清除用户的认证信息
    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    // 清除用户的缓存信息
    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    // 清除所有用户的授权信息
    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    // 清除所有用户的认证信息
    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    // 清除所有用户的缓存信息
    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }

}
