Example #1
0
  private void handleEnterCodeRequest(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws PwmUnrecoverableException, IOException, ServletException, ChaiUnavailableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final String userEnteredCode = pwmRequest.readParameterAsString(PwmConstants.PARAM_TOKEN);

    boolean tokenPassed = false;
    ErrorInformation errorInformation = null;
    try {
      final TokenPayload tokenPayload =
          pwmApplication
              .getTokenService()
              .processUserEnteredCode(
                  pwmSession, pwmRequest.getUserInfoIfLoggedIn(), null, userEnteredCode);
      if (tokenPayload != null) {
        if (TokenType.UPDATE_EMAIL.matchesName(tokenPayload.getName())) {
          LOGGER.debug(pwmRequest, "email token passed");

          updateProfileBean
              .getTokenVerificationProgress()
              .getPassedTokens()
              .add(TokenVerificationProgress.TokenChannel.EMAIL);
          updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .add(TokenVerificationProgress.TokenChannel.EMAIL);
          updateProfileBean.getTokenVerificationProgress().setPhase(null);
          tokenPassed = true;
        } else if (TokenType.UPDATE_SMS.matchesName(tokenPayload.getName())) {
          LOGGER.debug(pwmRequest, "SMS token passed");
          updateProfileBean
              .getTokenVerificationProgress()
              .getPassedTokens()
              .add(TokenVerificationProgress.TokenChannel.SMS);
          updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .add(TokenVerificationProgress.TokenChannel.SMS);
          updateProfileBean.getTokenVerificationProgress().setPhase(null);
          tokenPassed = true;
        } else {
          final String errorMsg = "token name/type is not recognized: " + tokenPayload.getName();
          errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
        }
      }
    } catch (PwmOperationalException e) {
      final String errorMsg = "token incorrect: " + e.getMessage();
      errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
    }

    if (!tokenPassed) {
      if (errorInformation == null) {
        errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT);
      }
      LOGGER.debug(pwmSession, errorInformation.toDebugStr());
      pwmRequest.setResponseError(errorInformation);
    }
  }
Example #2
0
  private void handleUpdateRequest(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws PwmUnrecoverableException, ChaiUnavailableException, IOException, ServletException {

    try {
      readFormParametersFromRequest(pwmRequest, updateProfileBean);
    } catch (PwmOperationalException e) {
      LOGGER.error(pwmRequest, e.getMessage());
      pwmRequest.setResponseError(e.getErrorInformation());
    }

    updateProfileBean.setFormSubmitted(true);
  }
  private void handleCreateRequest(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws PwmUnrecoverableException, ChaiUnavailableException, IOException, ServletException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean();
    final Configuration config = pwmApplication.getConfig();
    final Locale locale = ssBean.getLocale();

    final List<FormConfiguration> guestUserForm = config.readSettingAsForm(PwmSetting.GUEST_FORM);

    try {
      // read the values from the request
      final Map<FormConfiguration, String> formValues =
          FormUtility.readFormValuesFromRequest(pwmRequest, guestUserForm, locale);

      // read the expiration date from the request.
      final Date expirationDate = readExpirationFromRequest(pwmRequest);

      // see if the values meet form requirements.
      FormUtility.validateFormValues(config, formValues, locale);

      // read new user DN
      final String guestUserDN = determineUserDN(formValues, config);

      // read a chai provider to make the user
      final ChaiProvider provider = pwmSession.getSessionManager().getChaiProvider();

      // set up the user creation attributes
      final Map<String, String> createAttributes = new HashMap<>();
      for (final FormConfiguration formItem : formValues.keySet()) {
        LOGGER.debug(
            pwmSession,
            "Attribute from form: " + formItem.getName() + " = " + formValues.get(formItem));
        final String n = formItem.getName();
        final String v = formValues.get(formItem);
        if (n != null && n.length() > 0 && v != null && v.length() > 0) {
          createAttributes.put(n, v);
        }
      }

      // Write creator DN
      createAttributes.put(
          config.readSettingAsString(PwmSetting.GUEST_ADMIN_ATTRIBUTE),
          pwmSession.getUserInfoBean().getUserIdentity().getUserDN());

      // read the creation object classes.
      final Set<String> createObjectClasses =
          new HashSet<>(config.readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES));

      provider.createEntry(guestUserDN, createObjectClasses, createAttributes);
      LOGGER.info(pwmSession, "created user object: " + guestUserDN);

      final ChaiUser theUser = ChaiFactory.createChaiUser(guestUserDN, provider);
      final UserIdentity userIdentity =
          new UserIdentity(
              guestUserDN, pwmSession.getUserInfoBean().getUserIdentity().getLdapProfileID());

      // write the expiration date:
      if (expirationDate != null) {
        final String expirationAttr =
            config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);
        theUser.writeDateAttribute(expirationAttr, expirationDate);
      }

      final PwmPasswordPolicy passwordPolicy =
          PasswordUtility.readPasswordPolicyForUser(
              pwmApplication, pwmSession.getLabel(), userIdentity, theUser, locale);
      final PasswordData newPassword =
          RandomPasswordGenerator.createRandomPassword(
              pwmSession.getLabel(), passwordPolicy, pwmApplication);
      theUser.setPassword(newPassword.getStringValue());
      /*
      final UserInfoBean guestUserInfoBean = new UserInfoBean();
      final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication);
      userStatusReader.populateUserInfoBean(
              pwmSession.getLabel(),
              guestUserInfoBean,
              pwmSession.getSessionStateBean().getLocale(),
              userIdentity,
              theUser.getChaiProvider()
      );
      */

      { // execute configured actions
        LOGGER.debug(pwmSession, "executing configured actions to user " + theUser.getEntryDN());
        final List<ActionConfiguration> actions =
            pwmApplication.getConfig().readSettingAsAction(PwmSetting.GUEST_WRITE_ATTRIBUTES);
        if (actions != null && !actions.isEmpty()) {
          final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest, userIdentity);

          final ActionExecutor actionExecutor =
              new ActionExecutor.ActionExecutorSettings(pwmApplication, theUser)
                  .setExpandPwmMacros(true)
                  .setMacroMachine(macroMachine)
                  .createActionExecutor();

          actionExecutor.executeActions(actions, pwmSession);
        }
      }

      // everything good so forward to success page.
      this.sendGuestUserEmailConfirmation(pwmRequest, userIdentity);

      pwmApplication.getStatisticsManager().incrementValue(Statistic.NEW_USERS);

      pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_CreateGuest);
    } catch (ChaiOperationException e) {
      final ErrorInformation info =
          new ErrorInformation(
              PwmError.ERROR_NEW_USER_FAILURE, "error creating user: " + e.getMessage());
      pwmRequest.setResponseError(info);
      LOGGER.warn(pwmSession, info);
      this.forwardToJSP(pwmRequest, guestRegistrationBean);
    } catch (PwmOperationalException e) {
      LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
      pwmRequest.setResponseError(e.getErrorInformation());
      this.forwardToJSP(pwmRequest, guestRegistrationBean);
    }
  }
  protected void handleSearchRequest(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException {
    LOGGER.trace(pwmRequest, "Enter: handleSearchRequest(...)");
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final ChaiProvider chaiProvider = pwmSession.getSessionManager().getChaiProvider();
    final Configuration config = pwmApplication.getConfig();

    final String adminDnAttribute = config.readSettingAsString(PwmSetting.GUEST_ADMIN_ATTRIBUTE);
    final Boolean origAdminOnly =
        config.readSettingAsBoolean(PwmSetting.GUEST_EDIT_ORIG_ADMIN_ONLY);

    final String usernameParam = pwmRequest.readParameterAsString("username");
    final GuestRegistrationBean guBean =
        pwmApplication.getSessionStateService().getBean(pwmRequest, GuestRegistrationBean.class);

    final UserSearchEngine.SearchConfiguration searchConfiguration =
        new UserSearchEngine.SearchConfiguration();
    searchConfiguration.setChaiProvider(chaiProvider);
    searchConfiguration.setContexts(
        Collections.singletonList(config.readSettingAsString(PwmSetting.GUEST_CONTEXT)));
    searchConfiguration.setEnableContextValidation(false);
    searchConfiguration.setUsername(usernameParam);
    final UserSearchEngine userSearchEngine =
        new UserSearchEngine(pwmApplication, pwmSession.getLabel());

    try {
      final UserIdentity theGuest = userSearchEngine.performSingleUserSearch(searchConfiguration);
      final FormMap formProps = guBean.getFormValues();
      try {
        final List<FormConfiguration> guestUpdateForm =
            config.readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM);
        final Set<String> involvedAttrs = new HashSet<>();
        for (final FormConfiguration formItem : guestUpdateForm) {
          if (!formItem.getName().equalsIgnoreCase(HTTP_PARAM_EXPIRATION_DATE)) {
            involvedAttrs.add(formItem.getName());
          }
        }
        final UserDataReader userDataReader =
            LdapUserDataReader.selfProxiedReader(pwmApplication, pwmSession, theGuest);
        final Map<String, String> userAttrValues =
            userDataReader.readStringAttributes(involvedAttrs);
        if (origAdminOnly && adminDnAttribute != null && adminDnAttribute.length() > 0) {
          final String origAdminDn = userAttrValues.get(adminDnAttribute);
          if (origAdminDn != null && origAdminDn.length() > 0) {
            if (!pwmSession
                .getUserInfoBean()
                .getUserIdentity()
                .getUserDN()
                .equalsIgnoreCase(origAdminDn)) {
              final ErrorInformation info = new ErrorInformation(PwmError.ERROR_ORIG_ADMIN_ONLY);
              pwmRequest.setResponseError(info);
              LOGGER.warn(pwmSession, info);
              this.forwardToJSP(pwmRequest, guestRegistrationBean);
            }
          }
        }
        final String expirationAttribute =
            config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);
        if (expirationAttribute != null && expirationAttribute.length() > 0) {
          final Date expiration = userDataReader.readDateAttribute(expirationAttribute);
          if (expiration != null) {
            guBean.setUpdateUserExpirationDate(expiration);
          }
        }

        for (final FormConfiguration formItem : guestUpdateForm) {
          final String key = formItem.getName();
          final String value = userAttrValues.get(key);
          if (value != null) {
            formProps.put(key, value);
          }
        }

        guBean.setUpdateUserIdentity(theGuest);

        this.forwardToUpdateJSP(pwmRequest, guestRegistrationBean);
        return;
      } catch (ChaiOperationException e) {
        LOGGER.warn(pwmSession, "error reading current attributes for user: " + e.getMessage());
      }
    } catch (PwmOperationalException e) {
      final ErrorInformation error = e.getErrorInformation();
      pwmRequest.setResponseError(error);
      this.forwardToJSP(pwmRequest, guestRegistrationBean);
      return;
    }
    this.forwardToJSP(pwmRequest, guestRegistrationBean);
  }
  protected void handleUpdateRequest(
      final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
      throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException {
    // Fetch the session state bean.
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmApplication.getConfig();

    final List<FormConfiguration> formItems =
        pwmApplication.getConfig().readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM);
    final String expirationAttribute =
        config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE);

    try {
      // read the values from the request
      final Map<FormConfiguration, String> formValues =
          FormUtility.readFormValuesFromRequest(pwmRequest, formItems, pwmRequest.getLocale());

      // see if the values meet form requirements.
      FormUtility.validateFormValues(config, formValues, ssBean.getLocale());

      // read current values from user.
      final ChaiUser theGuest =
          pwmSession
              .getSessionManager()
              .getActor(pwmApplication, guestRegistrationBean.getUpdateUserIdentity());

      // check unique fields against ldap
      FormUtility.validateFormValueUniqueness(
          pwmApplication,
          formValues,
          ssBean.getLocale(),
          Collections.singletonList(guestRegistrationBean.getUpdateUserIdentity()),
          false);

      final Date expirationDate = readExpirationFromRequest(pwmRequest);

      // Update user attributes
      Helper.writeFormValuesToLdap(pwmApplication, pwmSession, theGuest, formValues, false);

      // Write expirationDate
      if (expirationDate != null) {
        theGuest.writeDateAttribute(expirationAttribute, expirationDate);
      }

      // send email.
      final UserStatusReader userStatusReader =
          new UserStatusReader(pwmApplication, pwmSession.getLabel());
      final UserInfoBean guestUserInfoBean = new UserInfoBean();
      userStatusReader.populateUserInfoBean(
          guestUserInfoBean,
          pwmSession.getSessionStateBean().getLocale(),
          guestRegistrationBean.getUpdateUserIdentity(),
          theGuest.getChaiProvider());
      this.sendUpdateGuestEmailConfirmation(pwmRequest, guestUserInfoBean);

      pwmApplication.getStatisticsManager().incrementValue(Statistic.UPDATED_GUESTS);

      // everything good so forward to confirmation page.
      pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateGuest);
      return;
    } catch (PwmOperationalException e) {
      LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
      pwmRequest.setResponseError(e.getErrorInformation());
    } catch (ChaiOperationException e) {
      final ErrorInformation info =
          new ErrorInformation(
              PwmError.ERROR_UNKNOWN, "unexpected error writing to ldap: " + e.getMessage());
      LOGGER.error(pwmSession, info);
      pwmRequest.setResponseError(info);
    }
    this.forwardToUpdateJSP(pwmRequest, guestRegistrationBean);
  }
Example #6
0
  private void advanceToNextStep(
      final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean)
      throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();

    final String updateProfileAgreementText =
        pwmApplication
            .getConfig()
            .readSettingAsLocalizedString(
                PwmSetting.UPDATE_PROFILE_AGREEMENT_MESSAGE,
                pwmSession.getSessionStateBean().getLocale());

    if (updateProfileAgreementText != null && updateProfileAgreementText.length() > 0) {
      if (!updateProfileBean.isAgreementPassed()) {
        final MacroMachine macroMachine =
            pwmRequest
                .getPwmSession()
                .getSessionManager()
                .getMacroMachine(pwmRequest.getPwmApplication());
        final String expandedText = macroMachine.expandMacros(updateProfileAgreementText);
        pwmRequest.setAttribute(PwmConstants.REQUEST_ATTR.AgreementText, expandedText);
        pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_AGREEMENT);
        return;
      }
    }

    final Map<FormConfiguration, String> formValues = updateProfileBean.getFormData();
    if (!updateProfileBean.isFormSubmitted()) {
      final Map<FormConfiguration, String> formMap = updateProfileBean.getFormData();
      final List<FormConfiguration> formFields =
          pwmApplication.getConfig().readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
      FormUtility.populateFormMapFromLdap(
          formFields,
          pwmRequest.getSessionLabel(),
          formMap,
          pwmSession.getSessionManager().getUserDataReader(pwmApplication));
      forwardToForm(pwmRequest);
      return;
    }

    // make sure there is form data in the bean.
    if (updateProfileBean.getFormData() == null) {
      forwardToForm(pwmRequest);
      return;
    }

    // validate the form data.
    try {
      // verify form meets the form requirements
      verifyFormAttributes(pwmRequest, formValues, true);
    } catch (PwmOperationalException e) {
      LOGGER.error(pwmSession, e.getMessage());
      pwmRequest.setResponseError(e.getErrorInformation());
      forwardToForm(pwmRequest);
      return;
    }

    final boolean requireConfirmation =
        pwmApplication
            .getConfig()
            .readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SHOW_CONFIRMATION);
    if (requireConfirmation && !updateProfileBean.isConfirmationPassed()) {
      forwardToConfirmForm(pwmRequest);
      return;
    }

    try {
      // write the form values
      final ChaiUser theUser = pwmSession.getSessionManager().getActor(pwmApplication);
      doProfileUpdate(pwmRequest, formValues, theUser);
      pwmRequest.forwardToSuccessPage(Message.Success_UpdateProfile);
      return;
    } catch (PwmException e) {
      LOGGER.error(pwmSession, e.getMessage());
      pwmRequest.setResponseError(e.getErrorInformation());
    } catch (ChaiException e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_UPDATE_ATTRS_FAILURE, e.toString());
      LOGGER.error(pwmSession, errorInformation.toDebugStr());
      pwmRequest.setResponseError(errorInformation);
    }

    forwardToForm(pwmRequest);
  }
Example #7
0
  private void advanceToNextStep(
      final PwmRequest pwmRequest,
      final UpdateAttributesProfile updateAttributesProfile,
      final UpdateProfileBean updateProfileBean)
      throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();

    final String updateProfileAgreementText =
        updateAttributesProfile.readSettingAsLocalizedString(
            PwmSetting.UPDATE_PROFILE_AGREEMENT_MESSAGE,
            pwmSession.getSessionStateBean().getLocale());

    if (updateProfileAgreementText != null && updateProfileAgreementText.length() > 0) {
      if (!updateProfileBean.isAgreementPassed()) {
        final MacroMachine macroMachine =
            pwmRequest
                .getPwmSession()
                .getSessionManager()
                .getMacroMachine(pwmRequest.getPwmApplication());
        final String expandedText = macroMachine.expandMacros(updateProfileAgreementText);
        pwmRequest.setAttribute(PwmRequest.Attribute.AgreementText, expandedText);
        pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_AGREEMENT);
        return;
      }
    }

    // make sure there is form data in the bean.
    if (updateProfileBean.getFormData() == null) {
      updateProfileBean.setFormData(formDataFromLdap(pwmRequest, updateAttributesProfile));
      forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean);
      return;
    }

    if (!updateProfileBean.isFormSubmitted()) {
      forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean);
      return;
    }

    // validate the form data.
    try {
      // verify form meets the form requirements
      final List<FormConfiguration> formFields =
          updateAttributesProfile.readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
      final Map<FormConfiguration, String> formValues =
          FormUtility.readFormValuesFromMap(
              updateProfileBean.getFormData(), formFields, pwmRequest.getLocale());
      verifyFormAttributes(pwmRequest, formValues, true);
    } catch (PwmException e) {
      LOGGER.error(pwmSession, e.getMessage());
      pwmRequest.setResponseError(e.getErrorInformation());
      forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean);
      return;
    }

    final boolean requireConfirmation =
        updateAttributesProfile.readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SHOW_CONFIRMATION);
    if (requireConfirmation && !updateProfileBean.isConfirmationPassed()) {
      forwardToConfirmForm(pwmRequest, updateAttributesProfile, updateProfileBean);
      return;
    }

    final Set<TokenVerificationProgress.TokenChannel> requiredVerifications =
        determineTokenPhaseRequired(pwmRequest, updateProfileBean, updateAttributesProfile);
    if (requiredVerifications != null) {
      for (final TokenVerificationProgress.TokenChannel tokenChannel : requiredVerifications) {
        if (requiredVerifications.contains(tokenChannel)) {
          if (!updateProfileBean
              .getTokenVerificationProgress()
              .getIssuedTokens()
              .contains(tokenChannel)) {
            initializeToken(pwmRequest, updateProfileBean, tokenChannel);
          }

          if (!updateProfileBean
              .getTokenVerificationProgress()
              .getPassedTokens()
              .contains(tokenChannel)) {
            updateProfileBean.getTokenVerificationProgress().setPhase(tokenChannel);
            pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_ENTER_CODE);
            return;
          }
        }
      }
    }

    try {
      // write the form values
      final ChaiUser theUser = pwmSession.getSessionManager().getActor(pwmApplication);
      doProfileUpdate(pwmRequest, updateProfileBean.getFormData(), theUser);
      pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateProfile);
      return;
    } catch (PwmException e) {
      LOGGER.error(pwmSession, e.getMessage());
      pwmRequest.setResponseError(e.getErrorInformation());
    } catch (ChaiException e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_UPDATE_ATTRS_FAILURE, e.toString());
      LOGGER.error(pwmSession, errorInformation.toDebugStr());
      pwmRequest.setResponseError(errorInformation);
    }

    forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean);
  }
  static boolean checkAuthentication(
      final PwmRequest pwmRequest, final ConfigManagerBean configManagerBean)
      throws IOException, PwmUnrecoverableException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final ConfigurationReader runningConfigReader =
        ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession())
            .getConfigReader();
    final StoredConfigurationImpl storedConfig = runningConfigReader.getStoredConfiguration();

    boolean authRequired = false;
    if (storedConfig.hasPassword()) {
      authRequired = true;
    }

    if (PwmApplication.MODE.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) {
      if (!pwmSession.getSessionStateBean().isAuthenticated()) {
        throw new PwmUnrecoverableException(PwmError.ERROR_AUTHENTICATION_REQUIRED);
      }

      if (!pwmRequest
          .getPwmSession()
          .getSessionManager()
          .checkPermission(pwmRequest.getPwmApplication(), Permission.PWMADMIN)) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED);
        pwmRequest.respondWithError(errorInformation);
        return true;
      }

      if (pwmSession.getLoginInfoBean().getAuthenticationType()
          != AuthenticationType.AUTHENTICATED) {
        throw new PwmUnrecoverableException(
            new ErrorInformation(
                PwmError.ERROR_AUTHENTICATION_REQUIRED,
                "Username/Password authentication is required to edit configuration.  This session has not been authenticated using a user password (SSO or other method used)."));
      }
    }

    if (PwmApplication.MODE.CONFIGURATION != pwmRequest.getPwmApplication().getApplicationMode()) {
      authRequired = true;
    }

    if (!authRequired) {
      return false;
    }

    if (!storedConfig.hasPassword()) {
      final String errorMsg = "config file does not have a configuration password";
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg, new String[] {errorMsg});
      pwmRequest.respondWithError(errorInformation, true);
      return true;
    }

    if (configManagerBean.isPasswordVerified()) {
      return false;
    }

    String persistentLoginValue = null;
    boolean persistentLoginAccepted = false;
    boolean persistentLoginEnabled = false;
    if (pwmRequest.getConfig().isDefaultValue(PwmSetting.PWM_SECURITY_KEY)) {
      LOGGER.debug(pwmRequest, "security not available, persistent login not possible.");
    } else {
      persistentLoginEnabled = true;
      final PwmSecurityKey securityKey = pwmRequest.getConfig().getSecurityKey();

      if (PwmApplication.MODE.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) {
        persistentLoginValue =
            SecureEngine.hash(
                storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH)
                    + pwmSession.getUserInfoBean().getUserIdentity().toDelimitedKey(),
                PwmHashAlgorithm.SHA512);

      } else {
        persistentLoginValue =
            SecureEngine.hash(
                storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH),
                PwmHashAlgorithm.SHA512);
      }

      {
        final String cookieStr =
            ServletHelper.readCookie(
                pwmRequest.getHttpServletRequest(), PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN);
        if (securityKey != null && cookieStr != null && !cookieStr.isEmpty()) {
          try {
            final String jsonStr = pwmApplication.getSecureService().decryptStringValue(cookieStr);
            final PersistentLoginInfo persistentLoginInfo =
                JsonUtil.deserialize(jsonStr, PersistentLoginInfo.class);
            if (persistentLoginInfo != null && persistentLoginValue != null) {
              if (persistentLoginInfo.getExpireDate().after(new Date())) {
                if (persistentLoginValue.equals(persistentLoginInfo.getPassword())) {
                  persistentLoginAccepted = true;
                  LOGGER.debug(
                      pwmRequest,
                      "accepting persistent config login from cookie (expires "
                          + PwmConstants.DEFAULT_DATETIME_FORMAT.format(
                              persistentLoginInfo.getExpireDate())
                          + ")");
                }
              }
            }
          } catch (Exception e) {
            LOGGER.error(
                pwmRequest, "error examining persistent config login cookie: " + e.getMessage());
          }
          if (!persistentLoginAccepted) {
            Cookie removalCookie = new Cookie(PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, null);
            removalCookie.setMaxAge(0);
            pwmRequest.getPwmResponse().addCookie(removalCookie);
            LOGGER.debug(pwmRequest, "removing non-working persistent config login cookie");
          }
        }
      }
    }

    final String password = pwmRequest.readParameterAsString("password");
    boolean passwordAccepted = false;
    if (!persistentLoginAccepted) {
      if (password != null && password.length() > 0) {
        if (storedConfig.verifyPassword(password)) {
          passwordAccepted = true;
          LOGGER.trace(pwmRequest, "valid configuration password accepted");
          updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), true);
        } else {
          LOGGER.trace(pwmRequest, "configuration password is not correct");
          pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
          pwmApplication
              .getIntruderManager()
              .mark(
                  RecordType.USERNAME,
                  PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME,
                  pwmSession.getLabel());
          final ErrorInformation errorInformation =
              new ErrorInformation(PwmError.ERROR_WRONGPASSWORD);
          pwmRequest.setResponseError(errorInformation);
          updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), false);
        }
      }
    }

    if ((persistentLoginAccepted || passwordAccepted)) {
      configManagerBean.setPasswordVerified(true);
      pwmApplication.getIntruderManager().convenience().clearAddressAndSession(pwmSession);
      pwmApplication
          .getIntruderManager()
          .clear(RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME);
      if (persistentLoginEnabled
          && !persistentLoginAccepted
          && "on".equals(pwmRequest.readParameterAsString("remember"))) {
        final int persistentSeconds = figureMaxLoginSeconds(pwmRequest);
        if (persistentSeconds > 0) {
          final Date expirationDate =
              new Date(System.currentTimeMillis() + (persistentSeconds * 1000));
          final PersistentLoginInfo persistentLoginInfo =
              new PersistentLoginInfo(expirationDate, persistentLoginValue);
          final String jsonPersistentLoginInfo = JsonUtil.serialize(persistentLoginInfo);
          final String cookieValue =
              pwmApplication.getSecureService().encryptToString(jsonPersistentLoginInfo);
          pwmRequest
              .getPwmResponse()
              .writeCookie(
                  PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, cookieValue, persistentSeconds);
          LOGGER.debug(
              pwmRequest,
              "set persistent config login cookie (expires "
                  + PwmConstants.DEFAULT_DATETIME_FORMAT.format(expirationDate)
                  + ")");
        }
      }

      if (configManagerBean.getPrePasswordEntryUrl() != null) {
        final String originalUrl = configManagerBean.getPrePasswordEntryUrl();
        configManagerBean.setPrePasswordEntryUrl(null);
        pwmRequest.getPwmResponse().sendRedirect(originalUrl);
        return true;
      }
      return false;
    }

    if (configManagerBean.getPrePasswordEntryUrl() == null) {
      configManagerBean.setPrePasswordEntryUrl(
          pwmRequest.getHttpServletRequest().getRequestURL().toString());
    }

    forwardToJsp(pwmRequest);
    return true;
  }