/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.jetspeed.services.security.turbine;

import javax.servlet.ServletConfig;

import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.turbine.util.Log;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;

import org.apache.jetspeed.services.security.PortalAuthentication;
import org.apache.jetspeed.services.security.LoginException;

import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.UserNamePrincipal;

import org.apache.jetspeed.services.JetspeedUserManagement;
import org.apache.jetspeed.services.security.JetspeedSecurityService;
import org.apache.jetspeed.services.security.FailedLoginException;
import org.apache.jetspeed.services.security.CredentialExpiredException;
import org.apache.jetspeed.services.security.UnknownUserException;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.security.JetspeedSecurityCache;
import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.turbine.services.rundata.RunDataService;

/**
 * <p> The <code>TurbineAuthentication</code> class is a default Jetspeed
 * security provider, implementing the <code>PortalAuthentication</code> interface.
 * It provides authentication services using a User database table mimicking the 
 * legacy Turbine-2 user table. 
 *
 * This service does not use any of the Turbine security or user management classes.
 * 
 * @author <a href="mailto:david@bluesunrise.com">David Sean Taylor</a>
 * @author <a href="mailto:morciuch@apache.org">Mark Orciuch</a> 
 * @version $Id: TurbineAuthentication.java,v 1.5 2003/03/04 00:05:12 sgala Exp $
 */
                                                             
public class TurbineAuthentication  extends    TurbineBaseService
                                    implements PortalAuthentication
{
    /** The JetspeedRunData Service. */
    private JetspeedRunDataService runDataService = null;

    private final static String CONFIG_ANONYMOUS_USER = "user.anonymous";
    String anonymousUser = "anon";
    private final static String CACHING_ENABLE = "caching.enable";
    private boolean cachingEnable = true;

    private final static String CONFIG_PASSWORD_EXPIRATION_PERIOD = "password.expiration.period";

    private int expirationPeriod = 0;

    /**
     * Given a public credential(username) and private credential(password), 
     * perform authentication. If authentication succeeds, a <code>JetspeedUser</code> 
     * is returned representing the authenticated subject.
     *
     * @param username a public credential of the subject to be authenticated.
     * @param password a private credentialof the subject to be authenticated.
     * @return a <code>JetspeedUser</code> object representing the authenticated subject.
     * @exception LoginException when general security provider failure.
     * @exception FailedLoginException when the authentication failed.
     * @exception AccountExpiredException when the subject's account is expired.
     * @exception CredentialExpiredException when the subject's credential is expired.
     */
    public JetspeedUser login(String username, String password)
        throws LoginException
    {
        JetspeedUser user = null;

        username = JetspeedSecurity.convertUserName(username);
        password = JetspeedSecurity.convertPassword(password);
       
        try
        {
            user = JetspeedUserManagement.getUser(new UserNamePrincipal(username));
            password = JetspeedSecurity.encryptPassword(password);
        }                            
        catch (UnknownUserException e)
        {
            throw new FailedLoginException(e.toString());
        }
        catch (JetspeedSecurityException e)
        {
            throw new LoginException(e.toString());
        }

        if(!user.getPassword().equals(password))
        {
            throw new FailedLoginException("Credential authentication failure");
        }  

        // Check for password expiration
        if (this.expirationPeriod > 0)
        {
            Date passwordLastChangedDate = user.getPasswordChanged();
            Date passwordExpireDate = null;
            if (passwordLastChangedDate != null) {
                GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance();
                gcal.setTime(passwordLastChangedDate);
                gcal.add(GregorianCalendar.DATE, this.expirationPeriod);
                passwordExpireDate = gcal.getTime();
                if (Log.getLogger().isDebugEnabled())
                {
                    Log.debug("TurbineAuthentication: password last changed = " + passwordLastChangedDate.toString() +
                              ", password expires = " + passwordExpireDate.toString());
                }
            }

            if (passwordExpireDate == null || (new Date().getTime() > passwordExpireDate.getTime())) {
                throw new CredentialExpiredException("Password expired");
            }

        }

        // Mark the user as being logged in.
        user.setHasLoggedIn(new Boolean(true));

        // Set the last_login date in the database.
        try
        {
            user.updateLastLogin();
            putUserIntoContext(user);
            if (cachingEnable)
            {
                JetspeedSecurityCache.load(username);
            }
        }
        catch (Exception e)
        {
            putUserIntoContext(JetspeedSecurity.getAnonymousUser());
            throw new LoginException("Failed to update last login ", e);
        }

        return user;
        
    }

    /**
     * Automatically authenticates and retrieves the portal anonymous user.
     *
     * @return a <code>JetspeedUser</code> object representing the authenticated subject.
     * @exception LoginException if the authentication fails.
     */
    public JetspeedUser getAnonymousUser()
        throws LoginException
    {
        JetspeedUser user = null;
        try
        {
            user = JetspeedUserManagement.getUser(new UserNamePrincipal(anonymousUser));
            user.setHasLoggedIn(new Boolean(false));
            putUserIntoContext(user);
            if (cachingEnable)
            {
                JetspeedSecurityCache.load(user.getUserName());
            }
        }
        catch (JetspeedSecurityException e)
        {
            throw new LoginException("Failed to get anonymous user: " + e);
        }
        return user;
    }

    /**
     * Logout the <code>JetspeedUser</code>.
     *
     * The logout procedure my may include removing/destroying
     * <code>Principal</code> and <code>Credential</code> information
     * if relevant to the security provider.
     *
     * @exception LoginException if the logout fails.
     */
    public void logout()
        throws LoginException
    {
        try
        {
            //if (cachingEnable)
            //{
            //    JetspeedSecurityCache.unload(getUserFromContext().getUserName());
            //}
            getAnonymousUser();
        }
        catch (Exception e)
        {
            throw new LoginException("Exception logging user out ", e );
        }
    }

    /**
     * This is the early initialization method called by the 
     * Turbine <code>Service</code> framework
     * @param conf The <code>ServletConfig</code>
     * @exception throws a <code>InitializationException</code> if the service
     * fails to initialize
     */
    public synchronized void init(ServletConfig conf) 
        throws InitializationException 
    {
        if (getInit()) return;

        super.init(conf);

        // get configuration parameters from Jetspeed Resources
        ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
                                                     .getResources(JetspeedSecurityService.SERVICE_NAME);

        anonymousUser = serviceConf.getString(CONFIG_ANONYMOUS_USER, anonymousUser);
        cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, cachingEnable );
        expirationPeriod = serviceConf.getInt( this.CONFIG_PASSWORD_EXPIRATION_PERIOD, 0 );

        this.runDataService =
            (JetspeedRunDataService)TurbineServices.getInstance()
                .getService(RunDataService.SERVICE_NAME);


        setInit(true);
     }

    ////////////////////////////////////////////////////////////////////////////

    protected JetspeedRunData getRunData()
    {
        JetspeedRunData rundata = null;
        if (this.runDataService != null)
        {
            rundata = this.runDataService.getCurrentRunData();
        }
        return rundata;
    }

    protected JetspeedUser getUserFromContext()
    {
        JetspeedRunData rundata = getRunData();
        JetspeedUser user = null;
        if (rundata != null)
        {
            user = (JetspeedUser)rundata.getUser();
        }
        return user;
    }

    protected JetspeedRunData putUserIntoContext(JetspeedUser user)
    {
        JetspeedRunData rundata = getRunData();
        if (rundata != null)
        {
            rundata.setUser(user);
            rundata.save();
        }
        return rundata;
    }


}