You are here

function password_policy_ajax_check in Password Policy 7.2

AJAX callback to check password against applicable policies.

1 string reference to 'password_policy_ajax_check'
password_policy_menu in ./password_policy.module
Implements hook_menu().

File

./password_policy.module, line 27
Enforces password policies.

Code

function password_policy_ajax_check() {

  // Decode password which javascript ran encodeURIComponent.
  // The password will not be displayed, so there is no need to filter it with
  // check_plain() or filter_xss() as suggested by Coder.
  // @ignore security_17
  if (isset($_POST['password'])) {
    $untrimmed_password = rawurldecode($_POST['password']);

    // Trim the password before checking against policies, since Drupal will
    // trim passwords before saving them.
    $password = trim($untrimmed_password);
    $is_trimmed = $password !== $untrimmed_password;

    // Determine whether password is all spaces.  If it is empty string after
    // trimming, it was all spaces.
    $is_all_spaces = $is_trimmed && $password === '';
    if ($is_all_spaces) {
      return drupal_json_output(array(
        'message' => t('Password is all spaces and will not be saved.'),
        'strength' => 0,
        'indicatorText' => '',
      ));
    }

    // Do not process overlong passwords to avoid potential DoS.
    // Drupal core does not allow passwords over a certain number of bytes, so
    // impose the same limitation.
    if (_password_policy_is_password_too_long($password)) {
      return drupal_json_output(array(
        'message' => t('Password exceeds maximum length. Please choose a shorter password.'),
        'strength' => 0,
        'indicatorText' => '',
      ));
    }

    // Using this user is not always going to work.
    global $user;
    $account = $user;
    password_policy_user_load(array(
      $account->uid => $account,
    ));
    $policies = PasswordPolicy::matchedPolicies($account);

    // Exit prematurely if no policies are usable.
    if (count($policies) == 0) {
      return;
    }
    $total = 0;
    $errors = array();
    foreach ($policies as $policy) {
      $total += count($policy
        ->messages());
      $errors = array_merge($errors, $policy
        ->check($password, $account));
    }
    $sus_count = $total - count($errors);
    $score = $sus_count / $total * 100;
    $msg = '';
    if (!empty($errors)) {
      $msg .= t('Password does not meet the following requirements:');
      $msg .= theme('item_list', array(
        'items' => $errors,
      ));
      if ($is_trimmed) {
        $msg .= t('Password has spaces at the beginning or end which are ignored.');
      }
    }
    $return = array(
      'message' => $msg,
      'strength' => $score,
      'indicatorText' => t('@sus_count of @total', array(
        '@sus_count' => $sus_count,
        '@total' => $total,
      )),
    );
    drupal_json_output($return);
  }
}