You are here

function genpass_register_validate in Generate Password 8

Same name and namespace in other branches
  1. 5 genpass.module \genpass_register_validate()
  2. 6 genpass.module \genpass_register_validate()
  3. 7 genpass.module \genpass_register_validate()

User registration validation.

1 string reference to 'genpass_register_validate'
genpass_form_alter in ./genpass.module
Implements hook_form_alter().

File

./genpass.module, line 258
Contains genpass.module.

Code

function genpass_register_validate($form, FormStateInterface &$form_state) {

  // Only validate on final submission, and when there are no errors.
  if ($form_state
    ->getErrors() || !$form_state
    ->isSubmitted()) {
    return;
  }

  // Generate password when one hasn't been provided.
  if (empty($form_state
    ->getValue('pass'))) {

    // Generate and set password.
    $pass = genpass_generate();
    $pass_item =& _genpass_get_form_item($form, 'pass');
    $form_state
      ->setValueForElement($pass_item, $pass);
    $display = Drupal::config('genpass.settings')
      ->get('genpass_display');
    $is_admin_or_both = in_array($display, [
      GenpassInterface::PASSWORD_DISPLAY_ADMIN,
      GenpassInterface::PASSWORD_DISPLAY_BOTH,
    ]);
    $is_user_or_both = in_array($display, [
      GenpassInterface::PASSWORD_DISPLAY_USER,
      GenpassInterface::PASSWORD_DISPLAY_BOTH,
    ]);
    $genpass_mode = $form_state
      ->getValue('genpass_mode');

    // Keep messages as original objects to pass HTML through messenger.
    $messages = [];

    // Administrator created the user.
    if (\Drupal::routeMatch()
      ->getRouteName() == 'user.admin_create') {
      $messages[] = t('Since you did not provide a password, it was generated automatically for this account.');
      if ($is_admin_or_both) {
        $messages[] = t('The password is: <strong class="genpass-password">@password</strong>', [
          '@password' => $pass,
        ]);
      }
    }
    elseif ($genpass_mode == GenpassInterface::PASSWORD_OPTIONAL) {
      $messages[] = t('Since you did not provide a password, it was generated for you.');
      if ($is_user_or_both) {
        $messages[] = t('Your password is: <strong class="genpass-password">@password</strong>', [
          '@password' => $pass,
        ]);
      }
    }
    elseif ($genpass_mode == GenpassInterface::PASSWORD_RESTRICTED && $is_user_or_both) {
      $messages[] = t('The following password was generated for you: <strong class="genpass-password">@password</strong>', [
        '@password' => $pass,
      ]);
    }
    if (!empty($messages)) {
      $messenger = \Drupal::messenger();
      foreach ($messages as $message) {
        $messenger
          ->addStatus($message);
      }
    }
  }
}