package com.cogix.vwf;
/**
 * (c) 2001-7 cogix Corporation All Rights Reserved
 * May be used and modified when used with a licensed copy of ViewsFlash
 */

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Example of how to replace J2EE getRemoteUser() authentication with a custom authentication system
 * This example assumes that the logged in user ID is stored in a cookie
 */

public class AuthenticationSkeleton extends RequestNotifier {

    AuthenticationSkeleton () {}

    /*
     * Use this for any global initialization required.
     * This class is instantiated at servlet initialization time, and this method is called only once right after construction
     *
     */
    void init (ServletConfig conf) throws ServletException {
        super.init (conf);
    }

    /*
   * Called during servlet destroy()
    */
    void destroy () throws ServletException {
        super.destroy();
    }

    /*
    * Called at the beginning of request processing
    * if user is already authenticated, save their user ID
    * If not, redirect or present a login form
    *
    */

    public void onRequest ( ThisCall thiscall ) throws ServletException {

        HttpServletRequest request = thiscall.req;
        HttpServletResponse response = thiscall.res;

        /*
             Determine if the URL requires simulated J2EE authentication or not.
             In a J2EE environment, this is done using web.xml security-constraint elements; be sure to remove such constraints from web.xml

             servlet/vfadmin is the application, and require authentication.  appsecurity=user must be set in viewflash.properties
             servlet/vfauth is for questionnaires that use the Basic authentication option; these require authentication
             servlet/viewsflash is for questionnaires and other commands that do not use J2EE authentication. Do not authenticate these.
         */

        String requesturi = request.getRequestURI();   //  ViewsFlash/servlet/vfadmin, etc
        if ( requesturi == null ||  requesturi.endsWith("servlet/viewsflash") )
            return; //  no authentication required

        //  Determine which is the correct logged in state.
        String cookiename = "COOKIE";
        String userid;
        Cookie[] c = request.getCookies();
        for ( int k = 0 ; c!= null &&  k < c.length; k++ ) {
            Cookie ck = c [k];
            if ( cookiename.equals(ck.getName())) {
                userid = ck.getValue();
                thiscall.userid = userid;
                //  Tell ViewsFlash that this is the user ID of the logged in user.
                // ViewsFlash uses this value instead of request.getRemoteUser();

                //  Optional: enable this to allow requesting this authentication method explicitly in Security page,
                // in place of "Portal". See getUIText() , below.  There is no visible benefit in allowing this.
                //  thiscall.req.setAttribute (RequestNotifierId, "");
                return;
            }
        }

        //  User is not logged in.
        //  Two ways to present the user with a log in  form.
        //  Method 1: use a redirect
        //  Method 2: write the login form now
        boolean bRedirectMethod = true;
        boolean bWriteTheForm  = false;

        if ( bRedirectMethod ) {
            //  Redirect to a login form, passing along the original request.
            // The login form, when successful, should set the cookie and redirect to the original requests' URL
            String originalurl = request.getRequestURL().toString();  //  Ok in Java 1.4 and 1.5
            String redirecturl = "http://www.yourserver.com/Authenticate?redirect=" + originalurl;

            redirecturl = response.encodeRedirectURL (redirecturl);
            thiscall.bRediraftersetattribute = true;    //  signals redirect wanted immediately upon return
            thiscall.rediraftersetattribute = redirecturl ;  //  where to redirect to
        }
        else if ( bWriteTheForm ) {
            PrintWriter out = thiscall.out;
            out.print("The login form");
            //  do not close out
            thiscall.bEndRequestProcessing = true;  //  ends request processing immediately upon return
        }
    }

    public String getUIText () {
        return "<b>Custom authentication</b>";
    }

}
