package de.snailshell.consensus.demo.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import de.snailshell.consensus.demo.Constants;
import de.uka.ipd.consensus.foundation.schema.User;
import de.uka.ipd.consensus.foundation.user.UserManager;

/**
 * @author Thomas Much
 * @version 2006-06-14
 */
public class LoginAction extends BasisAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String benutzername = ((DynaActionForm)form).getString("benutzername");
		String passwort     = ((DynaActionForm)form).getString("passwort");
		
		((DynaActionForm)form).set("passwort","");

		UserManager manager = this.getUserManager();

		User user = manager.login(benutzername, passwort);

		// no exception, "user" valid

		HttpSession session = request.getSession(false);

		if (session != null) {
			User old = (User)session.getAttribute( Constants.SESSION_ATTR_USER );

			if ((old != null) && old.isLoggedOn()) {
				manager.logout( old );
			}

			session.invalidate();
		}

		session = request.getSession(true);

		session.setAttribute( Constants.SESSION_ATTR_USER, user );

		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}

}
