/*
 * $Id: Logon.gv 481833 2006-12-03 17:32:52Z niallp $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.ModuleException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.apps.scriptingmailreader.*;

form = struts.form;

def getUser(database, username, password, errors) {
    
    user = null;
    if (database == null){
        errors.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("error.database.missing"));
    }
    else {
        user = database.findUser(username);
        if ((user != null) && !user.getPassword().equals(password)) {
            user = null;
        }
        if (user == null) {
            errors.add(
                ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.password.mismatch"));
        }
    }
    return user;
}

def saveUser(request, user) {
 
    session = request.getSession();
    session.setAttribute(Constants.USER_KEY, user);
    if (log.isDebugEnabled()) {
        log.debug(
            "LogonAction: User '"
                + user.getUsername()
                + "' logged on in session "
                + session.getId());
    }

}

// Local variables
errors = new ActionErrors();
username = PropertyUtils.getSimpleProperty(form, "username");
password = PropertyUtils.getSimpleProperty(form, "password");
database = application.getAttribute(Constants.DATABASE_KEY);

// Retrieve user
user = getUser(database,username,password,errors);

// Save (or clear) user object
saveUser(request,user);

// Report back any errors, and exit if any
if (!errors.isEmpty()) {
    struts.action.saveErrors(request, errors);
    struts.setForward(struts.mapping.getInputForward());
}

// Otherwise, return "success"
struts.setForwardName(Constants.SUCCESS);
