UserController.php 8.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\user\Controller\UserController.
 */

namespace Drupal\user\Controller;

10
use Drupal\Component\Utility\Xss;
11
use Drupal\Core\Controller\ControllerBase;
12 13
use Drupal\Core\Datetime\DateFormatter;
use Drupal\user\UserDataInterface;
14
use Drupal\user\UserInterface;
15
use Drupal\user\UserStorageInterface;
16 17
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
18 19 20 21

/**
 * Controller routines for user routes.
 */
22
class UserController extends ControllerBase {
23

24
  /**
25
   * The date formatter service.
26
   *
27
   * @var \Drupal\Core\Datetime\DateFormatter
28
   */
29
  protected $dateFormatter;
30 31 32 33 34 35 36 37

  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;

38 39 40 41 42 43 44
  /**
   * The user data service.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $userData;

45 46 47
  /**
   * Constructs a UserController object.
   *
48
   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
49
   *   The date formatter service.
50 51
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
52 53
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
54
   */
55
  public function __construct(DateFormatter $date_formatter, UserStorageInterface $user_storage, UserDataInterface $user_data) {
56
    $this->dateFormatter = $date_formatter;
57
    $this->userStorage = $user_storage;
58
    $this->userData = $user_data;
59 60 61 62 63 64 65
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
66
      $container->get('date.formatter'),
67
      $container->get('entity.manager')->getStorage('user'),
68
      $container->get('user.data')
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    );
  }

  /**
   * Returns the user password reset page.
   *
   * @param int $uid
   *   UID of user requesting reset.
   * @param int $timestamp
   *   The current timestamp.
   * @param string $hash
   *   Login link hash.
   *
   * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
   *   The form structure or a redirect response.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   *   If the login link is for a blocked user or invalid user ID.
   */
  public function resetPass($uid, $timestamp, $hash) {
    $account = $this->currentUser();
    $config = $this->config('user.settings');
    // When processing the one-time login link, we have to make sure that a user
    // isn't already logged in.
    if ($account->isAuthenticated()) {
      // The current user is already logged in.
      if ($account->id() == $uid) {
96
        drupal_set_message($this->t('You are logged in as %user. <a href="@user_edit">Change your password.</a>', array('%user' => $account->getUsername(), '@user_edit' => $this->url('entity.user.edit_form', array('user' => $account->id())))));
97 98 99 100
      }
      // A different user is already logged in on the computer.
      else {
        if ($reset_link_user = $this->userStorage->load($uid)) {
101 102
          drupal_set_message($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">logout</a> and try using the link again.',
            array('%other_user' => $account->getUsername(), '%resetting_user' => $reset_link_user->getUsername(), '@logout' => $this->url('user.logout'))));
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        }
        else {
          // Invalid one-time link specifies an unknown user.
          drupal_set_message($this->t('The one-time login link you clicked is invalid.'));
        }
      }
      return $this->redirect('<front>');
    }
    else {
      // The current user is not logged in, so check the parameters.
      // Time out, in seconds, until login URL expires.
      $timeout = $config->get('password_reset_timeout');
      $current = REQUEST_TIME;
      /* @var \Drupal\user\UserInterface $user */
      $user = $this->userStorage->load($uid);
      // Verify that the user exists and is active.
      if ($user && $user->isActive()) {
        // No time out for first time login.
        if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
          drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'));
          return $this->redirect('user.pass');
        }
125
        elseif ($user->isAuthenticated() && ($timestamp >= $user->getLastLoginTime()) && ($timestamp <= $current) && ($hash === user_pass_rehash($user->getPassword(), $timestamp, $user->getLastLoginTime(), $user->id()))) {
126
          $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
127 128 129 130 131 132 133 134 135 136 137 138 139
          return $this->formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm', $user, $expiration_date, $timestamp, $hash);
        }
        else {
          drupal_set_message($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.'));
          return $this->redirect('user.pass');
        }
      }
    }
    // Blocked or invalid user ID, so deny access. The parameters will be in the
    // watchdog's URL for the administrator to check.
    throw new AccessDeniedHttpException();
  }

140
  /**
141
   * Redirects users to their profile page.
142
   *
143 144 145
   * This controller assumes that it is only invoked for authenticated users.
   * This is enforced for the 'user.page' route with the '_user_is_logged_in'
   * requirement.
146
   *
147 148
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns a redirect to the profile of the currently logged in user.
149
   */
150
  public function userPage() {
151
    return $this->redirect('entity.user.canonical', array('user' => $this->currentUser()->id()));
152 153
  }

154 155 156 157 158 159 160 161 162 163 164 165 166
  /**
   * Route title callback.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   *
   * @return string
   *   The user account name.
   */
  public function userTitle(UserInterface $user = NULL) {
    return $user ? Xss::filter($user->getUsername()) : '';
  }

167 168 169 170 171 172
  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
173
  public function logout() {
174
    user_logout();
175
    return $this->redirect('<front>');
176 177
  }

178
  /**
179 180 181 182 183 184 185 186 187 188 189
   * Confirms cancelling a user account via an email link.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   * @param int $timestamp
   *   The timestamp.
   * @param string $hashed_pass
   *   The hashed password.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response.
190 191
   */
  public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass = '') {
192 193 194 195 196 197 198 199
    // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
    $timeout = 86400;
    $current = REQUEST_TIME;

    // Basic validation of arguments.
    $account_data = $this->userData->get('user', $user->id());
    if (isset($account_data['cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) {
      // Validate expiration and hashed password/login.
200
      if ($timestamp <= $current && $current - $timestamp < $timeout && $user->id() && $timestamp >= $user->getLastLoginTime() && $hashed_pass == user_pass_rehash($user->getPassword(), $timestamp, $user->getLastLoginTime(), $user->id())) {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        $edit = array(
          'user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'),
        );
        user_cancel($edit, $user->id(), $account_data['cancel_method']);
        // Since user_cancel() is not invoked via Form API, batch processing
        // needs to be invoked manually and should redirect to the front page
        // after completion.
        return batch_process('');
      }
      else {
        drupal_set_message(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'));
        return $this->redirect('entity.user.cancel_form', ['user' => $user->id()], ['absolute' => TRUE]);
      }
    }
    throw new AccessDeniedHttpException();
216 217
  }

218
}