Altering the User Password Reset Landing Page in Drupal 9/10

lakshmi , Credit to  volkotech-solutions Jul 24

This blog will cover how to customize the user password reset landing page in Drupal 9 and Drupal 10. This customization can help enforce strong password policies and improve the overall security of your Drupal site.

Introduction

Customizing the user password reset landing page is a crucial step in enhancing the security of your Drupal site. By enforcing strong password policies, you can ensure that users choose secure passwords, reducing the risk of unauthorized access.

Creating a Custom Module

To start, we need to create a custom module. We'll call this module custom_passwordpolicy

Create a .info.yml file:

Create the folder /modules/custom/custom_passwordpolicy. In this folder, we'll need to create a custom_passwordpolicy.info.yml file and add the following code.

name: 'Custom Password Policy'
type: module
description: 'Custom module to enforce password policies on user password reset form.'
core_version_requirement: ^9 || ^10
package: Custom

Enable a module:

For all possible ways to enable a module click here.

Using the Manage administrative menu, navigate to the Extend page in the list of modules, search the Custom Password Policy module, and then select its checkbox. Scroll down to the bottom of the webpage, and then click Install, then the Custom module Custom Password Policy has been enabled successfully.

Altering the Password Reset Form

create a .module File:

Create custom_passwordpolicy.module file under the folder /modules/custom/custom_passwordpolicy and add the following code. 

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;

/**
 * Implements hook_form_alter() for Alters the user password reset landing page.
 */
function custom_passwordpolicy_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'user_pass_reset' || $form_id === 'user_form') {
    $form['actions']['submit']['#validate'][] = 'custom_passwordpolicy_pwd_reset_validation';
  }
}

/**
 * Password validation callback.
 */
function custom_passwordpolicy_pwd_reset_validation(array &$form, FormStateInterface $form_state) {
  $password = $form_state->getValue('pass');

  if (!empty($password)) {
    $form_state->setTemporaryValue('entity_validated', TRUE);

    $errors = [];

    // Check if the password meets the minimum length requirement.
    if (strlen($password) < 8) {
      $errors[] = t('The password must be at least 8 characters long.');
    }

    // Check for presence of at least one lowercase letter.
    if (!preg_match('/[a-z]/', $password)) {
      $errors[] = t('The password must contain at least one lowercase letter.');
    }

    // Check for presence of at least one uppercase letter.
    if (!preg_match('/[A-Z]/', $password)) {
      $errors[] = t('The password must contain at least one uppercase letter.');
    }

    // Check for presence of at least one digit.
    if (!preg_match('/[0-9]/', $password)) {
      $errors[] = t('The password must contain at least one digit.');
    }

    // Check for presence of at least one special character.
    if (!preg_match('/[\W_]/', $password)) {
      $errors[] = t('The password must contain at least one special character.');
    }

    // If there are any errors, set them on the form.
    if (!empty($errors)) {
      // Wrap the errors in an unordered list.
      $error_message = t('The password does not meet the following requirements:') . '<ul><li>' . implode('</li><li>', array_map([Xss::class, 'filter'], $errors)) . '</li></ul>';
      $form_state->setErrorByName('pass', Markup::create($error_message));
    }
  }
}


/**
 * Implements hook_module_implements_alter().
 */
function custom_passwordpolicy_module_implements_alter(array &$implementations, $hook) {
  if ($hook === 'form_alter' && isset($implementations['custom_passwordpolicy'])) {
    $group = $implementations['custom_passwordpolicy'];
    unset($implementations['custom_passwordpolicy']);
    $implementations['custom_passwordpolicy'] = $group;
  }
}

The hook_form_alter function in the custom_passwordpolicy.module file targets the user_pass_reset form ID. This allows you to modify the form and add custom validation and messages. In the custom_passwordpolicy_pwd_reset_validation function, we check for various password criteria such as minimum length, presence of lowercase and uppercase letters, digits, and special characters. If any criteria are not met, an error message is displayed.

Trigger Password Reset:

Navigate to /user/1/edit?destination=/admin/people and initiate a password reset to test the form alterations.

Enter various passwords to test the validation rules implemented. Here are some example scenarios:

Scenario 1: Password shorter than 8 characters

  • Input: Test1!
  • Expected Result: An error message stating "The password must be at least 8 characters long."

Scenario 2: Password without lowercase letters

  • Input: TEST123!
  • Expected Result: An error message stating "The password must contain at least one lowercase letter."

Scenario 3: Password without uppercase letters

  • Input: test123!
  • Expected Result: An error message stating "The password must contain at least one uppercase letter."

Scenario 4: Password without digits

  • Input: TestTest!
  • Expected Result: An error message stating "The password must contain at least one digit."

Scenario 5: Password without special characters

  • Input: Test1234
  • Expected Result: An error message stating "The password must contain at least one special character."
password_validate_error_messages

Scenario 6: Valid password

  • Input: Test123!
  • Expected Result: No validation errors, and the form should be submitted successfully.

After entering a valid password, submit the form. Verify that the form submission proceeds without any errors, log out, and then log back in with the new password to ensure it has been successfully reset.

Conclusion

By following these steps, you can effectively alter the user password reset landing page in Drupal 9 and Drupal 10 to include custom password policies. This enhances both the security and usability of your Drupal site.

 

Comments