You are here

password_strength.module in Password Strength 5

File

password_strength.module
View source
<?php

/**
 * Implementation of hook_perm().
 */
function password_strength_perm() {
  return array(
    'configure password strength',
  );
}

/**
 * Implementation of hook_menu().
 */
function password_strength_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/settings/password_strength',
      'title' => t('Password strength'),
      'description' => t('Configure password strength enforcement rules.'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array(
        'password_strength_admin_settings',
      ),
      'access' => user_access('configure password strength'),
    );
  }
  return $items;
}

/**
 * Implementation of hook_help().
 */
function password_strength_help($section) {
  switch ($section) {
    case 'admin/settings/password_strength':
      return t('<p>The rules below are tested to determine password strength. A <em>high</em> strength password contains:</p>
        <ul>
          <li>letters,</li>
          <li>numbers,</li>
          <li>punctuation,</li>
          <li>both upper- and lower-case letters.</li>
        </ul>
      <p>Minimum length and username match tests do not count toward the "score" of a password. If either of these conditions fails to match the configured settings, the password is immediately rejected.</p>');
    default:
      return;
  }
}

/**
 * Menu callback
 */
function password_strength_admin_settings() {
  $form['rules'] = array(
    '#type' => 'fieldset',
    '#title' => t('Enforcement rules'),
  );
  $form['rules']['password_strength_verify_on_server'] = array(
    '#type' => 'checkbox',
    '#title' => t('Verify password strength on server'),
    '#default_value' => variable_get('password_strength_verify_on_server', 0),
    '#description' => t('Drupal should verify and enforce password strength on the server (i.e. not only in JavaScript).'),
  );
  $form['rules']['password_strength_not_username'] = array(
    '#type' => 'checkbox',
    '#title' => t('Test password not same as username'),
    '#default_value' => variable_get('password_strength_not_username', 1),
  );
  $options = drupal_map_assoc(array(
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16,
  ));
  $form['rules']['password_strength_min_length'] = array(
    '#type' => 'select',
    '#title' => t('Minimum length'),
    '#options' => $options,
    '#default_value' => variable_get('password_strength_min_length', 6),
  );
  $form['rules']['password_strength_min_level'] = array(
    '#type' => 'select',
    '#title' => t('Enforcement level'),
    '#options' => array(
      1 => t('None'),
      2 => t('Low'),
      3 => t('Medium'),
      4 => t('High'),
    ),
    '#default_value' => variable_get('password_strength_min_level', 4),
    '#description' => t('
      <ul>
        <li><em>None:</em> 1 or fewer rules passed.</li>
        <li><em>Low:</em> 2 rules passed.</li>
        <li><em>Medium:</em> 3 rules passed.</li>
        <li><em>High:</em> 4 rules passed.</li>
      </ul>
    '),
  );
  return system_settings_form($form);
}

/**
 * Add the necessary classes, and validation to password_confirm elements
 */
function password_strength_expand_password_confirm($element) {
  drupal_add_js(password_strength_js_settings(), 'setting');
  drupal_add_js(drupal_get_path('module', 'password_strength') . '/password_strength.js');
  drupal_add_css(drupal_get_path('module', 'password_strength') . '/password_strength.css');
  $strength = variable_get('password_strength_min_level', 4);
  $levels = array(
    1 => t('none'),
    2 => t('low'),
    3 => t('medium'),
    4 => t('high'),
  );
  $element = expand_password_confirm($element);
  $element['pass1']['#attributes'] = array(
    'class' => 'password-field',
  );
  $element['pass2']['#attributes'] = array(
    'class' => 'password-confirm',
  );
  if ($strength > 1) {
    $element['#description'] .= ' ' . t('Password must be at least %strength strength.', array(
      '%strength' => $levels[$strength],
    ));
  }

  // Only validate on server if admins want it
  if (variable_get('password_strength_verify_on_server', 0)) {
    $element['#validate']['password_strength_confirm_validate'] = array();
  }
  return $element;
}

/**
 * Provide translatable strings and variables to javascript settings
 */
function password_strength_js_settings() {
  global $user;
  return array(
    'password' => array(
      'strengthTitle' => t('Password strength:'),
      'lowStrength' => t('Low'),
      'mediumStrength' => t('Medium'),
      'highStrength' => t('High'),
      'requiredStrength' => variable_get('password_strength_min_level', 4),
      'tooShort' => t('It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters.'),
      'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
      'recommendVariation' => t('Your password is strong enough to meet the site requirements, but could be stronger.  If you like, try:'),
      'addLetters' => t('Adding both upper and lowercase letters.'),
      'addNumbers' => t('Adding numbers.'),
      'addPunctuation' => t('Adding punctuation.'),
      'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
      'confirmSuccess' => t('Yes'),
      'confirmFailure' => t('No'),
      'confirmTitle' => t('Passwords match:'),
      'username' => $user->name ? $user->name : '',
      'minLength' => variable_get('password_strength_min_length', 6),
    ),
  );
}

/**
 * Implementation of hook_elements
 */
function password_strength_elements() {

  // Override the default password_confirm processor
  $type['password_confirm'] = array(
    '#input' => TRUE,
    '#process' => array(
      'password_strength_expand_password_confirm' => array(),
    ),
  );
  return $type;
}

/**
 * Validate password strength according to configured rules.
 * Confirmation that both passwords provided match is already handled
 * by password_confirm_validate.
 */
function password_strength_confirm_validate($form) {
  $pass1 = trim($form['pass1']['#value']);
  if (!empty($pass1)) {
    global $user;
    $min_length = variable_get('password_strength_min_length', '6');
    $min_level = variable_get('password_strength_min_level', 4);
    $pass = $form['pass1']['#value'];
    $has_letters = ereg("[a-zA-Z]", $pass);
    $has_numbers = ereg("[0-9]", $pass);
    $has_punctuation = ereg("[^a-zA-Z0-9]", $pass);
    $has_casing = ereg("[a-z]+.*[A-Z]+|[A-Z]+.*[a-z]", $pass);

    // Check if length is less than 6 characters.
    if (strlen($pass) < $min_length) {
      form_error($form, t('Password is not long enough. Password must be at least @l characters.', array(
        '@l' => $min_length,
      )));
    }
    else {
      if (strtolower($pass) == strtolower($user->name) && variable_get('password_strength_not_username', 1)) {
        form_error($form, t('Password cannot be the same as the username.'));
      }
      else {

        // Extremely bad passwords still count as low.
        $count = ($has_letters ? 1 : 0) + ($has_numbers ? 1 : 0) + ($has_punctuation ? 1 : 0) + ($has_casing ? 1 : 0);
        if ($count < $min_level) {
          $msgs = array();
          if (!$has_letters || !$has_casing) {
            $msgs[] = t('Adding both upper and lowercase letters.');
          }
          if (!$has_numbers) {
            $msgs[] = t('Adding numbers.');
          }
          if (!$has_punctuation) {
            $msgs[] = t('Adding punctuation.');
          }
          if (count($msgs)) {
            $msg = t('The password does not include enough variation to be secure. Try:') . '<ul><li>' . implode('</li><li>', $msgs) . '</li></ul>';
            form_error($form, $msg);
          }
        }
      }
    }
  }

  // Password field must be converted from a two-element array into a single
  // string regardless of validation results.
  form_set_value($form['pass1'], NULL);
  form_set_value($form['pass2'], NULL);
  form_set_value($form, $pass1);
  return $form;
}

Functions

Namesort descending Description
password_strength_admin_settings Menu callback
password_strength_confirm_validate Validate password strength according to configured rules. Confirmation that both passwords provided match is already handled by password_confirm_validate.
password_strength_elements Implementation of hook_elements
password_strength_expand_password_confirm Add the necessary classes, and validation to password_confirm elements
password_strength_help Implementation of hook_help().
password_strength_js_settings Provide translatable strings and variables to javascript settings
password_strength_menu Implementation of hook_menu().
password_strength_perm Implementation of hook_perm().