<%@ page import="java.io.*,
                 java.util.*,
                 javax.xml.bind.DatatypeConverter,
                 jet.cs.util.*,
                 jet.server.api.http.*,
                 jet.JSvrResource,
                 jet.server.log.*" 
%>
<%@ page import="jet.server.api.*" %>
<%!
%>
<%    

    boolean clReturn = false;
    boolean clFailed = false; ;  // true -> checkLogin() failed by throwing an exception
    String clErrorMsg = "";      // exception message

    // get URL to display to show what is passed in
    String uri = request.getRequestURI();

    // header might contain credentials in the hader, obtained from named element "Authorization".
    // if so, it looks like this "Basic encoded-Data".
    // encoded-Data is the base64 encoding of a string that looks like this "user : password"
    String authorization = request.getHeader("Authorization");
    String hdrUser = "";
    String hdrPwd = "";
    String headerAuthorization = "NULL";
    if (authorization != null) {
        String encodedUserPwd = authorization.substring(6).trim();
        String UserPwd = new String(DatatypeConverter.parseBase64Binary(encodedUserPwd));
        int pColon = UserPwd.indexOf(":");
        hdrUser = UserPwd.substring(0, pColon);
        hdrPwd = UserPwd.substring(pColon+1);
        headerAuthorization = hdrUser + ":" + hdrPwd;
    }

    // Do work to identify if this login is called while someone is logged in.
    // If this is the case, the login work below will ignore authentication controls and do nothing. 
    // Let's identify this case so we can note that it is going on.
    HttpRptServer httpRptServer = HttpUtil.getHttpRptServer(request);
    if (httpRptServer == null) {
        System.getProperties().put("jreport.context", application);
        HttpUtil.initEnv(System.getProperties());
        httpRptServer = HttpUtil.getHttpRptServer(request);
    }
    HttpUserSessionManager httpUserSessionManager = httpRptServer.getHttpUserSessionManager();
    String user1 = (String)httpUserSessionManager.getUser(request);
    // When no one is logged in, getUser() returns an empty string.
    boolean userIsAlreadyLoggedIn = (user1.equals("") ? false : true);


    // Do the login work, using similar code as in dhtmljsp/AuthCheck.jsp.
    // This code is to show use of checkLogin() so there is nothing here
    // for handling the case of the webserver and report server being on 
    // different machines as there is in AuthCheck.jsp.
    try {
        // HttpUserSessionManager.checkLogin() will return true without 
        // doing any work when a user is already logged in. 
        //
        // When a user is not already logged in, it will attempt to get
        // credentials for a user and verify a match to a known JReport uuser.
        // It respects the ExternalAuthorized framework when it is set.
        // If that is not set, it will look at HTTP Header in the request
        // to see if credentials are passed in using HTTP authorization.
        // If that is not set, it will look at properties hash table that is passed in,
        // looking for credential values to check.
        // The expected use case is that the caller will fill the properties
        // hash table with the URL query parameters.
        //
        // It will then return true or false indicating if authentication happened. 
        // It is up to the caller to handle the failure case.
        //
        // In this code, checkLogin() returning FALSE will lead to engaging in a dialog with the browser
        // to attempt using HTTP authorization to get valid credentials.
        // This is done by code in this JSP, not by checkLogin().

        // Build up Properties value to hold HTTP parameters for use in call.
        Properties ht = new Properties();
        for (java.util.Enumeration e = request.getParameterNames(); e
                .hasMoreElements();) {
            String key = (String) e.nextElement();
            ht.put(key, request.getParameter(key));
        }

        clReturn = httpUserSessionManager.checkLogin(request,  response,
                                                     httpRptServer.getResourceManager().getRealm(), 
                                                     ht);

        // When checkLogin() is not able to get a credential that validates to a JReport User,
        // enter into a dialog with the browser to use HTTP Authentication.
                                                                 
        if (!clReturn) {
            httpUserSessionManager.sendUnauthorizedResponse(request, response, "Basic",
                         httpRptServer.getResourceManager().getRealm());
            return;  // stop processing this page - response is sent to browser
        }
        
    } catch (Exception e) {
        clErrorMsg = e.getMessage();
        clFailed = true;
    } 

// Fall through to here when checkLogin() "succeeds".
// This happens 
//   when a user was already logged in 
//    (checkLogin() does no work when it sees this case)
// or 
//   when checkLogin() obtained authentication information 
//   that matches the credentials of an existing JReport user.

%>

<html>
<head>
<title>HttpSessionUserManager.checkLogin status</title>
</head>
<body>

    <h2>Login using HttpUserSessonManager.checkLogin()</h2>

<p>
This page was requested with this URL: 
<br>
<b><%=uri %></b>
<p>
This page was requested with this Authorization Header: 
<b><%=headerAuthorization %></b>

<p>
<hr>
<p>

<form name="form1" action="loginIndex.jsp" style="Width:550px;">
    <fieldset>
        <legend>Go to main dispatch page, to show current state.</legend>
      <input type="submit" value="Go" />
    </fieldset>
</form
<hr>

<% if (clFailed) { %>

     Login request failed with a thrown exception...
     <p>
     Exception: <%=clErrorMsg %>

<%  } else if (userIsAlreadyLoggedIn) { %>
     Login request did no work...
     <p>
     A user is already logged in.
     <br>
     checkLogin() returned true without looking at any authentication data.
     <br>
     It accepted the current user, <b><%=user1 %></b>, as the user that is logged in. 

<% } else { %>

     Login request was successful...
     <p>
     HttpUserSessionManager.checkLogin() is a method that simply takes the credentials 
     passed in and validates and logs in the specified user, and then returns with a report on 
     the success of the request.
     <p>
     First, checkLogin() does nothing if a user is already logged in.  
     But when a user is not logged in,
     it looks for credentials to check.
     <p>
     It looks for credentials to check in this order:
     <br>
     <ol>
         <li>Use <b>External Authentication</b> class, if the class exists.</li>
         <li>Use <b>HTTP Request Header</b> Authorization data, if it exists.</li>
         <li>Use the <b>Property parameters</b> passed in by the caller (built from query parameters).</li>
     </ol>
     <p>
     checkLogin() returns true is a user is already logged in.
     checkLogin() returns true if credentials were found and they validated.
     checkLogin() returns false is no credentials were found or they did not validate.
     <p>
<% } %>
</body>
</html>
