/*
 * ApplicationLogin.java 1.00 27-Feb-2001
 *
 * Copyright 2000-2001 by Oracle Corporation
 * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
 * All rights reserved.
 */
package oracle.portal.sample.v2.devguide.externalApp;

import java.lang.reflect.*;
import java.io.*;
import java.text.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import oracle.portal.provider.v2.*;
import oracle.portal.provider.v2.externalApp.*;
import oracle.portal.provider.v2.render.PortletRenderRequest;

public class ApplicationLogin
{
    private Cookie mCookie;
    private String mUser;
    private HttpServletRequest mRequest;
    private HttpServletResponse mResponse;
    private boolean mLoggedIn = false;
    private static final String[] VALIDUSERNAMES={"user1","user2","user3", "user4", "user5"};
    private static final String[] VALIDPASSWORDS={"pass1","pass2","pass3", "pass4", "pass5"};
    private static final String COOKIENAME="flightcookie";

    /**
     *  Constructor
     *
     *  Use the HttpServletRequest and Response to set up some initial
     *  pieces of data which are needed.
     *
     *  @param req   Servlet Request
     *  @param res   Servlet Response
     */
    public ApplicationLogin(HttpServletRequest req, HttpServletResponse res)
    {
        mResponse = res;
        mRequest = req;

        Cookie[] cookieList = mRequest.getCookies();
        if(cookieList == null)
        {
            return;
        }
        for (int i = cookieList.length - 1; i >= 0; i--)
        {
            //Look for the Flight Cookie
            if (cookieList[i].getName().equalsIgnoreCase(COOKIENAME))
            {
                mCookie = cookieList[i];
                mUser = mCookie.getValue();
                mLoggedIn = true;
                break;
            }
        }
    }

    /**
     *  Constructor for ApplicationLogin
     *
     *  This overload of the constructor was needed to support
     *  the different object for the External Web Application.
     *
     *  @param  pr  is a PortletRenderRequest which can be seen in the
     *  JPDK API Documentation.
     */
    public ApplicationLogin(PortletRenderRequest pr)
    {
        Object[] cookieList = pr.getCookies();
        if(cookieList == null)
        {
            return;
        }
        Cookie cookie = null;
        for (int i = cookieList.length - 1; i >= 0; i--)
        {
            cookie = (Cookie)cookieList[i];
            if (cookie.getName().equalsIgnoreCase(COOKIENAME))
            {
                mCookie = cookie;
                mUser = mCookie.getValue();
                mLoggedIn = true;
                break;
            }
        }
    }

    /**
     *  Overloaded Constructor
     *
     *  This constructor does nothing, but create the object.
     */
    public ApplicationLogin()
    {}

    /**
     *  Perform the login for the mapped user sent from the portal
     *
     *  This method uses the external application user mapping (user/password +
     *  form field names & values) to determine if the portal user is allowed to
     *  access this application.
     *
     *  @param user mapped user information
     *  @param cookiePath server path which should be set on the cookie
     *  @return  cookie for this user.
     */
    public Cookie getApplicationCookie(ExternalPrincipal user, String cookiePath)
    {
        Cookie cookie = null;
        if (user != null)
        {
            String username = user.toString();
            String password = user.getPassword();
            for (int i=0; i<VALIDUSERNAMES.length; i++)
            {
                if (username.equalsIgnoreCase(VALIDUSERNAMES[i]) &&
                    password.equalsIgnoreCase(VALIDPASSWORDS[i]))
                {
                    System.err.println("creating  user cookie...");
                    cookie = new Cookie(COOKIENAME,username);
                    cookie.setPath(cookiePath);
                    break;
                }
            }
        }
        return cookie;
    }

    /**
     *  Return the boolean to determine if a request is logged in.
     *
     *  @return  boolean true for logged in, false if not.
     */
    public boolean isLoggedIn()
    {
        return mLoggedIn;
    }

    /**
     * Return the presently logged user.
     *
     *  @return User name from the cookie.
     */
    public String getUser()
    {
        return mUser;
    }

    /**
     *  Draw a login screen.
     *
     *  This method outputs a login screen for the user
     *  to enter their username and password for login.
     *  @param servletURL absoute path to the servlet.
     */
    public void drawLogin(String servletURL)
        throws IOException
    {
        StringBuffer server = new StringBuffer();
        //set up the server string
        server.append(mRequest.getScheme()).append("://")
            .append(mRequest.getServerName());
        int serverPort = mRequest.getServerPort();
        if (( serverPort != 80) && (serverPort!= 433))
        {
            server.append(":")
                .append(serverPort);
        }
        Writer out = mResponse.getWriter();
        out.write("<HTML>");
        out.write("<HEAD>");
        out.write("<TITLE>Flights Login</TITLE></HEAD>");
        out.write("<Body>");
        out.write("<Center>");
        out.write("<BR><b><font color=\"#33CCFF\"><font size=+1>");
        out.write("Flights Of Fancy</font></font></b><BR><BR>");
        out.write("<Form action=\""+servletURL + "\"");
        out.write(" Method=POST Name=flightlogin>");
        out.write("<B>Flight Login:</B>&nbsp;&nbsp;");
        out.write("<input type=text name=\"FlightUser\">");
        out.write("<BR><BR>");
        out.write("<B>Flight Password:</B>&nbsp;&nbsp;");
        out.write("<input type=password name=\"FlightPass\">");
        out.write("<input type=hidden NAME=\"FlightAction\" Value=\"performlogin\">");
        out.write("<BR><BR>");
        out.write("<input type=submit value=\"Submit\">");
        out.write("</Form>");
        out.write("</Center>");
        out.write("</Body>");
        out.write("</HTML>");
        out.flush();

    }

    /**
     *  Perform Login logs in the user which was submitted from a form.
     *
     *  This method is used by both the Portal External Application form, as well as the
     *  Stand alone example application.
     *
     *  @param username  Username for login.
     *  @param password  Password for login.
     *  @param dest  Destination to be redirected to.
     *  @param cookiePath server path which should be set on the cookie
     */
    public void performLogin(String username, String password, String dest, String cookiePath)
        throws IOException
    {

        StringBuffer server = new StringBuffer();

        Cookie cookie = null;
        for (int i=0; i<VALIDUSERNAMES.length; i++)
        {
            if (username.equalsIgnoreCase(VALIDUSERNAMES[i]) &&
                password.equalsIgnoreCase(VALIDPASSWORDS[i]))
            {
                cookie = new Cookie(COOKIENAME,username);
                cookie.setPath(cookiePath);
                break;
            }
        }
        if (cookie != null)
        {
            mResponse.addCookie(cookie);
        }
        mResponse.sendRedirect(dest);
    }

}
