3 namespace Drupal\Tests\user\Functional;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Test\AssertMailTrait;
8 use Drupal\Tests\system\Functional\Cache\PageCacheTagsTestBase;
9 use Drupal\user\Entity\User;
12 * Ensure that password reset methods work as expected.
16 class UserPasswordResetTest extends PageCacheTagsTestBase {
19 getMails as drupalGetMails;
23 * The user object to test password resetting.
25 * @var \Drupal\user\UserInterface
34 public static $modules = ['block'];
39 protected function setUp() {
42 $this->drupalPlaceBlock('system_menu_block:account');
45 $account = $this->drupalCreateUser();
47 // Activate user by logging in.
48 $this->drupalLogin($account);
50 $this->account = User::load($account->id());
51 $this->account->passRaw = $account->passRaw;
52 $this->drupalLogout();
54 // Set the last login time that is used to generate the one-time link so
55 // that it is definitely over a second ago.
56 $account->login = REQUEST_TIME - mt_rand(10, 100000);
57 db_update('users_field_data')
58 ->fields(['login' => $account->getLastLoginTime()])
59 ->condition('uid', $account->id())
64 * Tests password reset functionality.
66 public function testUserPasswordReset() {
67 // Verify that accessing the password reset form without having the session
68 // variables set results in an access denied message.
69 $this->drupalGet(Url::fromRoute('user.reset.form', ['uid' => $this->account->id()]));
70 $this->assertResponse(403);
72 // Try to reset the password for an invalid account.
73 $this->drupalGet('user/password');
75 $edit = ['name' => $this->randomMachineName(32)];
76 $this->drupalPostForm(NULL, $edit, t('Submit'));
78 $this->assertText(t('@name is not recognized as a username or an email address.', ['@name' => $edit['name']]), 'Validation error message shown when trying to request password for invalid account.');
79 $this->assertEqual(count($this->drupalGetMails(['id' => 'user_password_reset'])), 0, 'No email was sent when requesting a password for an invalid account.');
81 // Reset the password by username via the password reset page.
82 $edit['name'] = $this->account->getUsername();
83 $this->drupalPostForm(NULL, $edit, t('Submit'));
85 // Verify that the user was sent an email.
86 $this->assertMail('to', $this->account->getEmail(), 'Password email sent to user.');
87 $subject = t('Replacement login information for @username at @site', ['@username' => $this->account->getUsername(), '@site' => $this->config('system.site')->get('name')]);
88 $this->assertMail('subject', $subject, 'Password reset email subject is correct.');
90 $resetURL = $this->getResetURL();
91 $this->drupalGet($resetURL);
92 // Ensure that the current url does not contain the hash and timestamp.
93 $this->assertUrl(Url::fromRoute('user.reset.form', ['uid' => $this->account->id()]));
95 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'));
97 // Ensure the password reset URL is not cached.
98 $this->drupalGet($resetURL);
99 $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'));
101 // Check the one-time login page.
102 $this->assertText($this->account->getUsername(), 'One-time login page contains the correct username.');
103 $this->assertText(t('This login can be used only once.'), 'Found warning about one-time login.');
104 $this->assertTitle(t('Reset password | Drupal'), 'Page title is "Reset password".');
106 // Check successful login.
107 $this->drupalPostForm(NULL, NULL, t('Log in'));
108 $this->assertLink(t('Log out'));
109 $this->assertTitle(t('@name | @site', ['@name' => $this->account->getUsername(), '@site' => $this->config('system.site')->get('name')]), 'Logged in using password reset link.');
111 // Change the forgotten password.
112 $password = user_password();
113 $edit = ['pass[pass1]' => $password, 'pass[pass2]' => $password];
114 $this->drupalPostForm(NULL, $edit, t('Save'));
115 $this->assertText(t('The changes have been saved.'), 'Forgotten password changed.');
117 // Verify that the password reset session has been destroyed.
118 $this->drupalPostForm(NULL, $edit, t('Save'));
119 $this->assertText(t("Your current password is missing or incorrect; it's required to change the Password."), 'Password needed to make profile changes.');
121 // Log out, and try to log in again using the same one-time link.
122 $this->drupalLogout();
123 $this->drupalGet($resetURL);
124 $this->drupalPostForm(NULL, NULL, t('Log in'));
125 $this->assertText(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'One-time link is no longer valid.');
127 // Request a new password again, this time using the email address.
128 $this->drupalGet('user/password');
129 // Count email messages before to compare with after.
130 $before = count($this->drupalGetMails(['id' => 'user_password_reset']));
131 $edit = ['name' => $this->account->getEmail()];
132 $this->drupalPostForm(NULL, $edit, t('Submit'));
133 $this->assertTrue(count($this->drupalGetMails(['id' => 'user_password_reset'])) === $before + 1, 'Email sent when requesting password reset using email address.');
135 // Visit the user edit page without pass-reset-token and make sure it does
136 // not cause an error.
137 $resetURL = $this->getResetURL();
138 $this->drupalGet($resetURL);
139 $this->drupalPostForm(NULL, NULL, t('Log in'));
140 $this->drupalGet('user/' . $this->account->id() . '/edit');
141 $this->assertNoText('Expected user_string to be a string, NULL given');
142 $this->drupalLogout();
144 // Create a password reset link as if the request time was 60 seconds older than the allowed limit.
145 $timeout = $this->config('user.settings')->get('password_reset_timeout');
146 $bogus_timestamp = REQUEST_TIME - $timeout - 60;
147 $_uid = $this->account->id();
148 $this->drupalGet("user/reset/$_uid/$bogus_timestamp/" . user_pass_rehash($this->account, $bogus_timestamp));
149 $this->drupalPostForm(NULL, NULL, t('Log in'));
150 $this->assertText(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'Expired password reset request rejected.');
152 // Create a user, block the account, and verify that a login link is denied.
153 $timestamp = REQUEST_TIME - 1;
154 $blocked_account = $this->drupalCreateUser()->block();
155 $blocked_account->save();
156 $this->drupalGet("user/reset/" . $blocked_account->id() . "/$timestamp/" . user_pass_rehash($blocked_account, $timestamp));
157 $this->assertResponse(403);
159 // Verify a blocked user can not request a new password.
160 $this->drupalGet('user/password');
161 // Count email messages before to compare with after.
162 $before = count($this->drupalGetMails(['id' => 'user_password_reset']));
163 $edit = ['name' => $blocked_account->getUsername()];
164 $this->drupalPostForm(NULL, $edit, t('Submit'));
165 $this->assertRaw(t('%name is blocked or has not been activated yet.', ['%name' => $blocked_account->getUsername()]), 'Notified user blocked accounts can not request a new password');
166 $this->assertTrue(count($this->drupalGetMails(['id' => 'user_password_reset'])) === $before, 'No email was sent when requesting password reset for a blocked account');
168 // Verify a password reset link is invalidated when the user's email address changes.
169 $this->drupalGet('user/password');
170 $edit = ['name' => $this->account->getUsername()];
171 $this->drupalPostForm(NULL, $edit, t('Submit'));
172 $old_email_reset_link = $this->getResetURL();
173 $this->account->setEmail("1" . $this->account->getEmail());
174 $this->account->save();
175 $this->drupalGet($old_email_reset_link);
176 $this->drupalPostForm(NULL, NULL, t('Log in'));
177 $this->assertText(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'One-time link is no longer valid.');
179 // Verify a password reset link will automatically log a user when /login is
181 $this->drupalGet('user/password');
182 $edit = ['name' => $this->account->getUsername()];
183 $this->drupalPostForm(NULL, $edit, t('Submit'));
184 $reset_url = $this->getResetURL();
185 $this->drupalGet($reset_url . '/login');
186 $this->assertLink(t('Log out'));
187 $this->assertTitle(t('@name | @site', ['@name' => $this->account->getUsername(), '@site' => $this->config('system.site')->get('name')]), 'Logged in using password reset link.');
189 // Ensure blocked and deleted accounts can't access the user.reset.login
191 $this->drupalLogout();
192 $timestamp = REQUEST_TIME - 1;
193 $blocked_account = $this->drupalCreateUser()->block();
194 $blocked_account->save();
195 $this->drupalGet("user/reset/" . $blocked_account->id() . "/$timestamp/" . user_pass_rehash($blocked_account, $timestamp) . '/login');
196 $this->assertResponse(403);
198 $blocked_account->delete();
199 $this->drupalGet("user/reset/" . $blocked_account->id() . "/$timestamp/" . user_pass_rehash($blocked_account, $timestamp) . '/login');
200 $this->assertResponse(403);
204 * Retrieves password reset email and extracts the login link.
206 public function getResetURL() {
207 // Assume the most recent email.
208 $_emails = $this->drupalGetMails();
209 $email = end($_emails);
211 preg_match('#.+user/reset/.+#', $email['body'], $urls);
217 * Test user password reset while logged in.
219 public function testUserPasswordResetLoggedIn() {
220 $another_account = $this->drupalCreateUser();
221 $this->drupalLogin($another_account);
222 $this->drupalGet('user/password');
223 $this->drupalPostForm(NULL, NULL, t('Submit'));
225 // Click the reset URL while logged and change our password.
226 $resetURL = $this->getResetURL();
227 // Log in as a different user.
228 $this->drupalLogin($this->account);
229 $this->drupalGet($resetURL);
230 $this->assertRaw(new FormattableMarkup(
231 'Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">log out</a> and try using the link again.',
232 ['%other_user' => $this->account->getUsername(), '%resetting_user' => $another_account->getUsername(), ':logout' => Url::fromRoute('user.logout')->toString()]
235 $another_account->delete();
236 $this->drupalGet($resetURL);
237 $this->assertText('The one-time login link you clicked is invalid.');
240 $this->drupalLogin($this->account);
242 // Reset the password by username via the password reset page.
243 $this->drupalGet('user/password');
244 $this->drupalPostForm(NULL, NULL, t('Submit'));
246 // Click the reset URL while logged and change our password.
247 $resetURL = $this->getResetURL();
248 $this->drupalGet($resetURL);
249 $this->drupalPostForm(NULL, NULL, t('Log in'));
251 // Change the password.
252 $password = user_password();
253 $edit = ['pass[pass1]' => $password, 'pass[pass2]' => $password];
254 $this->drupalPostForm(NULL, $edit, t('Save'));
255 $this->assertText(t('The changes have been saved.'), 'Password changed.');
257 // Logged in users should not be able to access the user.reset.login or the
258 // user.reset.form routes.
259 $timestamp = REQUEST_TIME - 1;
260 $this->drupalGet("user/reset/" . $this->account->id() . "/$timestamp/" . user_pass_rehash($this->account, $timestamp) . '/login');
261 $this->assertResponse(403);
262 $this->drupalGet("user/reset/" . $this->account->id());
263 $this->assertResponse(403);
267 * Prefill the text box on incorrect login via link to password reset page.
269 public function testUserResetPasswordTextboxFilled() {
270 $this->drupalGet('user/login');
272 'name' => $this->randomMachineName(),
273 'pass' => $this->randomMachineName(),
275 $this->drupalPostForm('user/login', $edit, t('Log in'));
276 $this->assertRaw(t('Unrecognized username or password. <a href=":password">Forgot your password?</a>',
277 [':password' => \Drupal::url('user.pass', [], ['query' => ['name' => $edit['name']]])]));
278 unset($edit['pass']);
279 $this->drupalGet('user/password', ['query' => ['name' => $edit['name']]]);
280 $this->assertFieldByName('name', $edit['name'], 'User name found.');
281 // Ensure the name field value is not cached.
282 $this->drupalGet('user/password');
283 $this->assertNoFieldByName('name', $edit['name'], 'User name not found.');
287 * Make sure that users cannot forge password reset URLs of other users.
289 public function testResetImpersonation() {
290 // Create two identical user accounts except for the user name. They must
291 // have the same empty password, so we can't use $this->drupalCreateUser().
293 $edit['name'] = $this->randomMachineName();
294 $edit['mail'] = $edit['name'] . '@example.com';
296 $user1 = User::create($edit);
299 $edit['name'] = $this->randomMachineName();
300 $user2 = User::create($edit);
303 // Unique password hashes are automatically generated, the only way to
304 // change that is to update it directly in the database.
305 db_update('users_field_data')
306 ->fields(['pass' => NULL])
307 ->condition('uid', [$user1->id(), $user2->id()], 'IN')
309 \Drupal::entityManager()->getStorage('user')->resetCache();
310 $user1 = User::load($user1->id());
311 $user2 = User::load($user2->id());
313 $this->assertEqual($user1->getPassword(), $user2->getPassword(), 'Both users have the same password hash.');
315 // The password reset URL must not be valid for the second user when only
316 // the user ID is changed in the URL.
317 $reset_url = user_pass_reset_url($user1);
318 $attack_reset_url = str_replace("user/reset/{$user1->id()}", "user/reset/{$user2->id()}", $reset_url);
319 $this->drupalGet($attack_reset_url);
320 $this->drupalPostForm(NULL, NULL, t('Log in'));
321 $this->assertNoText($user2->getUsername(), 'The invalid password reset page does not show the user name.');
322 $this->assertUrl('user/password', [], 'The user is redirected to the password reset request page.');
323 $this->assertText('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.');