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

 
// Java Core Classes
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Locale;
import java.io.StringWriter;

import javax.servlet.http.Cookie;

// Turbine Modules
import org.apache.velocity.context.Context;
import org.apache.turbine.TurbineConstants;
import org.apache.turbine.modules.Action;
import org.apache.turbine.modules.ActionEvent;
import org.apache.turbine.modules.ActionLoader;
import org.apache.turbine.services.localization.Localization;
import org.apache.turbine.services.velocity.TurbineVelocity;
import org.apache.turbine.services.template.TurbineTemplate;
import org.apache.turbine.util.Log;
import org.apache.turbine.util.mail.SimpleEmail;
import org.apache.turbine.util.mail.Email;
import org.apache.turbine.util.DynamicURI;
import org.apache.turbine.util.RunData;
import org.apache.jetspeed.services.TemplateLocator;


import org.apache.jetspeed.om.security.JetspeedUser;

import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.security.LoginException;
import org.apache.jetspeed.services.security.FailedLoginException;
import org.apache.jetspeed.services.security.CredentialExpiredException;
import org.apache.jetspeed.services.security.AccountExpiredException;
import org.apache.jetspeed.services.security.UnknownUserException;

/**
    This class is responsible for logging a user into the system. It is also
    responsible for making sure that the user has been marked as confirmed. 
    If the user is not marked as confirmed, then it will show them the 
    
*/
public class JLoginUser extends ActionEvent
{

    /**
    * called when the password reminder button is pressed.
    * sends a user their password
    **/
    public void doReminder( RunData rundata ) throws Exception
    {
        JetspeedRunData data = (JetspeedRunData)rundata;

        try {
            String username = data.getParameters().getString("username", "");

            JetspeedUser user = null;

            try {
                user = JetspeedSecurity.getUser(username);
            } catch (JetspeedSecurityException ignored) {
            }

            if (user == null)
            {
                data.setScreenTemplate("LoginHelp");
                data.setMessage(Localization.getString("JLOGINUSER_PASSWORDREMINDER_INVALIDUSER"));
                if (Log.getLogger().isDebugEnabled())
                    Log.debug(Localization.getString("JLOGINUSER_PASSWORDREMINDER_INVALIDUSER"));
                return;
            }

            user.setHasLoggedIn( Boolean.FALSE);
            data.setUser(user);
 
            DynamicURI url = new DynamicURI(data);

            //build body via template
            StringWriter email_body = new StringWriter();

            Context context = TurbineVelocity.getContext(data);
            context.put( "data", data );
            context.put( "user", user );
            context.put("userurl",url);
            context.put("config",new JetspeedResources());

            //determine the language to be used for the notification email
            String lang = (String)user.getPerm("language");
            String ctry = (String)user.getPerm("country");
            Locale loc = null;
            if (lang != null && ctry != null)
            {
                loc = new Locale(lang,ctry); 
            }

            String templatePath = TemplateLocator.locateEmailTemplate(data, JetspeedResources.getString("password.reminder.template"), loc);

            SimpleEmail se = new SimpleEmail();

            context.put("email",se);

            TurbineVelocity.handleRequest(context, templatePath, email_body);

            se.setMsg(email_body.toString());

            Properties props = System.getProperties();
            String mailServerMachine = JetspeedResources.getString( "mail.server" );
            props.put("mail.host", mailServerMachine );
            props.put("mail.smtp.host", mailServerMachine);

            se.send();

            data.setMessage (Localization.getString("JLOGINUSER_PASSWORDREMINDER_SENT"));
            Log.info( "Password for user " + user.getUserName() + " was sent to " + user.getEmail());
            Log.info(Localization.getString("JLOGINUSER_PASSWORDREMINDER_SENT"));
            data.setScreenTemplate("Login");
        } catch ( Exception e ) {
            data.setScreenTemplate("LoginHelp");
            String errorTitle = Localization.getString("JLOGINUSER_PASSWORDREMINDER_ERROR") ;
            String errorMessage = errorTitle + e.toString();

            Log.warn( errorMessage, e );
            data.setMessage ( errorMessage );
        }
    }


    public void doPerform( RunData rundata ) throws Exception
    {
        JetspeedRunData data = (JetspeedRunData)rundata;
        
        String username = data.getParameters().getString("username", "");
        String password = data.getParameters().getString("password", "");

        boolean newUserApproval = JetspeedResources.getBoolean("newuser.approval.enable", false);
        String secretkey = (String) data.getParameters().getString("secretkey", null);
        if ( secretkey != null )
        {

            // its the first logon - we are verifying the secretkey

            // handle the buttons on the ConfirmRegistration page
            String button1 = data.getParameters().getString ( "submit1", null );
            if ( button1 != null && button1.equalsIgnoreCase("Cancel") )
            {
                data.setScreenTemplate(TurbineTemplate.getDefaultScreen());
                return;
            }
            
            // check to make sure the user entered the right confirmation key
            // if not, then send them to the ConfirmRegistration screen            
            JetspeedUser user = JetspeedSecurity.getUser(username);

            if (user == null)
            {
                Log.warn("JLogin User: Unexpected condition : user is NULL");
                return;   
            }
            String confirm_value = user.getConfirmed();
            if ( ! secretkey.equals ( confirm_value ) && ! confirm_value.equals ( JetspeedResources.CONFIRM_VALUE ) )
            {
                if ( newUserApproval )
                {
                    data.setMessage(Localization.getString("JLOGINUSER_KEYNOTVALID"));
                    data.setScreenTemplate("NewUserAwaitingAcceptance");
                    return;
                }
                else
                {
                  if ( user.getConfirmed().equals(JetspeedResources.CONFIRM_VALUE_REJECTED))
                  {
                    data.setMessage(Localization.getString("JLOGINUSER_KEYNOTVALID"));
                    data.setScreenTemplate("NewUserRejected");
                    return;
                  }
                  else
                  {
                    data.setMessage(Localization.getString("JLOGINUSER_KEYNOTVALID"));
                    data.setScreenTemplate("ConfirmRegistration");
                    return;
                  }
                }
            }
             
            user.setConfirmed( JetspeedResources.CONFIRM_VALUE );
            JetspeedSecurity.saveUser(user);
            data.setMessage (Localization.getString("JLOGINUSER_WELCOME"));
        }
        
        JetspeedUser user = null;
        try
        {
            user = JetspeedSecurity.login(username, password);
        }
        catch (LoginException e)
        {
            data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_LOGIN));
            String message = e.getMessage() != null ? e.getMessage() : e.toString();
            data.setMessage(message);
            data.setUser(JetspeedSecurity.getAnonymousUser());
            data.getUser().setHasLoggedIn(new Boolean (false) );            

            if (e instanceof FailedLoginException)
            {
                Log.info("JLoginUser: Credential Failure on login for user: " + username);
                data.setMessage(Localization.getString("PASSWORDFORM_FAILED_MSG"));
            }
            else if (e instanceof AccountExpiredException)
            {
                Log.info("JLoginUser: Account Expired for user " + username);
            } 
            else if (e instanceof CredentialExpiredException)
            {
                Log.info("JLoginUser: Credentials expired for user: " + username);
                data.setScreenTemplate(
                    JetspeedResources.getString(JetspeedResources.CHANGE_PASSWORD_TEMPLATE, "ChangePassword")
                    );
                data.setMessage(Localization.getString("PASSWORDFORM_EXPIRED_MSG"));
                data.getParameters().setString("username", username);
            } 

            return;
        }

        if (user.getDisabled())
        {
            data.setMessage(Localization.getString("JLOGINUSER_ACCOUNT_DISABLED"));
            data.setScreenTemplate(JetspeedResources.getString("logon.disabled.form"));
            data.getUser().setHasLoggedIn(new Boolean (false) );
            return;
        }

        // check for being confirmed before allowing someone to finish logging in

        if ( data.getUser().hasLoggedIn())
        {
            if  (JetspeedSecurity.isDisableAccountCheckEnabled())
            {
                // dst: this needs some refactoring. I don't believe this api is necessary
                JetspeedSecurity.resetDisableAccountCheck(data.getParameters().getString("username", ""));
            }        

            String confirmed = data.getUser().getConfirmed();
            if (confirmed == null || !confirmed.equals(JetspeedResources.CONFIRM_VALUE ))
            {
                if (confirmed != null && confirmed.equals(JetspeedResources.CONFIRM_VALUE_REJECTED))
                {
                  data.setMessage(Localization.getString("JLOGINUSER_KEYNOTVALID"));
                  data.setScreenTemplate("NewUserRejected");
                  data.getUser().setHasLoggedIn(new Boolean (false) );
                  return;
                }
                else
                {
                  data.setMessage(Localization.getString("JLOGINUSER_CONFIRMFIRST"));
                  data.setScreenTemplate("ConfirmRegistration");
                  data.getUser().setHasLoggedIn(new Boolean (false) );
                  return;
                }
            }

            // user has logged in successfully at this point
  
            boolean automaticLogonEnabled = JetspeedResources.getBoolean("automatic.logon.enable", false);
            if (automaticLogonEnabled)
            {
              //Does the user want to use this facility?
              boolean userRequestsRememberMe = data.getParameters().getBoolean("rememberme",false);
              if (userRequestsRememberMe)
              {
                //save cookies on the users machine.
                int maxage = JetspeedResources.getInt("automatic.logon.cookie.maxage",-1);
                String comment = JetspeedResources.getString("automatic.logon.cookie.comment","");
                String domain = JetspeedResources.getString("automatic.logon.cookie.domain");
                String path = JetspeedResources.getString("automatic.logon.cookie.path","/");

                if (domain == null)
                {
                  String server = data.getServerName();
                  domain = "." + server;
                }

                String loginCookieValue = null;

                if ( JetspeedResources.getString("automatic.logon.cookie.generation","everylogon").equals("everylogon") )
                {
                  loginCookieValue = ""+Math.random();
                  data.getUser().setPerm("logincookie",loginCookieValue);
                  JetspeedSecurity.saveUser( data.getJetspeedUser() );
                } 
                else 
                {
                  loginCookieValue = (String)data.getUser().getPerm("logincookie");
                  if (loginCookieValue == null || loginCookieValue.length() == 0)
                  {
                    loginCookieValue = ""+Math.random();
                    data.getUser().setPerm("logincookie",loginCookieValue);
                    JetspeedSecurity.saveUser( data.getJetspeedUser() );
                  }
                }

                Cookie userName = new Cookie("username",data.getUser().getUserName());
                Cookie loginCookie = new Cookie("logincookie",loginCookieValue);

                userName.setMaxAge(maxage);
                userName.setComment(comment);
                userName.setDomain(domain);
                userName.setPath(path);

                loginCookie.setMaxAge(maxage);
                loginCookie.setComment(comment);
                loginCookie.setDomain(domain);
                loginCookie.setPath(path);

                data.getResponse().addCookie(userName);
                data.getResponse().addCookie(loginCookie);

              }
                    
            }

        }
        else
        {
            // disable user after a configurable number of strikes
            if  (JetspeedSecurity.isDisableAccountCheckEnabled())
            {
                boolean disabled = JetspeedSecurity.checkDisableAccount(data.getParameters().getString("username", ""));
                if (disabled)
                {
                    data.setMessage(Localization.getString("JLOGINUSER_ACCOUNT_DISABLED"));
                    data.setScreenTemplate(JetspeedResources.getString("logon.disabled.form"));
                    data.getUser().setHasLoggedIn(new Boolean (false) );
                }
            }
        }

    }

}
