/**
 * 
 */
package org.ajax4jsf.portlet.seam;

import static org.jboss.seam.ScopeType.SESSION;
import static org.jboss.seam.annotations.Install.APPLICATION;

import java.security.Principal;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.security.auth.login.LoginException;

import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.security.Identity;

/**
 * @author asmirnov
 * 
 */
//@Name("org.jboss.seam.security.identity")
//@Scope(SESSION)
//@BypassInterceptors
//@Install(precedence = APPLICATION, classDependencies = "javax.portlet.Portlet")
//@Startup
public class PortalIdentity extends Identity {

	public PortalIdentity() {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#authenticate()
	 */
	@Override
	public void authenticate() throws LoginException {
		if (!isLoggedIn()) {
			throw new LoginException();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#hasPermission(java.lang.String,
	 *      java.lang.String, java.lang.Object[])
	 */
	@Override
	public boolean hasPermission(String name, String action, Object... arg) {
		// TODO Auto-generated method stub
		return super.hasPermission(name, action, arg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#getPrincipal()
	 */
	@Override
	public Principal getPrincipal() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getUserPrincipal();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#getUsername()
	 */
	@Override
	public String getUsername() {
		String userName = null;
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (null != facesContext) {
			ExternalContext externalContext = facesContext.getExternalContext();
			if (null != externalContext.getUserPrincipal()) {
				userName = externalContext.getRemoteUser();
			}
		}
		return userName;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#hasRole(java.lang.String)
	 */
	@Override
	public boolean hasRole(String role) {
		return FacesContext.getCurrentInstance().getExternalContext()
				.isUserInRole(role);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#isLoggedIn()
	 */
	@Override
	public boolean isLoggedIn() {
		return null != getPrincipal();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Identity#isLoggedIn(boolean)
	 */
	@Override
	public boolean isLoggedIn(boolean attemptLogin) {
		return isLoggedIn();
	}

}
