09544aa63802fb93d1b68270a11acc054f46838c
[yaffs-website] / web / core / modules / user / src / Controller / UserController.php
1 <?php
2
3 namespace Drupal\user\Controller;
4
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Component\Utility\Xss;
7 use Drupal\Core\Controller\ControllerBase;
8 use Drupal\Core\Datetime\DateFormatterInterface;
9 use Drupal\user\Form\UserPasswordResetForm;
10 use Drupal\user\UserDataInterface;
11 use Drupal\user\UserInterface;
12 use Drupal\user\UserStorageInterface;
13 use Psr\Log\LoggerInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
17
18 /**
19  * Controller routines for user routes.
20  */
21 class UserController extends ControllerBase {
22
23   /**
24    * The date formatter service.
25    *
26    * @var \Drupal\Core\Datetime\DateFormatterInterface
27    */
28   protected $dateFormatter;
29
30   /**
31    * The user storage.
32    *
33    * @var \Drupal\user\UserStorageInterface
34    */
35   protected $userStorage;
36
37   /**
38    * The user data service.
39    *
40    * @var \Drupal\user\UserDataInterface
41    */
42   protected $userData;
43
44   /**
45    * A logger instance.
46    *
47    * @var \Psr\Log\LoggerInterface
48    */
49   protected $logger;
50
51   /**
52    * Constructs a UserController object.
53    *
54    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
55    *   The date formatter service.
56    * @param \Drupal\user\UserStorageInterface $user_storage
57    *   The user storage.
58    * @param \Drupal\user\UserDataInterface $user_data
59    *   The user data service.
60    * @param \Psr\Log\LoggerInterface $logger
61    *   A logger instance.
62    */
63   public function __construct(DateFormatterInterface $date_formatter, UserStorageInterface $user_storage, UserDataInterface $user_data, LoggerInterface $logger) {
64     $this->dateFormatter = $date_formatter;
65     $this->userStorage = $user_storage;
66     $this->userData = $user_data;
67     $this->logger = $logger;
68   }
69
70   /**
71    * {@inheritdoc}
72    */
73   public static function create(ContainerInterface $container) {
74     return new static(
75       $container->get('date.formatter'),
76       $container->get('entity.manager')->getStorage('user'),
77       $container->get('user.data'),
78       $container->get('logger.factory')->get('user')
79     );
80   }
81
82   /**
83    * Redirects to the user password reset form.
84    *
85    * In order to never disclose a reset link via a referrer header this
86    * controller must always return a redirect response.
87    *
88    * @param \Symfony\Component\HttpFoundation\Request $request
89    *   The request.
90    * @param int $uid
91    *   User ID of the user requesting reset.
92    * @param int $timestamp
93    *   The current timestamp.
94    * @param string $hash
95    *   Login link hash.
96    *
97    * @return \Symfony\Component\HttpFoundation\RedirectResponse
98    *   The redirect response.
99    */
100   public function resetPass(Request $request, $uid, $timestamp, $hash) {
101     $account = $this->currentUser();
102     // When processing the one-time login link, we have to make sure that a user
103     // isn't already logged in.
104     if ($account->isAuthenticated()) {
105       // The current user is already logged in.
106       if ($account->id() == $uid) {
107         user_logout();
108         // We need to begin the redirect process again because logging out will
109         // destroy the session.
110         return $this->redirect(
111           'user.reset',
112           [
113             'uid' => $uid,
114             'timestamp' => $timestamp,
115             'hash' => $hash,
116           ]
117         );
118       }
119       // A different user is already logged in on the computer.
120       else {
121         /** @var \Drupal\user\UserInterface $reset_link_user */
122         if ($reset_link_user = $this->userStorage->load($uid)) {
123           $this->messenger()
124             ->addWarning($this->t('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.',
125               [
126                 '%other_user' => $account->getUsername(),
127                 '%resetting_user' => $reset_link_user->getUsername(),
128                 ':logout' => $this->url('user.logout'),
129               ]));
130         }
131         else {
132           // Invalid one-time link specifies an unknown user.
133           $this->messenger()->addError($this->t('The one-time login link you clicked is invalid.'));
134         }
135         return $this->redirect('<front>');
136       }
137     }
138
139     $session = $request->getSession();
140     $session->set('pass_reset_hash', $hash);
141     $session->set('pass_reset_timeout', $timestamp);
142     return $this->redirect(
143       'user.reset.form',
144       ['uid' => $uid]
145     );
146   }
147
148   /**
149    * Returns the user password reset form.
150    *
151    * @param \Symfony\Component\HttpFoundation\Request $request
152    *   The request.
153    * @param int $uid
154    *   User ID of the user requesting reset.
155    *
156    * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
157    *   The form structure or a redirect response.
158    *
159    * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
160    *   If the pass_reset_timeout or pass_reset_hash are not available in the
161    *   session. Or if $uid is for a blocked user or invalid user ID.
162    */
163   public function getResetPassForm(Request $request, $uid) {
164     $session = $request->getSession();
165     $timestamp = $session->get('pass_reset_timeout');
166     $hash = $session->get('pass_reset_hash');
167     // As soon as the session variables are used they are removed to prevent the
168     // hash and timestamp from being leaked unexpectedly. This could occur if
169     // the user does not click on the log in button on the form.
170     $session->remove('pass_reset_timeout');
171     $session->remove('pass_reset_hash');
172     if (!$hash || !$timestamp) {
173       throw new AccessDeniedHttpException();
174     }
175
176     /** @var \Drupal\user\UserInterface $user */
177     $user = $this->userStorage->load($uid);
178     if ($user === NULL || !$user->isActive()) {
179       // Blocked or invalid user ID, so deny access. The parameters will be in
180       // the watchdog's URL for the administrator to check.
181       throw new AccessDeniedHttpException();
182     }
183
184     // Time out, in seconds, until login URL expires.
185     $timeout = $this->config('user.settings')->get('password_reset_timeout');
186
187     $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
188     return $this->formBuilder()->getForm(UserPasswordResetForm::class, $user, $expiration_date, $timestamp, $hash);
189   }
190
191   /**
192    * Validates user, hash, and timestamp; logs the user in if correct.
193    *
194    * @param int $uid
195    *   User ID of the user requesting reset.
196    * @param int $timestamp
197    *   The current timestamp.
198    * @param string $hash
199    *   Login link hash.
200    *
201    * @return \Symfony\Component\HttpFoundation\RedirectResponse
202    *   Returns a redirect to the user edit form if the information is correct.
203    *   If the information is incorrect redirects to 'user.pass' route with a
204    *   message for the user.
205    *
206    * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
207    *   If $uid is for a blocked user or invalid user ID.
208    */
209   public function resetPassLogin($uid, $timestamp, $hash) {
210     // The current user is not logged in, so check the parameters.
211     $current = REQUEST_TIME;
212     /** @var \Drupal\user\UserInterface $user */
213     $user = $this->userStorage->load($uid);
214
215     // Verify that the user exists and is active.
216     if ($user === NULL || !$user->isActive()) {
217       // Blocked or invalid user ID, so deny access. The parameters will be in
218       // the watchdog's URL for the administrator to check.
219       throw new AccessDeniedHttpException();
220     }
221
222     // Time out, in seconds, until login URL expires.
223     $timeout = $this->config('user.settings')->get('password_reset_timeout');
224     // No time out for first time login.
225     if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
226       $this->messenger()->addError($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'));
227       return $this->redirect('user.pass');
228     }
229     elseif ($user->isAuthenticated() && ($timestamp >= $user->getLastLoginTime()) && ($timestamp <= $current) && Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp))) {
230       user_login_finalize($user);
231       $this->logger->notice('User %name used one-time login link at time %timestamp.', ['%name' => $user->getDisplayName(), '%timestamp' => $timestamp]);
232       $this->messenger()->addStatus($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
233       // Let the user's password be changed without the current password
234       // check.
235       $token = Crypt::randomBytesBase64(55);
236       $_SESSION['pass_reset_' . $user->id()] = $token;
237       return $this->redirect(
238         'entity.user.edit_form',
239         ['user' => $user->id()],
240         [
241           'query' => ['pass-reset-token' => $token],
242           'absolute' => TRUE,
243         ]
244       );
245     }
246
247     $this->messenger()->addError($this->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.'));
248     return $this->redirect('user.pass');
249   }
250
251   /**
252    * Redirects users to their profile page.
253    *
254    * This controller assumes that it is only invoked for authenticated users.
255    * This is enforced for the 'user.page' route with the '_user_is_logged_in'
256    * requirement.
257    *
258    * @return \Symfony\Component\HttpFoundation\RedirectResponse
259    *   Returns a redirect to the profile of the currently logged in user.
260    */
261   public function userPage() {
262     return $this->redirect('entity.user.canonical', ['user' => $this->currentUser()->id()]);
263   }
264
265   /**
266    * Route title callback.
267    *
268    * @param \Drupal\user\UserInterface $user
269    *   The user account.
270    *
271    * @return string|array
272    *   The user account name as a render array or an empty string if $user is
273    *   NULL.
274    */
275   public function userTitle(UserInterface $user = NULL) {
276     return $user ? ['#markup' => $user->getDisplayName(), '#allowed_tags' => Xss::getHtmlTagList()] : '';
277   }
278
279   /**
280    * Logs the current user out.
281    *
282    * @return \Symfony\Component\HttpFoundation\RedirectResponse
283    *   A redirection to home page.
284    */
285   public function logout() {
286     user_logout();
287     return $this->redirect('<front>');
288   }
289
290   /**
291    * Confirms cancelling a user account via an email link.
292    *
293    * @param \Drupal\user\UserInterface $user
294    *   The user account.
295    * @param int $timestamp
296    *   The timestamp.
297    * @param string $hashed_pass
298    *   The hashed password.
299    *
300    * @return \Symfony\Component\HttpFoundation\RedirectResponse
301    *   A redirect response.
302    */
303   public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass = '') {
304     // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
305     $timeout = 86400;
306     $current = REQUEST_TIME;
307
308     // Basic validation of arguments.
309     $account_data = $this->userData->get('user', $user->id());
310     if (isset($account_data['cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) {
311       // Validate expiration and hashed password/login.
312       if ($timestamp <= $current && $current - $timestamp < $timeout && $user->id() && $timestamp >= $user->getLastLoginTime() && Crypt::hashEquals($hashed_pass, user_pass_rehash($user, $timestamp))) {
313         $edit = [
314           'user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'),
315         ];
316         user_cancel($edit, $user->id(), $account_data['cancel_method']);
317         // Since user_cancel() is not invoked via Form API, batch processing
318         // needs to be invoked manually and should redirect to the front page
319         // after completion.
320         return batch_process('<front>');
321       }
322       else {
323         $this->messenger()->addError($this->t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'));
324         return $this->redirect('entity.user.cancel_form', ['user' => $user->id()], ['absolute' => TRUE]);
325       }
326     }
327     throw new AccessDeniedHttpException();
328   }
329
330 }