/***
 * Excerpted from "Domain-Driven Design Using Naked Objects",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/dhnako for more book information.
***/
package com.pragprog.dhnako.carserv.wicket.app;

import java.util.List;

import org.apache.wicket.Request;
import org.apache.wicket.Session;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.nakedobjects.metamodel.authentication.AuthenticationSession;
import org.nakedobjects.runtime.authentication.AuthenticationManager;
import org.nakedobjects.runtime.authentication.AuthenticationRequestPassword;
import org.nakedobjects.runtime.context.NakedObjectsContext;

public class NakedObjectsAuthenticatedWebSession extends AuthenticatedWebSession {
	
	private static final long serialVersionUID = 1L;
	
	public static NakedObjectsAuthenticatedWebSession get() {
		return (NakedObjectsAuthenticatedWebSession) Session.get();
	}
	
	private AuthenticationSession authenticationSession;

	public NakedObjectsAuthenticatedWebSession(Request request) {
		super(request);
	}

	@Override
	public boolean authenticate(final String username, final String password) {
		AuthenticationRequestPassword authenticationRequest = new AuthenticationRequestPassword(username, password);
		authenticationSession = getAuthenticationManager().authenticate(authenticationRequest);
		return authenticationSession != null;
	}
	
	public AuthenticationSession getAuthenticationSession() {
		return authenticationSession;
	}

	@Override
	public Roles getRoles() {
		if (!isSignedIn()) {
			return null;
		} 
		List<String> roles = authenticationSession.getRoles();
		return new Roles(roles.toArray(new String[]{}));
	}
	
	private static AuthenticationManager getAuthenticationManager() {
		return NakedObjectsContext.getAuthenticationManager();
	}
	
}