# UserAccountDefinition.java

    /*
    ** Module   : UserAccountDefinition.java
    ** Abstract : UserAccountDefinition is a view and controller delegate to add and to edit user
    **            accounts.
    **
    ** Copyright (c) 2017-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description----------------------
    ** 001 HC  20170521 Created initial version.
    ** 002 GBB 20230825 Added OS users form field.
    */
    /*
    ** 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.admin.client.application.home.accounts.users;

    import com.goldencode.p2j.admin.*;
    import com.goldencode.p2j.admin.client.*;
    import com.goldencode.p2j.admin.client.application.*;
    import com.goldencode.p2j.admin.client.application.home.accounts.*;
    import com.goldencode.p2j.admin.client.widget.*;
    import com.goldencode.p2j.admin.client.widget.dialog.*;
    import com.goldencode.p2j.admin.client.widget.dialog.InputDialog.*;
    import com.google.gwt.user.client.ui.*;
    import com.google.inject.*;
    import org.gwtbootstrap3.client.ui.form.validator.*;
    import org.gwtbootstrap3.extras.select.client.ui.*;

    import java.io.*;
    import java.util.*;
    import java.util.function.*;

    /**
     * Implements the add and edit user accounts use cases.
     */
    public class UserAccountDefinition
    extends Composite
    {
       /**
        * User Account model
        */
       public static class UserData
       {
          /**
           * Creates the user account model.
           *
           * @param    userDef
           *           The user account definition
           * @param    extDef
           *           The account extension data
           */
          public UserData(UserDef userDef, Serializable extDef)
          {
             this.userDef = userDef;
             this.extDef = extDef;
          }

          /** The user account definition */
          public UserDef userDef;

          /** The account extension data */
          public Serializable extDef;
       }

       /** The account extension */
       @Inject(optional = true)
       AccountExtension acctExtension;

       /** The common input dialogs provider */
       private final Provider<InputDialog> inputDialogProvider;

       /** The administration server interface */
       private final com.goldencode.p2j.admin.shared.AdminServiceAsync adminService;

       /** The server alarm manager */
       private final Alarm alarm;

       /** The edit boolean flag which true value indicates the edit use case.*/
       private boolean edit;

       /** The common input dialog */
       private InputDialog inputDialog;

       /** The account name field */
       private Field acctName;

       /** The account disabled field */
       private Field acctDisabled;

       /** The account person field */
       private Field person;

       /** The OS user field */
       private Field osUser;

       /** The account mode field */
       private Field mode;

       /** The account custom authentication plugin field */
       private Field plugin;

       /** The account certificates field */
       private Field certificates;

       /** The account security options field */
       private Field secSelect;

       /** The new password field */
       private Field password;

       /** The confirmed password field */
       private Field password2;

       /**
        * Creates the User Account Definition delegate.
        *
        * @param    inputDialogProvider
        *           The injected common input dialogs provider
        * @param    adminService
        *           The injected administration server interface
        * @param    alarm
        *           The injected server alarm manager
        */
       @Inject
       public UserAccountDefinition(Provider<InputDialog> inputDialogProvider,
                                    com.goldencode.p2j.admin.shared.AdminServiceAsync adminService,
                                    Alarm alarm)
       {
          this.inputDialogProvider = inputDialogProvider;
          this.adminService = adminService;
          this.alarm = alarm;
       }

       /**
        * Builds the dialog's fields of the User Account Definition View.
        *
        * @param    uDef
        *           The given user account definition
        * @param    doneHandler
        *           The completion consumer
        */
       public void build(UserDef uDef, Consumer<Boolean> doneHandler)
       {
          edit = uDef != null;
          inputDialog = inputDialogProvider.get();
          buildStandardFields(uDef, items ->
          {
             if (items != null)
             {
                inputDialog.setLabelSize(3);
                Item[] itemsArray = items.toArray(new Item[0]);
                if (acctExtension != null)
                {
                   Map<AccountExtension.StandardFields, InputDialog.Field> standardFields;
                   standardFields = new HashMap<>();
                   standardFields.put(AccountExtension.StandardFields.ACCT_NAME, acctName);
                   acctExtension.createFields(edit,
                                              inputDialog,
                                              standardFields,
                                              itemsArray,
                                              allItems ->
                   {
                      buildStep2(uDef, allItems.toArray(new Item[0]), doneHandler);
                   });
                }
                else
                {
                   buildStep2(uDef, itemsArray, doneHandler);
                }
             }
             else
             {
                doneHandler.accept(false);
             }
          });
       }

       /**
        * Shows the User Definition View dialog.
        *
        * @param    parent
        *           The parent container for the User Definition View dialog
        * @param    uDef
        *           The user account definition
        * @param    doneHandler
        *           The consumer of the user account model
        */
       public void show(HasWidgets parent, UserDef uDef, Consumer<UserData> doneHandler)
       {
          inputDialog.show(parent, false, values ->
          {
             if (values == null)
             {
                inputDialog.dismiss();
                doneHandler.accept(null);
                return;
             }

             saveUIData(uDef, values);
             Serializable extData = null;
             if (acctExtension != null)
             {
                extData = acctExtension.getExtData();
             }
             inputDialog.dismiss();
             doneHandler.accept(new UserData(uDef, extData));
          });
       }

       /**
        * Builds the extended user account fields.
        *
        * @param    uDef
        *           The given user account definition
        * @param    items
        *           The standard user account fields
        * @param    doneHandler
        *           The completion consumer
        */
       private void buildStep2(UserDef uDef, Item[] items, Consumer<Boolean> doneHandler)
       {
          inputDialog.build("User Account Definition", items);

          if (edit)
          {
             EnumRadioGroup secSel = (EnumRadioGroup) inputDialog.getWidget(secSelect);
             secSel.setEnabled(SecuritySelectorOptions.LEAVE_PASSWORD_UNCHANGED, false);
          }

          HasEnabled nameW = (HasEnabled) inputDialog.getWidget(acctName);
          nameW.setEnabled(!edit);

          updateUIState();
          bindHandlers();

          if (acctExtension != null)
          {
             acctExtension.onDialogBuilt(inputDialog, doneHandler);
          }
          else
          {
             doneHandler.accept(true);
          }
       }

       /**
        * Builds the standard dialog's fields for the given user account definition.
        *
        * @param    uDef
        *           The given user account definition
        * @param    doneHandler
        *           The consumer of the dialog's fields
        */
       private void buildStandardFields(UserDef uDef, Consumer<ArrayList<Item>> doneHandler)
       {
          ArrayList<Item> res = new ArrayList<>(20);
          loadUIData(data ->
          {
             acctName = new Field("Account Name", uDef == null ? "" : uDef.subjectId)
                            .withFieldSize(4);
             person = new Field("Person", uDef == null ? "" : uDef.person, true)
                            .withLabelSize(1)
                            .withFieldSize(4);
             res.add(new Span(acctName, person));

             acctDisabled = new Field("Account is Disabled", uDef == null ? false : !uDef.enabled);
             res.add(acctDisabled);

             osUser = new SelectField("OS User", data.osUsers,
                                      uDef == null || uDef.osUser == null ? "" : uDef.osUser,
                                      null, true);
             res.add(osUser);

             AuthModes selectMode = uDef == null ? AuthModes.SERVER_AUTH :
                                                   AuthModes.values()[uDef.mode];

             mode = new SelectField("Authentication Mode", getAuthModes(), selectMode.name(), null);
             res.add(mode);

             plugin = new SelectField("Custom Authentication Plugin", data.plugins,
                                      uDef == null || uDef.authPlugin == null ? "" : uDef.authPlugin,
                                      null, true);
             res.add(plugin);

             certificates = new SelectField("Certificates", data.certificates,
                                            uDef == null || uDef.alias == null ? "" : uDef.alias,
                                            null, true);
             res.add(certificates);

             SecuritySelectorOptions sOpt;
             sOpt = uDef == null ? SecuritySelectorOptions.ENTER_PASSWORD :
                            uDef.protect ? SecuritySelectorOptions.LEAVE_PASSWORD_UNCHANGED :
                                           SecuritySelectorOptions.NO_PASSWORD_PROTECTION;
             secSelect = new Field(null, sOpt);
             res.add(secSelect);

             password = new Field("Password", "").password(true);

             String msg = "Password values must match";
             AbstractValidator<String> pswdVal = new AbstractValidator<String>(msg)
             {
                @Override
                public int getPriority()
                {
                   return 999;
                }

                @Override
                public boolean isValid(String value)
                {
                   HasValue<String> pwd = inputDialog.getWidget(password);
                   String val1 = pwd.getValue();
                   if (val1 == null)
                   {
                      val1 = "";
                   }

                   return !((HasEnabled) pwd).isEnabled() || val1.equals(value);
                }
             };

             password2 = new Field("Confirm Password", "", false, pswdVal).password(true);
             Span pswdSpan = new Span(password, password2);
             res.add(pswdSpan);

             doneHandler.accept(res);
          });
       }

       /**
        * Attaches the dialog's input handlers
        */
       private void bindHandlers()
       {
          HasValue<String> wOsUser = (HasValue) inputDialog.getWidget(osUser);
          HasValue<String> wMode = (HasValue) inputDialog.getWidget(mode);
          HasValue<SecuritySelectorOptions> wSec = inputDialog.getWidget(secSelect);

          wOsUser.addValueChangeHandler(event -> updateUIState());
          wMode.addValueChangeHandler(event -> updateUIState());
          wSec.addValueChangeHandler(event -> updateUIState());
       }

       /**
        * Builds the list of authentication options.
        *
        * @return   The list of authentication options
        */
       private List<Option> getAuthModes()
       {
          List<Option> res = new ArrayList<>();
          for (AuthModes mode : AuthModes.values())
          {
             Option opt = new Option();
             if (mode == AuthModes.SERVER_AUTH)
             {
                opt.setValue("GROUP_SERVER_AUTH");
             }
             else
             {
                opt.setValue(mode.name());
             }

             opt.setText(mode.toString());
             res.add(opt);
          }

          return res;
       }

       /**
        * Loads UIData asynchronously and invokes the given result's consumer if this action is
        * completed successfully.
        *
        * @param    doneHandler
        *           The given result's consumer
        */
      private void loadUIData(Consumer<UIData> doneHandler)
       {
          MultiCallback mc = new MultiCallback(adminService, alarm);
          AdminCallback<TaggedName[]> pluginsCb = mc.newCallback();
          AdminCallback<TaggedName[]> certsCb = mc.newCallback();
          AdminCallback<TaggedName[]> osUsersCb = mc.newCallback();

          mc.onDone(() ->
          {
             if (mc.isSuccess())
             {
                TaggedName[] pluginstn = pluginsCb.getResult();
                TaggedName[] certstn = certsCb.getResult();
                TaggedName[] osUserstn = osUsersCb.getResult();

                List<Option> plugins = new ArrayList<>();
                Option empty = new Option();
                plugins.add(empty);
                for (TaggedName plugintn : pluginstn)
                {
                   Option opt = new Option();
                   opt.setValue(plugintn.getName());
                   opt.setText(plugintn.getTag());
                   plugins.add(opt);
                }

                List<Option> certs = new ArrayList<>();
                empty = new Option();
                certs.add(empty);
                for (TaggedName certtn : certstn)
                {
                   Option opt = new Option();
                   opt.setValue(certtn.getName());
                   opt.setText(certtn.getName());
                   opt.setSubtext(certtn.getTag());
                   certs.add(opt);
                }

                List<Option> osUsers = new ArrayList<>();
                Option defaultOsUserOpt = new Option();
                defaultOsUserOpt.setValue("");
                defaultOsUserOpt.setText("");
                osUsers.add(defaultOsUserOpt);

                for (TaggedName osUsertn : osUserstn)
                {
                   Option opt = new Option();
                   opt.setValue(osUsertn.getName());
                   opt.setText(osUsertn.getName());
                   osUsers.add(opt);
                }

                doneHandler.accept(new UIData(plugins, certs, osUsers));
             }
          });

          adminService.listAuthPlugins(pluginsCb);
          adminService.listPeerCerts(false, certsCb);
          adminService.listOsUsers(osUsersCb);
       }

      /**
       * Saves the user's input data into the target user account definition.
       *
       * @param    target
       *           The target user account definition
       * @param    values
       *           The map of the dialog's fields to their values
       */
       private void saveUIData(UserDef target, Map<Field, Object> values)
       {
          target.subjectId = (String) values.get(acctName);
          target.person = (String) values.get(person);
          String cert = (String) values.getOrDefault(certificates, null);
          target.alias = cert.isEmpty() ? null : cert;
          target.osUser = (String) values.get(osUser);

          AuthModes[] modes = AuthModes.values();
          String selMode = (String) values.get(mode);
          for (int i = 0; i < modes.length; i++)
          {
             if (modes[i].name().equals(selMode) ||
                 modes[i] == AuthModes.SERVER_AUTH && "GROUP_SERVER_AUTH".equals(selMode))
             {
                target.mode = i;
                break;
             }
          }
          target.enabled = !(boolean) values.get(acctDisabled);
          SecuritySelectorOptions selectedSec = (SecuritySelectorOptions) values.get(secSelect);
          target.protect = SecuritySelectorOptions.NO_PASSWORD_PROTECTION != selectedSec;
          if (selectedSec == SecuritySelectorOptions.ENTER_PASSWORD)
          {
             target.plainPassword = (String) values.get(password);
          }

          String pluginVal = (String) values.get(plugin);
          target.authPlugin = pluginVal.isEmpty() ? null : pluginVal;
       }

       /**
        * Updates the input fields states depending on the custom authentication plugin input and
        * the selected password option.
        */
       private void updateUIState()
       {
          HasEnabled wPlugin = (HasEnabled) inputDialog.getWidget(plugin);
          HasValue<String> wMode = (HasValue) inputDialog.getWidget(mode);
          HasValue<SecuritySelectorOptions> wSec = inputDialog.getWidget(secSelect);
          HasEnabled wPassword = (HasEnabled) inputDialog.getWidget(password);
          HasEnabled wPassword2 = (HasEnabled) inputDialog.getWidget(password2);

          wPlugin.setEnabled(AuthModes.CUST_AUTH.name().equals(wMode.getValue()));
          switch (wSec.getValue())
          {
             case ENTER_PASSWORD:
                wPassword.setEnabled(true);
                wPassword2.setEnabled(true);
                break;
             case LEAVE_PASSWORD_UNCHANGED:
             case NO_PASSWORD_PROTECTION:
                wPassword.setEnabled(false);
                wPassword2.setEnabled(false);
                break;
          }
       }

       /**
        * Holds custom authentication plugins and peer certificates.
        */
       private static class UIData
       {
          /** The option list filled with custom authentication plugins */
          List<Option> plugins;

          /** The option list filled with peer certificates */
          List<Option> certificates;

          /** The option list filled with  os users */
          List<Option> osUsers;

          /**
           * Creates this UI data container
           *
           * @param    plugins
           *           The option list filled with custom authentication plugins
           * @param    certificates
           *           The option list filled with peer certificates
           * @param    osUsers
           *           The option list filled with os users
           */
          public UIData(List<Option> plugins,
                        List<Option> certificates,
                        List<Option> osUsers)
          {
             this.plugins = plugins;
             this.certificates = certificates;
             this.osUsers = osUsers;
          }
       }
    }