/* ======================================================================
   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.servlet;

import java.util.Properties;

import org.bodington.server.BuildingServerException;
import org.bodington.server.NavigationSession;
import org.bodington.server.realm.WebAuthAuthenticator;

/**
 * Class that handles session initialization via WebAuth.
 * Really HttpSession should support a session termination time as this would
 * be nicer than having really long max inactivity settings.
 * @see <a href="http://webauthv3.stanford.edu/">WebAuth</a>
 * @author Alexis O'Connor
 * @author buckett
 */
public class WebAuthSessionInitializer extends AbstractSessionInitializer
{
    public static final String WEBAUTH_USER_PARAM_NAME = "WEBAUTH_USER";
    public static final String WEBAUTH_EXPIRATION_PARAM_NAME = "WEBAUTH_TOKEN_EXPIRATION";
    public static final String AUTH_TYPE_PARAM_NAME = "AUTH_TYPE";
    public static final String WEBAUTH_AUTH_TYPE = "WebAuth";
    public static final String UNSET = "<UNSET>";
    
    // All the constants here are in seconds as that is what the servlet spec deals with.
    // 2 hours.
    private static final int DEFAULT_SESSION = 7200;
    // 1 minute
    private static final int MINIMUM_SESSION = 60;
    // 12 Hours
    private static final int MAXIMUM_SESSION = 43200;

    protected boolean initialize( Request request, 
        HttpSession session, NavigationSession navigation )
    {
        try
        {
            String webauthUser = (String)request.getAttribute( 
                WEBAUTH_USER_PARAM_NAME );
            String type = (String)request.getAttribute( AUTH_TYPE_PARAM_NAME );

            if ( !UNSET.equals( webauthUser ) && WEBAUTH_AUTH_TYPE.equals( type) )
            {
                Properties props = new Properties();
                props.setProperty( "webauth_user_name", webauthUser );
                // This prevents other session initializers from (ab)using the
                // WebAuth authenticator.
                props.put(WebAuthAuthenticator.class, Boolean.TRUE);
                navigation.setAuthenticationCredentials( props, WebAuthAuthenticator.ALIAS );
                return true;
            }
        }
        catch ( BuildingServerException e )
        {
        }

        return false;
    }

    protected void postInitialize( HttpSession session, Request request )
    {
        super.postInitialize( session, request );
        session.setAuthType( WEBAUTH_AUTH_TYPE );
        
        // Work out how long to keep the session open for based on WebAuth
        int sessionDuration = DEFAULT_SESSION;
        try
        {
            long expires = Integer.parseInt((String) request
                .getAttribute(WEBAUTH_EXPIRATION_PARAM_NAME));
            long current = System.currentTimeMillis()/1000;
            sessionDuration = (int)((expires - current));
            if ( sessionDuration < MINIMUM_SESSION)
                sessionDuration = MINIMUM_SESSION;
            if (sessionDuration > MAXIMUM_SESSION)
                sessionDuration = MAXIMUM_SESSION;
        }
        catch (NumberFormatException nfe)
        {}
        session.setMaxInactiveInterval(sessionDuration);
    }

    /**
     * Find a session associated with the request. This implementation of the
     * method calls the version in its superclass and if that method returns
     * <code>null</code> this will just create a new one.
     * @param request {@inheritDoc}
     */
    protected HttpSession findHttpSession( Request request )
    {
        HttpSession session = super.findHttpSession( request );
        return (session == null) 
            ? (org.bodington.servlet.HttpSession) request.getSession( true ) 
            :  session;
    }
}
