function UserLoginTest::testPasswordRehashOnLogin

Same name and namespace in other branches
  1. 9 core/modules/user/tests/src/Functional/UserLoginTest.php \Drupal\Tests\user\Functional\UserLoginTest::testPasswordRehashOnLogin()
  2. 8.9.x core/modules/user/tests/src/Functional/UserLoginTest.php \Drupal\Tests\user\Functional\UserLoginTest::testPasswordRehashOnLogin()
  3. 11.x core/modules/user/tests/src/Functional/UserLoginTest.php \Drupal\Tests\user\Functional\UserLoginTest::testPasswordRehashOnLogin()

Tests user password is re-hashed upon login after changing $count_log2.

File

core/modules/user/tests/src/Functional/UserLoginTest.php, line 144

Class

UserLoginTest
Ensure that login works as expected.

Namespace

Drupal\Tests\user\Functional

Code

public function testPasswordRehashOnLogin() : void {
  // Retrieve instance of password hashing algorithm.
  $password_hasher = $this->container
    ->get('password');
  // Create a new user and authenticate.
  $account = $this->drupalCreateUser([]);
  $password = $account->passRaw;
  $this->drupalLogin($account);
  $this->drupalLogout();
  // Load the stored user. The password hash shouldn't need a rehash.
  $user_storage = $this->container
    ->get('entity_type.manager')
    ->getStorage('user');
  $account = User::load($account->id());
  // Check that the stored password doesn't need rehash.
  $this->assertFalse($password_hasher->needsRehash($account->getPassword()));
  // The current hashing cost is set to 10 in the container. Increase cost by
  // one, by enabling a module containing the necessary container changes.
  \Drupal::service('module_installer')->install([
    'user_custom_pass_hash_params_test',
  ]);
  $this->resetAll();
  // Reload the hashing service after container changes.
  $password_hasher = $this->container
    ->get('password');
  // Check that the stored password does need rehash.
  $this->assertTrue($password_hasher->needsRehash($account->getPassword()));
  $account->passRaw = $password;
  $this->drupalGet('user/login');
  $edit = [
    'name' => $account->getAccountName(),
    'pass' => $account->passRaw,
  ];
  $this->submitForm($edit, 'Log in');
  // Load the stored user, which should have a different password hash now.
  $user_storage->resetCache([
    $account->id(),
  ]);
  $account = $user_storage->load($account->id());
  // Check that the stored password doesn't need rehash.
  $this->assertFalse($password_hasher->needsRehash($account->getPassword()));
  $this->assertTrue($password_hasher->check($password, $account->getPassword()));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.