/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.server.realm;

import org.bodington.server.realm.Authenticator;
import java.util.Properties;

import org.apache.log4j.Logger;

import org.bodington.database.PrimaryKey;
import org.bodington.server.BuildingServerException;
import org.bodington.server.realm.User;

/**
 * The Authenticator for WebAuth Users.
 * @see org.bodington.server.realm.WebAuthUser
 * @author Colin Tatham
 */
public class WebAuthAuthenticator implements Authenticator
{
    
    private static Logger log = Logger.getLogger(WebAuthAuthenticator.class);
    
    /** indicates whether user is authenticated */
    private boolean authenticated = false;

    /** indicates whether current credentials have been used for authentication */
    private boolean lookup_attempted = false;

    /** Bodington user ID of user */
    private PrimaryKey user_id = null;

    /** Authentication credentials */
    private Properties credentials;

    /** Details of why authentication failed */
    private String error = "";

    /**
     * Authenticator Alias.
     */
    public static final String ALIAS = "webauth";

    public void setAuthenticationCredentials(Properties credentials)
        throws AuthenticationException
    {
        if (credentials == null)
            throw new AuthenticationException("No credentials supplied");

        this.credentials = credentials;
        lookup_attempted = false;
    }

    /**
     * Does the authentication
     */
    private void authenticate() throws AuthenticationException
    {
        if (lookup_attempted) return;

        String user_name;
        authenticated = false;

        if (credentials == null)
            throw new AuthenticationException(
                "Error, attempt to authenticate without credentials.");

        user_name = credentials.getProperty("webauth_user_name");
        
        // Check that the correct session initializer has been used.
        if ( !Boolean.TRUE.equals(credentials.get(WebAuthAuthenticator.class)))
            return;

        if (user_name != null && user_name.length() > 0)
        {
            try
            {
                WebAuthUser webAuthUser = WebAuthUser.findWebAuthUserByUserName(user_name);
                if (webAuthUser != null)
                {
                	User user = webAuthUser.getUser();
                	
                	if (user != null)
                	{
                		this.user_id = user.getUserId();
                		authenticated = true;
                	}
                }
                else
                {
                    error = "Username used in WebAuth not found in local database.";
                    log.warn("Authentication Failed: "+ user_name+
                        " used in WebAuth not found in local database");
                }
                
            }
            catch (BuildingServerException bs)
            {
                log.error( bs.getMessage(), bs);
                error = "Error occurred while attempting username lookup in local database.";
            }
        }
        else
            error = "WebAuth username not found in request.";

        /*
         * indicates that current credentials have been used in a lookup
         * attempt:
         */
        lookup_attempted = true;
    }

    /**
     * were the credentials accepted and validated?
     */
    public boolean isAuthenticated() throws AuthenticationException
    {
        authenticate();
        return authenticated;
    }

    /**
     * is the user a known person?
     */
    public boolean isAnonymous() throws AuthenticationException
    {
        return false;
    }

    /**
     * Get text of last error.
     */
    public String getAuthenticationError() throws AuthenticationException
    {
        authenticate();
        return error;
    }

    /**
     * Get the id of the user who authenticated
     */
    public PrimaryKey getAuthenticatedUserId() throws AuthenticationException
    {
        authenticate();
        return user_id;
    }

    /**
     * This will throw an exception as user cannot change webauth password from
     * within Bodington.
     */
    public void changeCredentials(Properties credentials)
        throws AuthenticationException
    {
        error = "Cannot change credentials as login method uses "
            + "Webauth. You must do this elsewhere. ";
        throw new AuthenticationException("Cannot change credentials");
    }

}
