package com.uas.sso.web.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
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 com.uas.sso.Token;

/**
 * <p>
 * shiro接口，sso 信任票据域
 * </p>
 * 
 */
public class SSOAuthorizingRealm extends AuthorizingRealm {

	private SSOPermission permission;

	/**
	 * 根据用户身份获取授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (principals == null) {
			throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
		}
		Token token = (Token) getAvailablePrincipal(principals);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		List<String> permissions = permission.getPermissions(token);
		if (permissions != null) {
			authorizationInfo.addStringPermissions(permissions);
		}
		return authorizationInfo;
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		return token != null && SSOAuthenticationToken.class.isAssignableFrom(token.getClass());
	}

	@Override
	public Class<?> getAuthenticationTokenClass() {
		return SSOAuthenticationToken.class;
	}

	/**
	 * 获取身份验证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
	}

	public SSOPermission getPermission() {
		return permission;
	}

	public void setPermission(SSOPermission permission) {
		this.permission = permission;
	}

}
