package com.ora.jsp.servlets;
import java.io.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ora.jsp.beans.emp.*;
/**
* This class performs authentication in the Project Billboard
* application.
*
* @author Hans Bergsten, Gefion software <hans@gefionsoftware.com>
* @version 1.0
*/
public class AuthenticateAction implements Action {
private ActionUtils utils = new ActionUtils();
/**
* Autheticates a user with help from the EmployeeRegistryBean,
* using the "userName" and "password" request parameters.
* If the user can be authenticated, the "validUser" session
* attribute is set to an instance of the EmployeeBean, to
* serve as an authentication token in this application.
* <p>
* Cookies with the user name and password are set or reset
* as specified by the "remember" request parameter.
*/
public void perform(HttpServlet servlet, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String userName = request.getParameter("userName");
if (userName == null) {
throw new ServletException("Missing User Name");
}
String password = request.getParameter("password");
if (password == null) {
throw new ServletException("Missing Password");
}
try {
EmployeeRegistryBean empReg = (EmployeeRegistryBean)
servlet.getServletContext().getAttribute("empReg");
boolean isRegistered = empReg.authenticate(userName, password);
if (isRegistered) {
EmployeeBean emp = empReg.getEmployee(userName);
HttpSession session = request.getSession();
session.setAttribute("validUser", emp);
// Set or "delete" cookies, as requested
Cookie userNameCookie = new Cookie("userName", userName);
Cookie passwordCookie = new Cookie("password", password);
int maxAge = 2592000;
if (request.getParameter("remember") == null) {
maxAge = 0;
}
userNameCookie.setMaxAge(maxAge);
passwordCookie.setMaxAge(maxAge);
response.addCookie(userNameCookie);
response.addCookie(passwordCookie);
// Redirect to the originally requested URL or main
String next = request.getParameter("origURL");
if (next == null || next.length() == 0) {
next = utils.getShowPageURL(request, "main.jsp");
}
response.sendRedirect(next);
}
else {
String loginURL = "login.jsp" +
"?errorMsg=" +
URLEncoder.encode("Invalid User Name or Password");
response.sendRedirect(loginURL);
}
}
catch (SQLException e) {
throw new ServletException("Database error", e);
}
}
} |