package com.uas.platform.b2b.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

/**
 * 在可信赖的情况下，直接创建一个有效Authentication
 * 
 * @author yingp
 *
 */
public class TrustedAuthenticationToken implements Authentication {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6121839379503504657L;
	private final Collection<GrantedAuthority> authorities;
	private boolean authenticated = false;
	private final Object principal;

	public TrustedAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
		this.principal = principal;
		if (authorities == null) {
			this.authorities = AuthorityUtils.NO_AUTHORITIES;
			return;
		}
		for (GrantedAuthority a : authorities) {
			if (a == null) {
				throw new IllegalArgumentException("Authorities collection cannot contain any null elements");
			}
		}
		ArrayList<GrantedAuthority> temp = new ArrayList<GrantedAuthority>(authorities.size());
		temp.addAll(authorities);
		this.authorities = Collections.unmodifiableList(temp);
		this.authenticated = true;
	}

	@Override
	public String getName() {
		return String.valueOf(this.principal);
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.authorities;
	}

	@Override
	public Object getCredentials() {
		return null;
	}

	@Override
	public Object getDetails() {
		return null;
	}

	@Override
	public Object getPrincipal() {
		return this.principal;
	}

	@Override
	public boolean isAuthenticated() {
		return this.authenticated;
	}

	@Override
	public void setAuthenticated(boolean paramBoolean) throws IllegalArgumentException {
		this.authenticated = paramBoolean;
	}

}
