package org.fedorahosted.flies.webtrans.gwt;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.apache.commons.lang.StringUtils;
import org.fedorahosted.flies.core.model.HPerson;
import org.fedorahosted.flies.gwt.model.Person;
import org.fedorahosted.flies.gwt.model.PersonId;
import org.fedorahosted.flies.gwt.rpc.AuthenticateAction;
import org.fedorahosted.flies.gwt.rpc.AuthenticateResult;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;
import org.jboss.seam.web.ServletContexts;

@Name("webtrans.gwt.AuthenticateHandler")
@Scope(ScopeType.STATELESS)
public class AuthenticateHandler implements ActionHandler<AuthenticateAction, AuthenticateResult> {

	@Logger Log log;
	
	@In Session session;
	
	@Override
	public AuthenticateResult execute(AuthenticateAction action, ExecutionContext context)
			throws ActionException {
		log.info("Authenticating {0}", action.getUsername());
		
		Identity.instance().getCredentials().setUsername(action.getUsername());
		Identity.instance().getCredentials().setPassword(action.getPassword());
		Identity.instance().tryLogin();
		
		if(Identity.instance().isLoggedIn()) {
			String sessionId = ServletContexts.instance().getRequest().getSession().getId();
			
			HPerson authenticatedPerson = (HPerson) Contexts.getSessionContext().get("authenticatedPerson");
			Person person = new Person( new PersonId(action.getUsername()), authenticatedPerson.getName());
			
			// TODO pass along permissions and roles
			
			return new AuthenticateResult(sessionId, person);
		}
		else {
			return AuthenticateResult.FAILED;
		}
	}

	@Override
	public Class<AuthenticateAction> getActionType() {
		return AuthenticateAction.class;
	}

	@Override
	public void rollback(AuthenticateAction action, AuthenticateResult result,
			ExecutionContext context) throws ActionException {
	}
	
}
@@ -302,32 +302,82 @@
 .model.HPerson;%0A
+import org.fedorahosted.flies.gwt.auth.SessionId;%0A
 import org.fedor
@@ -1586,21 +1586,24 @@
 ) %7B%0A%09%09%09S
-tring
+essionId
  session
@@ -1611,74 +1611,29 @@
 d = 
-ServletContexts.instance().getRequest().get
+retrieve
 Session
-().get
 Id();%0A
-%09%09%09%0A
 %09%09%09H
@@ -1988,16 +1988,156 @@
 ;%0A%09%09%7D%0A%09%7D
+%0A%09%0A%09public static SessionId retrieveSessionId() %7B%0A%09%09return new SessionId(ServletContexts.instance().getRequest().getSession().getId());%0A%09%7D%0A%09
 %0A%0A%09@Over

use sessionId in AuthenticateAction