0

I'm trying to create a custom module for resetting the user's password.

In the following block of code I'm attempting to get the password in hash form:

$pass='User123@';

$autoloader =require_once(\Drupal::service('file_system')->realpath('autoload.php'));
//echo $autoloader; exit;
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
$password_hasher = $kernel->getContainer()->get('password');
$newhash =  $password_hasher->hash($pass);

//echo  $newhash ; exit; 

This is my db update code:

 $updatepass = \Drupal::database()->update('users_field_data')
      ->fields(array(
        'pass' => $newhash,
      ))
      ->condition('name', "$id",'=')
      ->execute();

Please help me understand what mistake I've made.

2

Just use the setPassword() method to update the user's password:

// Get user storage object.
$user_storage = \Drupal::entityManager()->getStorage('user');

// Load user by their user ID
$user = $user_storage->load($id);

// Set the new password
$user->setPassword('User123@');

// Save the user
$user->save();

This will take care of all the hashing for you and will trigger all the appropriate hooks for saving a user.

  • Thank you for your response what about where condition i want to create a modules where admin can update password for other user – Abhinaw Aanand Sep 20 '18 at 9:17
  • So in this example we are loading a user with a specific id. The id is in the variable ``$id`. You are responsible for populating this value. So we are updating the users password where the id is equal to whatever value you provide. – Felix Eve Sep 20 '18 at 9:21
  • 1
    Also there is already core functionality for admins to update users passwords. Why do you want to duplicate this? – Felix Eve Sep 20 '18 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.