/*
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 */


package vkc.ws.axis.handler;

import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;

import vkc.db.entities.VKCUser;
import vkc.db.helper.UserHelper;
import vkc.exception.DBException;
import vkc.exception.DisabledUserAccountException;
import vkc.exception.PasswordMismatchException;
import vkc.exception.UnknownUserException;
import vkc.util.StringUtils;

/**
 * Axis-Handler Klasse zur Überprüfung der Authentifizierung
 * von eingehenden Requests
 */
public class AuthenticationHandler extends BasicHandler {

	/**
	 * Authenticate the user and password from the msgContext
	 */
	public void invoke(MessageContext msgContext) throws AxisFault {

		try {

			String  username = StringUtils.normalize( msgContext.getUsername() );
			String  password = StringUtils.normalize( msgContext.getPassword() );
			VKCUser user     = UserHelper.authenticate( username, password, null );

			// Note: if no exception is thrown by UserHelper.authenticate,
			// the user has been successfully authenticated
			msgContext.setProperty( MessageContext.AUTHUSER, user );

		} catch ( UnknownUserException e ) {
			throw new AxisFault( "Server.Unauthorized", "Unauthorized", null, null );
		} catch ( DisabledUserAccountException e ){
			throw new AxisFault( "Server.Unauthorized", "Account is currently disabled", null, null );
		} catch ( PasswordMismatchException e ){
			throw new AxisFault( "Server.Unauthorized", "Unauthorized", null, null );
		} catch ( DBException e ) {
			throw new AxisFault( "Server.Failure", "Database access error", null, null );
		} catch ( Exception e ) {
			throw new AxisFault( "Server.Failure", "General error", null, null );
		}
	}
}
