# BasicAuth.java

    /*
    ** Module   : BasicAuth.java
    ** Abstract : Implementation for the Basic authentication mode for web requests.
    **
    ** Copyright (c) 2022-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ------------------------------------Description-------------------------------------------
    ** 001 CA  20220404 Created the first version.
    ** 002 GBB 20230825 Legacy web security manager methods moved to LegacyWebSecurityManager.
    ** 003 GBB 20250403 Reusing the duplicated logging code by introducing the log method.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.main;

    import java.util.*;
    import java.util.logging.*;

    import javax.servlet.http.*;

    import com.goldencode.p2j.security.*;

    /**
     * Performs authentication and authorization using the <code>username:password</code> combo from the request's
     * {@value #AUTH_HEADER_NAME} header.
     */
    class BasicAuth
    extends WebServiceAuth
    {
       /** The authorization header. */
       private static final String AUTH_HEADER_NAME = "Authorization";

       /**
        * Create a web service authentication and authorization with the specified details.
        *
        * @param    type
        *           The web service type (REST, SOAP, WEBHANDLER).
        * @param    loginApiAuth
        *           Flag indicating if there is an explicit login API to be used.
        * @param    timeout
        *           The context timeout.
        */
       public BasicAuth(String type, boolean loginApiAuth, int timeout)
       {
          super(type, loginApiAuth, timeout);
       }

       /**
        * Perform the actual login, which will create the FWD context associated with this web request.
        *
        * @param    request
        *           The HTTP request.
        *
        * @return   The authentication token, or <code>null</code> if the authentication failed.
        */
       @Override
       protected String login(HttpServletRequest request)
       {
          String[] authDetails = getAuthenticationDetails(request);

          if (authDetails == null)
          {
             return null;
          }

          String token;

          try
          {
             token = wsm.createWebRequestContext(authDetails[0], authDetails[1], timeout);
          }
          catch (RestrictedUseException e)
          {
             String msg = "Could not login: " + request.toString() + " with " +
                          authDetails[0] + ":" + authDetails[1];
             log(msg, e);

             return null;
          }

          return token;
       }

       /**
        * Authenticate this request, but do not create the FWD context.
        *
        * @param    request
        *           The HTTP request.
        *
        * @return   <code>true</code> if the request contains valid credentials.
        */
       @Override
       protected boolean authenticate(HttpServletRequest request)
       {
          String[] authDetails = getAuthenticationDetails(request);

          if (authDetails == null)
          {
             return false;
          }

          try
          {
             return wsm.authWebRequest(authDetails[0], authDetails[1]);
          }
          catch (RestrictedUseException e)
          {
             String msg = "Could not authenticate request: " + request.toString() + " with " +
                          authDetails[0] + " " + authDetails[1];
             log(msg, e);

             return false;
          }
       }

       /**
        * Get the authentication details from the request.
        * <p>
        * For Basic authentication, the {@value #AUTH_HEADER_NAME} header must be set with the base64-encoded of
        * the <code>username:password</code> combo, prefixed by the "Basic " string.
        *
        * @param    request
        *           The HTTP request.
        *
        * @return   If the authentication details exist at the request, return an array with the username and
        *           password, in this order.
        */
       private String[] getAuthenticationDetails(HttpServletRequest request)
       {
          // get the authorization
          String header = request.getHeader(AUTH_HEADER_NAME);
          if (header == null || header.isEmpty())
          {
             return null;
          }

          try
          {
             header = header.substring("Basic ".length());
             byte[] bytes = Base64.getDecoder().decode(header.getBytes());

             String auth = new String(bytes);
             String user = auth.substring(0, auth.indexOf(':'));
             String uuid = auth.substring(auth.indexOf(':') + 1);

             return new String[] { user, uuid };
          }
          catch (Exception e)
          {
             String msg = "Authentication details invalid for " + request.getRequestURI() +
                          " with " + AUTH_HEADER_NAME +": " + request.getHeader(AUTH_HEADER_NAME);
             log(msg, e);

             return null;
          }
       }

       /**
        * Logs the exception and the message if log level FINE is enabled, otherwise logs only the message on
        * level WARNING.
        *
        * @param    msg
        *           The message.
        * @param    e
        *           The exception.
        */
       private void log(String msg, Exception e)
       {
          if (LOG.isLoggable(Level.FINE))
          {
             LOG.log(Level.FINE, msg, e);
          }
          else if (LOG.isLoggable(Level.WARNING))
          {
             LOG.log(Level.WARNING, msg);
          }
       }
    }