3 namespace Drupal\user\Controller;
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;
19 * Controller routines for user routes.
21 class UserController extends ControllerBase {
24 * The date formatter service.
26 * @var \Drupal\Core\Datetime\DateFormatterInterface
28 protected $dateFormatter;
33 * @var \Drupal\user\UserStorageInterface
35 protected $userStorage;
38 * The user data service.
40 * @var \Drupal\user\UserDataInterface
47 * @var \Psr\Log\LoggerInterface
52 * Constructs a UserController object.
54 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
55 * The date formatter service.
56 * @param \Drupal\user\UserStorageInterface $user_storage
58 * @param \Drupal\user\UserDataInterface $user_data
59 * The user data service.
60 * @param \Psr\Log\LoggerInterface $logger
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;
73 public static function create(ContainerInterface $container) {
75 $container->get('date.formatter'),
76 $container->get('entity.manager')->getStorage('user'),
77 $container->get('user.data'),
78 $container->get('logger.factory')->get('user')
83 * Redirects to the user password reset form.
85 * In order to never disclose a reset link via a referrer header this
86 * controller must always return a redirect response.
88 * @param \Symfony\Component\HttpFoundation\Request $request
91 * User ID of the user requesting reset.
92 * @param int $timestamp
93 * The current timestamp.
97 * @return \Symfony\Component\HttpFoundation\RedirectResponse
98 * The redirect response.
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) {
108 // We need to begin the redirect process again because logging out will
109 // destroy the session.
110 return $this->redirect(
114 'timestamp' => $timestamp,
119 // A different user is already logged in on the computer.
121 /** @var \Drupal\user\UserInterface $reset_link_user */
122 if ($reset_link_user = $this->userStorage->load($uid)) {
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.',
126 '%other_user' => $account->getUsername(),
127 '%resetting_user' => $reset_link_user->getUsername(),
128 ':logout' => $this->url('user.logout'),
132 // Invalid one-time link specifies an unknown user.
133 $this->messenger()->addError($this->t('The one-time login link you clicked is invalid.'));
135 return $this->redirect('<front>');
139 $session = $request->getSession();
140 $session->set('pass_reset_hash', $hash);
141 $session->set('pass_reset_timeout', $timestamp);
142 return $this->redirect(
149 * Returns the user password reset form.
151 * @param \Symfony\Component\HttpFoundation\Request $request
154 * User ID of the user requesting reset.
156 * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
157 * The form structure or a redirect response.
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.
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();
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();
184 // Time out, in seconds, until login URL expires.
185 $timeout = $this->config('user.settings')->get('password_reset_timeout');
187 $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
188 return $this->formBuilder()->getForm(UserPasswordResetForm::class, $user, $expiration_date, $timestamp, $hash);
192 * Validates user, hash, and timestamp; logs the user in if correct.
195 * User ID of the user requesting reset.
196 * @param int $timestamp
197 * The current timestamp.
198 * @param string $hash
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.
206 * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
207 * If $uid is for a blocked user or invalid user ID.
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);
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();
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');
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
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()],
241 'query' => ['pass-reset-token' => $token],
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');
252 * Redirects users to their profile page.
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'
258 * @return \Symfony\Component\HttpFoundation\RedirectResponse
259 * Returns a redirect to the profile of the currently logged in user.
261 public function userPage() {
262 return $this->redirect('entity.user.canonical', ['user' => $this->currentUser()->id()]);
266 * Route title callback.
268 * @param \Drupal\user\UserInterface $user
271 * @return string|array
272 * The user account name as a render array or an empty string if $user is
275 public function userTitle(UserInterface $user = NULL) {
276 return $user ? ['#markup' => $user->getDisplayName(), '#allowed_tags' => Xss::getHtmlTagList()] : '';
280 * Logs the current user out.
282 * @return \Symfony\Component\HttpFoundation\RedirectResponse
283 * A redirection to home page.
285 public function logout() {
287 return $this->redirect('<front>');
291 * Confirms cancelling a user account via an email link.
293 * @param \Drupal\user\UserInterface $user
295 * @param int $timestamp
297 * @param string $hashed_pass
298 * The hashed password.
300 * @return \Symfony\Component\HttpFoundation\RedirectResponse
301 * A redirect response.
303 public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass = '') {
304 // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
306 $current = REQUEST_TIME;
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))) {
314 'user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'),
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
320 return batch_process('<front>');
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]);
327 throw new AccessDeniedHttpException();