# SampleSsoAuthenticator.java

    /*
     ** Module   : SampleSsoAuthenticator.java
     ** Abstract : Example implementation for standard SSO authentication hook interface.
     **
     ** Copyright (c) 2023, Golden Code Development Corporation.
     **
     ** -#- -I- --Date-- ---------------------------------Description---------------------------------
     ** 001 GBB 20230704 Created initial version
     ** 002 GBB 20231027 Prefix for storageId for authenticated users in the dummy implementation.
     ** 003 GBB 20231121 Session description added to successful auth result.
     */
    /*
     ** 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.security;

    import com.goldencode.p2j.main.*;
    import com.goldencode.util.*;

    import javax.servlet.http.*;
    import java.util.*;

    /** Sample implementation of the standard SSO authenticator hook. Uses mostly hard-coded values. */
    public class SampleSsoAuthenticator
    implements SsoAuthenticator
    {
       /** Cookie name used for auto-login. */
       private static final String SAMPLE_COOKIE_NAME = "SampleSsoAuthenticator";

       /** Cookie invalid value used to invalidate the cookie. */
       private static final String SAMPLE_COOKIE_INVALID_VALUE = "Invalid";

       /** Path for the auth cookie. */
       private static final String SAMPLE_COOKIE_PATH = "/; HttpOnly;";

       /** Example value for SESSION:AUTH-BLOB. */
       private static final String SAMPLE_AUTH_BLOB = "Bearer dfg978sdftgvsdfvvs879d9u0gvsdf";

       /** The FWD user returned by default for all in-app users. */
       private String defaultFwdUser = "newuser";

       /**
        * First attempts aut-login by validating only the cookies. If auth by cookie fails, simulates
        * successful response by setting the hard-coded values in the result.
        *
        * @param    paramMap
        *           A map of all query / form params.
        * @param    cookies
        *           All cookies coming with the HTTP request for authentication.
        * @param    licensingData
        *           Data that can be used for enforcing licensing policy.
        *
        * @return   A container with all details needed by the FWD framework to spawn a new client.
        */
       @Override
       public Result authenticate(Map<String, String[]> paramMap, Cookie[] cookies, LicensingData licensingData)
       {
          if (cookies != null && cookies.length > 0)
          {
             Result cookieAuthResult = authenticate(cookies, licensingData);
             if (cookieAuthResult != null && cookieAuthResult.isSuccess())
             {
                return cookieAuthResult;
             }
          }

          String appUser = paramMap.get(FWD_SDK_LOGIN_PARAM_USER)[0];
          String appPass = paramMap.get(FWD_SDK_LOGIN_PARAM_PASS)[0];

          // TODO: check credentials against an auth provider
          Cookie cookie = new Cookie(SAMPLE_COOKIE_NAME, appUser);
          cookie.setPath(SAMPLE_COOKIE_PATH);
          cookie.setSecure(true);

          Result result = new Result(true,
                                     defaultFwdUser,
                                     "storage-" + appUser,
                                     SAMPLE_AUTH_BLOB,
                                     cookie);
          result.setSessionDescription("Session for end user " + appUser);
          return result;
       }

       /**
        * Invalidates the web session associated with the authentication cookie by communicating with the auth
        * server or updating the DB and returns a cookie with the same name, but invalid value.
        *
        * @param    cookies
        *           The cookie to be returned to the browser and used in the next auth requests.
        *
        * @return   <code>null</code> if the web session / cookie invalidation failed, otherwise an
        *           authentication Cookie with invalid value.
        */
       @Override
       public Cookie logout(Cookie[] cookies)
       {
          // TODO: invalidate session in auth provider

          Cookie cookie = new Cookie(SAMPLE_COOKIE_NAME, SAMPLE_COOKIE_INVALID_VALUE);
          cookie.setPath(SAMPLE_COOKIE_PATH);
          cookie.setSecure(true);
          return cookie;
       }

       /**
        * Simulates authentication by cookie.
        *
        * @param    cookies
        *           All cookies coming with the HTTP request for authentication.
        * @param    licensingData
        *           Data that can be used for enforcing licensing policy.
        *
        * @return   A container with all details needed by the FWD framework to spawn a new client.
        */
       @Override
       public Result authenticate(Cookie[] cookies, LicensingData licensingData)
       {
          if (cookies == null || cookies.length == 0)
          {
             return null;
          }
          // read the cookie, query the auth provider
          String authCookieValue = Arrays.stream(cookies)
                                         .filter(cookie -> cookie.getName().equals(SAMPLE_COOKIE_NAME))
                                         .findAny()
                                         .map(Cookie::getValue)
                                         .orElse(null);

          if (authCookieValue == null || SAMPLE_COOKIE_INVALID_VALUE.equals(authCookieValue))
          {
             return new Result(false, WebDriverHandler.SupportedHttpCode.UNAUTHORIZED, null);
          }

          // TODO: check cookie value against an auth provider and receive the new cookie value
          Cookie cookie = new Cookie(SAMPLE_COOKIE_NAME, authCookieValue);
          cookie.setPath(SAMPLE_COOKIE_PATH);
          cookie.setSecure(true);

          Result result = new Result(true,
                                     defaultFwdUser,
                                     "storage-" + authCookieValue,
                                     SAMPLE_AUTH_BLOB,
                                     cookie);
          result.setSessionDescription("Session for end user " + authCookieValue);
          return result;
       }

       /**
        * Returns the hard-coded cookie name used for authentication.
        *
        * @return   The name of the cookie used for authentication.
        */
       @Override
       public String getAuthCookieName()
       {
          return SAMPLE_COOKIE_NAME;
       }

       /**
        * Sets the default FWD user.
        *
        * @param    option
        *           All cookies coming with the HTTP request for authentication.
        */
       @Override
       public void setOption(String option)
       {
          if (StringHelper.hasContent(option))
          {
             this.defaultFwdUser = option;
          }
       }

       /**
        * Returns null. The default template will be used.
        *
        * @param    loadedTemplate
        *           The html template loaded from the standard location in the custom root package or null.
        *
        * @return   <code>null</code>.
        */
       @Override
       public String getLoginPage(String loadedTemplate)
       {
          return null;
       }
    }