Last active
October 28, 2020 17:55
-
-
Save baikho/897b5c4d3e58351c7bdd254a93ff6793 to your computer and use it in GitHub Desktop.
Drupal 5/6 to Drupal 8 user passwords migration through batch update hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\user\Entity\User; | |
/** | |
* Implements hook_update_N(). | |
* | |
* Rehash migrated Drupal 5 MD5 hashes for Drupal 8. | |
*/ | |
function example_update_8101(&$sandbox) { | |
// This update hook should only be ran if the user migration didn't process | |
// the MD5 passwords with the 'md5_passwords' configuration option. Ideally | |
// the user migration should handle this re-hashing. | |
/** @var \Drupal\Core\Password\PasswordInterface $password */ | |
$password = \Drupal::service('password'); | |
// We exclude user records already having the correct hash. | |
$hashType = '$S$'; | |
if (!isset($sandbox['progress'])) { | |
$user_count = \Drupal::entityQuery('user') | |
->condition('pass', $hashType . '%', 'NOT LIKE') | |
->count() | |
->execute(); | |
$sandbox['progress'] = 0; | |
$sandbox['limit'] = 500; | |
$sandbox['total'] = $user_count; | |
} | |
$uids = \Drupal::entityQuery('user') | |
->condition('pass', $hashType . '%', 'NOT LIKE') | |
->range($sandbox['progress'], $sandbox['progress'] + $sandbox['limit']) | |
->execute(); | |
foreach ($uids as $uid) { | |
$user = User::load($uid); | |
// @see \Drupal\user\Plugin\migrate\destination\EntityUser::save() | |
// @see \Drupal\Core\Field\Plugin\Field\FieldType\PasswordItem::preSave() | |
$user->pass->pre_hashed = TRUE; | |
$user->pass->value = 'U' . $password->hash($user->pass->value); | |
$user->save(); | |
$sandbox['progress']++; | |
} | |
$sandbox['#finished'] = ($sandbox['progress'] / $sandbox['total']); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment