john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

servlet login session template

// 2012-05-21 johnpfeiffer (servlet load on Start for Password to Log) requires Password , DAO's and (data) Model Objects (as POJO's)

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AppProperties extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final String CLASSVERSION = "0.5";
    Password loginPassword = null;
    private static String servletURL;
    private ArrayList <String> authorizedTokens;

    private static final String PARAMLOGINUSERPASSWORD = "userPassword";
    private static final String PARAMLOGINBUTTON = "login";
    private static final String PARAMLOGOUTBUTTON = "logout";

    private static final String PARAMCONFIGUREBUTTON = "configure";
    private static final String PARAMCONFIGURE = "configureradio";

    private static final String CONFIGURESTORAGE = "storage";
    private static final String CONFIGUREAUTHENTICATION = "authentication";
    private static final String SAVESTORAGE = "savestorage";
    private static final String SAVEAUTHENTICATION = "saveauthentication";
    private static final String SAVE = "save";

    private static final String FORMSTYLE = "style ='margin: 10px; padding: 5px;'";

    public void init( ServletConfig config ) throws ServletException
    {
        super.init( config );
        authorizedTokens = new ArrayList <String> ();
        writeToLog( "AppProperties version " + CLASSVERSION );
        loginPassword = new Password( 8 );
        writeToLog( "One time use login password: " + loginPassword.get() );
    }

    protected void doGet( HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException
    {
        String contextPath = request.getContextPath();
        String servletName =  getServletName();
        servletURL = contextPath + "/" + servletName;
        String sessionToken;

        response.setContentType( "text/html" );     // MIME type
        PrintWriter servletresponse = null;
        try{    servletresponse = response.getWriter();
        }catch( Exception e )
        {       writeToLog( "ERROR: Unable to create a PrintWriter" );
                e.printStackTrace();
                System.exit( 1 );
        }

        HttpSession session = request.getSession( true );

        servletresponse.println( getXHTMLHeader( "Configuration" ) );
        servletresponse.println( "<body>" );
        String currentToken = "";
        if( session != null )
        {       currentToken = (String) session.getAttribute( "sessionToken" );
        }

        String logout = request.getParameter( PARAMLOGOUTBUTTON );
        if( logout != null && !logout.isEmpty() && logout.equals( PARAMLOGOUTBUTTON ) )
        {
            logout = "";
            if( session != null )
            {
                while( authorizedTokens.contains( currentToken ) )
                {       authorizedTokens.remove( currentToken );
                }
                if( request.isRequestedSessionIdValid() == true )
                {       writeToLog( getUTCTimestamp() + " UTC " + session.getId() + " , " + currentToken + " Logged out." );
                        session.invalidate();
                }else
                {       writeToLog( "Logged out.  Session is invalidated." );
                }
            }
        }

        if( !authorizedTokens.contains( currentToken ) )    //validate start a session, accidentally keeping an extra token from login?
        {
            String userPassword = request.getParameter( PARAMLOGINUSERPASSWORD );
            if( loginPassword.isValid( userPassword ) )
            {
                userPassword = "";                  //use the session, not the password
                session.setMaxInactiveInterval( 5 * 60 );               // 5 * 60 seconds = 5 minutes
                sessionToken = UUID.randomUUID().toString();        // SecureRandom based
                session.setAttribute( "sessionToken" , sessionToken );
                authorizedTokens.add( sessionToken );

                session = changeSessionIdentifier( request );       //security measure against session hijacking
                currentToken = (String) session.getAttribute( "sessionToken" );
                writeToLog( getUTCTimestamp() + " UTC Login successful: " + session.getId() + " , " + currentToken );
                loginPassword = new Password( 8 );
                writeToLog( "One time use login password: " + loginPassword.get() );
            }else
            {       servletresponse.println( "<br />" );
                    servletresponse.println( getLoginForm() );
            }
        }


        if( authorizedTokens.contains( currentToken ) ) //resume a session
        {
            //servletresponse.println( "Version: " + CLASSVERSION + " <br /><br />" );

//BEGIN APPLICATION SPECIFIC LOGIC HERE
            try{
                displayMenu( servletresponse );

                //get HTTP PARAMS               String select = request.getParameter( PARAMCONFIGUREBUTTON );
                String menuSelection = request.getParameter( PARAMCONFIGURE );
                String authSaveButton = request.getParameter( SAVEAUTHENTICATION );
                String storageSaveButton = request.getParameter( SAVESTORAGE );
/*
                if( authSaveButton != null && !authSaveButton.isEmpty() && authSaveButton.equals( SAVE ) )
                {
                }
                if( storageSaveButton != null && !storageSaveButton.isEmpty() && storageSaveButton.equals( SAVE ) )
                {
                }
*/
                if( menuSelection != null && !menuSelection.isEmpty() )
                {
                    if( menuSelection.equals( CONFIGURESTORAGE ) )
                    {
                        servletresponse.println( "<form " + FORMSTYLE + " id='" + CONFIGURESTORAGE + "' action='" + servletURL + "' method='post' >" );
                        servletresponse.println( "<br />" + storageProperties.getHTMLForm() );
                        servletresponse.println( "<div><input type='submit' name='" + SAVESTORAGE + "' value='" + SAVE + "'/></div>" );
                        servletresponse.println( "</form>" );

                    }else if( menuSelection.equals( CONFIGUREAUTHENTICATION ) )
                    {
                        servletresponse.println( "<form " + FORMSTYLE + " id='" + CONFIGUREAUTHENTICATION + "' action='" + servletURL + "' method='post' >" );
                        servletresponse.println( "<br />" + authProperties.getHTMLForm() );
                        servletresponse.println( "<div><input type='submit' name='" + SAVEAUTHENTICATION + "' value='" + SAVE + "'/></div>" );
                        servletresponse.println( "</form>" );
                    }else
                    {       servletresponse.println( "Error: invalid Menu selection. <br />" );
                    }
                }


            }catch( Exception ioe )
            {       writeToLog( ioe.getMessage() );
                    servletresponse.println( ioe.getMessage() );
            }
//END APPLICATION SPECIFIC LOGIC

            servletresponse.println( "<br />" );
            servletresponse.println( getLogoutForm() );
        }
        servletresponse.println( "</body></html>" );
        servletresponse.close();
    } //end doGet()


//BEGIN APPLICATION SPECIFIC METHODS

    private static boolean containsIllegalCharacter( final String source )
    {
        boolean result = false;
    if( source != null)
    {   for( int i = 0; i < source.length(); i++ )
            {
                Character c = source.charAt(i);
                if( c.equals( '<' ) || c.equals( '>' ) )
                {       result = true;
                }
            }
    }
    return result;
    }
    private static boolean containsWhiteSpace( final String source )
    {
        boolean result = false;
    if( source != null)
    {   for( int i = 0; i < source.length(); i++ )
            {
                if( Character.isWhitespace( source.charAt(i) ) )
                {       result = true;
                }
            }
    }
    return result;
    }

    // Enumeration paramNames = request.getParameterNames();
  //while(paramNames.hasMoreElements()) {
//    String paramName = (String)paramNames.nextElement();



    private void displayMenu( PrintWriter out )
    {
        String space = "&#xA0;";
        out.println( "<form " + FORMSTYLE + "id='"+ PARAMCONFIGUREBUTTON + "' action='" + servletURL + "' method='post' >" );
        out.println( "<br />" );
        out.println( "<span><input type='submit' name='" + PARAMCONFIGUREBUTTON + "' value='" + PARAMCONFIGUREBUTTON + "'/></span>" );
        out.println( space + space + space );
        if( isStorageEnabled() )
        {           out.println( "<label><input type='radio' name='" + PARAMCONFIGURE + "' value='" + CONFIGURESTORAGE + "' /> " + CONFIGURESTORAGE + "</label>" );
        }
        if( isAuthenticationEnabled() )
        {           out.println( "<label><input type='radio' name='" + PARAMCONFIGURE + "' value='" + CONFIGUREAUTHENTICATION + "' /> " + CONFIGUREAUTHENTICATION + "</label>" );
        }
        out.println( "</form>" );
    }

    private boolean isAuthenticationEnabled()
    {
        boolean result = false;
        File f = new File( AuthServiceDAO.AUTHAPPPROPERTIES );
        if( f.exists() )
        {       result = true;
        }
        return result;
    }
    private boolean isStorageEnabled()
    {
        boolean result = false;
        File f = new File( StorageServiceDAO.STORAGEAPPPROPERTIES );
        if( f.exists() )
        {       result = true;
        }
        return result;
    }

//END APPLICATION SPECIFIC METHODS


//GENERIC HELPER METHODS

    private HttpSession changeSessionIdentifier( HttpServletRequest request )
    {
    HttpSession session = request.getSession();
    HashMap<String, Object> attributes = new HashMap<String, Object>();

//    @SuppressWarnings( "unchecked" )
    Enumeration <String> ss = session.getAttributeNames();
        Enumeration <String> attributeNames =  (Enumeration<String>) session.getAttributeNames();
    while( attributeNames != null && attributeNames.hasMoreElements() )
    {
        String name = attributeNames.nextElement();
        Object value = session.getAttribute( name );
        attributes.put( name , value );
    }
    session.invalidate();
    HttpSession newSession = request.getSession();

    Set<Map.Entry<String, Object>> attributeValues = attributes.entrySet();
    Iterator <Map.Entry<String, Object>> it = attributeValues.iterator();       // copy back the session content
    while( it.hasNext() )
    {   Map.Entry<String, Object> entry = it.next();
            newSession.setAttribute( (String) entry.getKey(), entry.getValue() );
    }
    return newSession;
    }

    private String getUTCTimestamp()
    {
        long currentTimeMilliseconds = System.currentTimeMillis();
        Date now = new Date( currentTimeMilliseconds );
        SimpleDateFormat utcFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        utcFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
        return utcFormat.format( now );
    }

    private void writeToLog( String content )
    {
        System.out.println( content );      //tomcat defaults to catalina.out
    }


    private static String getLogoutForm()
    {
        StringBuilder strb = new StringBuilder();
        String newline = System.getProperty( "line.separator" );
        strb.append( "<form " + FORMSTYLE + " id='" + PARAMLOGOUTBUTTON + "' action='" + servletURL + "' method='post' >" + newline );
        strb.append( "<div><input type='submit' name='" + PARAMLOGOUTBUTTON + "' value='" + PARAMLOGOUTBUTTON + "' /></div>" + newline );
        strb.append( "</form>" + newline );
        return strb.toString();
    }

    private static String getLoginForm()
    {
        StringBuilder strb = new StringBuilder();
        String newline = System.getProperty( "line.separator" );
        strb.append( "<form " + FORMSTYLE + " id='" + PARAMLOGINBUTTON + "' action='" + servletURL + "' method='post' >" + newline );
        strb.append( "Password: &nbsp; <input type='password' name='" + PARAMLOGINUSERPASSWORD + "' id='" + PARAMLOGINUSERPASSWORD + "' /> <br /><br />" + newline );
        strb.append( "<span><input type='submit' name='" + PARAMLOGINBUTTON + "' value='" + PARAMLOGINBUTTON + "'/></span>" + newline );
        strb.append( "</form>" + newline );
//      strb.append( "<script type='text/javascript'> document.forms[ '"+ PARAMLOGINBUTTON + "' ].elements[ '" + PARAMLOGINUSERPASSWORD + "' ].focus(); </script>" + newline );
        strb.append( "<script type='text/javascript'> document.getElementById( '" + PARAMLOGINUSERPASSWORD + "' ).focus(); </script>"  );
        return strb.toString();
    }

    private static String getXHTMLHeader( String title )
    {
        StringBuilder strb = new StringBuilder();
        String newline = System.getProperty( "line.separator" );
        strb.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" + newline );
        strb.append( "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + newline );
        strb.append( "<head><title>" + title + "</title>" + newline );
        strb.append( "<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />" + newline );
        strb.append( "<link type='text/css' rel='stylesheet' href='css/style.css' />" + newline );
//      strb.append( "<script type='text/javascript' src='" + contextPath + "/javascript.js'></script> + newline " );
        strb.append( "</head>" + newline );
        return strb.toString();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {       doGet( request, response);
    }
} //end class

  • « hashMap missing k numbers from sequence
  • puzzle equilibrium indexes »

Published

May 21, 2012

Category

java-servlet

~948 words

Tags

  • java-servlet 61
  • login 11
  • servlet 17
  • session 3
  • template 3