Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / user / tests / src / Functional / UserPasswordResetTest.php
1 <?php
2
3 namespace Drupal\Tests\user\Functional;
4
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Test\AssertMailTrait;
7 use Drupal\Core\Url;
8 use Drupal\Tests\system\Functional\Cache\PageCacheTagsTestBase;
9 use Drupal\user\Entity\User;
10
11 /**
12  * Ensure that password reset methods work as expected.
13  *
14  * @group user
15  */
16 class UserPasswordResetTest extends PageCacheTagsTestBase {
17
18   use AssertMailTrait {
19     getMails as drupalGetMails;
20   }
21
22   /**
23    * The user object to test password resetting.
24    *
25    * @var \Drupal\user\UserInterface
26    */
27   protected $account;
28
29   /**
30    * Modules to enable.
31    *
32    * @var array
33    */
34   public static $modules = ['block'];
35
36   /**
37    * {@inheritdoc}
38    */
39   protected function setUp() {
40     parent::setUp();
41
42     $this->drupalPlaceBlock('system_menu_block:account');
43
44     // Create a user.
45     $account = $this->drupalCreateUser();
46
47     // Activate user by logging in.
48     $this->drupalLogin($account);
49
50     $this->account = User::load($account->id());
51     $this->account->passRaw = $account->passRaw;
52     $this->drupalLogout();
53
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())
60       ->execute();
61   }
62
63   /**
64    * Tests password reset functionality.
65    */
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);
71
72     // Try to reset the password for an invalid account.
73     $this->drupalGet('user/password');
74
75     $edit = ['name' => $this->randomMachineName(32)];
76     $this->drupalPostForm(NULL, $edit, t('Submit'));
77
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.');
80
81     // Reset the password by username via the password reset page.
82     $edit['name'] = $this->account->getUsername();
83     $this->drupalPostForm(NULL, $edit, t('Submit'));
84
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.');
89
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()]));
94
95     $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'));
96
97     // Ensure the password reset URL is not cached.
98     $this->drupalGet($resetURL);
99     $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'));
100
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".');
105
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.');
110
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.');
116
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.');
120
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.');
126
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.');
134
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();
143
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.');
151
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);
158
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');
167
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.');
178
179     // Verify a password reset link will automatically log a user when /login is
180     // appended.
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.');
188
189     // Ensure blocked and deleted accounts can't access the user.reset.login
190     // route.
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);
197
198     $blocked_account->delete();
199     $this->drupalGet("user/reset/" . $blocked_account->id() . "/$timestamp/" . user_pass_rehash($blocked_account, $timestamp) . '/login');
200     $this->assertResponse(403);
201   }
202
203   /**
204    * Retrieves password reset email and extracts the login link.
205    */
206   public function getResetURL() {
207     // Assume the most recent email.
208     $_emails = $this->drupalGetMails();
209     $email = end($_emails);
210     $urls = [];
211     preg_match('#.+user/reset/.+#', $email['body'], $urls);
212
213     return $urls[0];
214   }
215
216   /**
217    * Test user password reset while logged in.
218    */
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'));
224
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()]
233     ));
234
235     $another_account->delete();
236     $this->drupalGet($resetURL);
237     $this->assertText('The one-time login link you clicked is invalid.');
238
239     // Log in.
240     $this->drupalLogin($this->account);
241
242     // Reset the password by username via the password reset page.
243     $this->drupalGet('user/password');
244     $this->drupalPostForm(NULL, NULL, t('Submit'));
245
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'));
250
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.');
256
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);
264   }
265
266   /**
267    * Prefill the text box on incorrect login via link to password reset page.
268    */
269   public function testUserResetPasswordTextboxFilled() {
270     $this->drupalGet('user/login');
271     $edit = [
272       'name' => $this->randomMachineName(),
273       'pass' => $this->randomMachineName(),
274     ];
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.');
284   }
285
286   /**
287    * Make sure that users cannot forge password reset URLs of other users.
288    */
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().
292     $edit = [];
293     $edit['name'] = $this->randomMachineName();
294     $edit['mail'] = $edit['name'] . '@example.com';
295     $edit['status'] = 1;
296     $user1 = User::create($edit);
297     $user1->save();
298
299     $edit['name'] = $this->randomMachineName();
300     $user2 = User::create($edit);
301     $user2->save();
302
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')
308       ->execute();
309     \Drupal::entityManager()->getStorage('user')->resetCache();
310     $user1 = User::load($user1->id());
311     $user2 = User::load($user2->id());
312
313     $this->assertEqual($user1->getPassword(), $user2->getPassword(), 'Both users have the same password hash.');
314
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.');
324   }
325
326 }