You are here

function _mass_pwreset_generate_password in Mass Password Reset 8

Same name and namespace in other branches
  1. 7 mass_pwreset.module \_mass_pwreset_generate_password()
  2. 2.x mass_pwreset.module \_mass_pwreset_generate_password()

Generate user passwords.

Modified version of Drupal's user_password() to include special characters.

Parameters

int $password_length: Length of password.

Return value

string Generated password

File

./mass_pwreset.module, line 150
Reset user passwords and optionally notify users.

Code

function _mass_pwreset_generate_password($password_length = 20) {

  // Regex to enforce the password requirements.
  // First and last characters cannot be digits (0-9).
  // Must contain two digit characters (0-9).
  // Must contain one lower case character (a-z).
  // Must contain one upper case character (A-Z).
  // Must contain three special characters
  // ( ()`~!@#$%^&*-+=|\{}[]:;"'<>,.?/ ).
  // Minimum length is 12 characters.
  // Maximum length is 128 characters.
  $password_requirements = '_^(?=.*\\d.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[()`~!@#$%^\\&*\\-+=\\|\\{}[\\]:;"\'<>,.?/].*[()`~!@#$%^\\&*\\-+=\\|\\{}[\\]:;"\'<>,.?/].*[()`~!@#$%^\\&*\\-+=\\|\\{}[\\]:;"\'<>,.?/])[\\D]{1}[\\s0-9a-zA-Z()`~!@#$%^\\&*\\-+=\\|\\{}[\\]:;"\'<>,.?/]{10,126}[\\D]{1}$_';

  // List of allowable characters for the password.
  $allowable_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789()`~!@#$%^&*-+=|\\{}[]:;"\'<>,.?/';

  // Zero-based count of characters in the allowable list.
  $characters_length = Unicode::strlen($allowable_characters) - 1;
  $characters_length = mb_strlen($allowable_characters) - 1;
  $new_password = '';

  // Generate passwords until password requirements are met.
  while (preg_match($password_requirements, $new_password) == 0) {

    // Loop the number of times specified by $length.
    for ($i = 0; $i < $characters_length; $i++) {
      do {

        // Find a secure random number within the range needed.
        $index = ord(drupal_random_bytes(1));
      } while ($index > $len);

      // Each iteration, pick a random character from the
      // allowable string and append it to the password:
      $new_password .= $allowable_characters[$index];
    }
  }
  return $new_password;
}