<%@ 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.*" %>
<%!
%>
<%    
    // get URL to display to show what is passed in
    String uri = request.getRequestURI();

    // 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);
    boolean userIsAlreadyLoggedIn = (user1.equals("") ? false : true);

    // Header might contain credentials in the hader, obtained from Header field named "Authorization".
    // The credentials would come from the browser, 
    //       when it has been asked to participate in HTTP Basic authentication.
    // If so, the Header field value 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 the login work, using similar code as in jinfonet/AuthCheck.jsp
    try {
        // HttpUtil.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 standard ways of passing
        // credentials to a page based on HTTP protocol.
        // All the work for doing this is done within the method call.
        // There is no return unless a user is authenticated. 
        // The method will throw exceptions in several error cases.
        // A call to this method may end with a response being sent to
        // the browser from within it, meaning that the rest of the
        // processing on this page is not executed. 
        if (!HttpUtil.checkLogin(request, response)) {
            // use the impossible failure case to allow possible success 
            // to fall through to the bottom.
            return;  
        }
    } catch (TooManyUsersException e) {
%>
<script language="JavaScript" type="text/JavaScript">
    alert("<%= HttpUtil.filterXSS(e.getMessage())%>");
    if (window.opener == null) {
        window.top.location.replace("lilo-show.jsp");
    } else {
        window.close();
    }
</script>
<% 
        return ;
    } catch (TooManyTimesException e) {
%>    

<script language="JavaScript" type="text/JavaScript">
    alert("<%= HttpUtil.filterXSS(e.getMessage())%>");
    if (window.opener == null) {
        history.back(1);
    } else {
        window.close();
    }
</script>
<%        
        return;
    } catch (jet.server.api.exception.NoRemoteServerException s) {
%>
<script language="JavaScript" type="text/JavaScript">
    alert("<%= HttpUtil.filterXSS(s.getMessage())%>");
    if (window.opener == null) {
        history.back(1);
    } else {
        window.close();
    }
</script>
<%
        return;
    } catch (Throwable t) {
%>    
<script language="JavaScript" type="text/JavaScript">
    alert("<%= HttpUtil.filterXSS(t.getMessage())%>");
    if (window.opener == null) {
        history.back(1);
    } else {
        window.close();
    }
</script>
<%        
        return;
    } 
        
// Fall through to here when checkLogin() "succeeds".
// This happens when a user was already logged in 
// (checkLogin() does nothing when it sees this case)
// or when checkLogin() obtained authentication information 
// that matches the credentials of an existing JReport user.

%>

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

    <h2>Login using HttpUtil.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 (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>
     HttpUtil.checkLogin() is a full service method that is a facade that wraps 
     HttpUserSessionManager.checkLogin() 
     so that standard approaches for authentication are performed in one method call. 
     <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 <b>URL query parameters</b> if they exist.</li>
     </ol>
     <p>
     If no authentication credentials exist that validates, 
     checkLogin() sends a response to the browser asking to use HTTP Basic authentication. 
     Processing on this page stops.  There is no return to this code from the checkLogin() call.
     This triggers the browser to display a login dialog to the user. 
     <p>
     The browser encodes the login credentials from the dialog into an HTTP Request Header sent to this page. 
     <br>
     This Request is processed the same way, with the HTTP Request Header authentication data found this time. 
     <p>
     If the authentication information does not match a JReport user/password, 
     checkLogin() sends a response to the browser asking to use HTTP Basic authentication. 
     <p>
     There can be many HTTP requests and  responses in the background between the browser 
     and this page before a user is authenticated and the logic flows to display this message.

     <p>
     Notice that if the user cancels the login dialog at the browser, the browser 
     transmits an HTTP request to report the cancel. 
     checkLogin() handles the cancel request with a response indicating a standard security 
     access failure - a 401 Unauthorized status code. 
     <p>
     When checkLogin() sends the 401 Unauthorized status code, it does 
     not return to this page, so this message is not displayed.
     The browser does not continue the dialog with this page after it gets the 401 response. 
<% } %>
</body>
</html>
