import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.*;
import java.sql.*;

public class LoginServlet extends HttpServlet
{
	public void init(ServletConfig config) throws ServletException
	{
		try
		{
			// open the database connections and prepare the statment
			JDBCHelper.initialize();
		}
		catch ( SQLException sqlE)
		{
			throw new ServletException( sqlE.getMessage() );
		}
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		// check to see if a session has already been created for this user
		//		don't create a new session yet.
		HttpSession session = request.getSession( false);

		String requestedPage = request.getParameter(Constants.REQUEST);

		if ( session == null)
		{

			// retrieve the username and password from the request
			String sUserName = request.getParameter( Constants.USERNAME);
			String sPassword = request.getParameter( Constants.PASSWORD);

			// AUTHENTICATE the user
			boolean isAuthenticated = authenticateUser( sUserName, sPassword);

			if ( isAuthenticated)
			{
				// create a session
				session = request.getSession( true);

				// convert the boolean to a Boolean
				Boolean booleanIsAuthenticated = new Boolean( isAuthenticated);

				// store the boolean value to the session
				session.putValue( Constants.AUTHENTICATION, booleanIsAuthenticated);

				// redirect to the entered page
				response.sendRedirect( requestedPage);

			}
			else
			{
				// redirect to the login servlet (passing parameter)
				response.sendRedirect( Constants.LOGIN + requestedPage);
			}
		}
		else
		{
			// if your business logic allows users to have sessions without
			// being logged in, determine the proper course of action


			// otherwise, this is an error condition (for the purpose of this example)

			// kill the session
			session.invalidate();

			// throw an exception
			throw new ServletException("Can't have a session unless you've logged in");

		}
	}

	private static boolean authenticateUser(String sUserName, String sPassword )
	{
		return JDBCHelper.authenticateUser(sUserName, sPassword);
	}
}
