package com.uas.platform.b2b.support;

import java.util.Collection;
import java.util.Iterator;

//import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

/**
 * 访问决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源 ;做最终的访问控制决定
 * 
 * @author yingp
 * @version 1.0
 * 
 */
public class CustomAccessDecisionManager implements AccessDecisionManager {

	/**
	 * @param authentication
	 * @param object
	 * @param configAttributes
	 * @throws AccessDeniedException
	 * @throws InsufficientAuthenticationException
	 */
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (null == configAttributes || configAttributes.size() == 0) {
			return;
		}
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		String needPermission = null;
		while (iterator.hasNext()) {
			ConfigAttribute configAttribute = iterator.next();
			needPermission = configAttribute.getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needPermission.equals(ga.getAuthority())) {
					return;
				}
			}
		}
		if (needPermission != null)
			throw new AccessDeniedException("无法访问，没有 " + needPermission + " 权限！");
	}

	/**
	 * @param attribute
	 * @return
	 */
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	/**
	 * @param clazz
	 * @return
	 */
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
