You are here

class ChangePwdPageController in Password Separate Form 8

Controller routines for user routes.

Hierarchy

Expanded class hierarchy of ChangePwdPageController

File

src/Controller/ChangePwdPageController.php, line 17

Namespace

Drupal\change_pwd_page\Controller
View source
class ChangePwdPageController extends ControllerBase {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

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

  /**
   * The user data service.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $userData;

  /**
   * The Datetime interface.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * Constructs a UserController object.
   *
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The datetime service.
   */
  public function __construct(DateFormatterInterface $date_formatter, UserStorageInterface $user_storage, UserDataInterface $user_data, TimeInterface $time) {
    $this->dateFormatter = $date_formatter;
    $this->userStorage = $user_storage;
    $this->userData = $user_data;
    $this->time = $time;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('date.formatter'), $container
      ->get('entity_type.manager')
      ->getStorage('user'), $container
      ->get('user.data'), $container
      ->get('datetime.time'));
  }

  /**
   * Redirects users to their password change form.
   *
   * This controller assumes that it is only invoked for authenticated users.
   * This is enforced for the 'change_pwd_page.change_password' route with the
   * '_user_is_logged_in' requirement.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns a redirect to the password change form of the currently logged in
   *   user.
   */
  public function changePass() {
    return $this
      ->redirect('change_pwd_page.change_password_form', [
      'user' => $this
        ->currentUser()
        ->id(),
    ]);
  }

  /**
   * 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) {
        user_logout();
      }
      else {
        if ($reset_link_user = $this->userStorage
          ->load($uid)) {
          $this
            ->messenger()
            ->addMessage($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.', [
            '%other_user' => $account
              ->getDisplayName(),
            '%resetting_user' => $reset_link_user
              ->getDisplayName(),
            ':logout' => Url::fromRoute('user.logout')
              ->toString(),
          ]), 'warning');
        }
        else {

          // Invalid one-time link specifies an unknown user.
          $this
            ->messenger()
            ->addError($this
            ->t('The one-time login link you clicked is invalid.'));
        }
        return $this
          ->redirect('<front>');
      }
    }

    // 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 = $this->time
      ->getRequestTime();

    /* @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) {
        $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.'));
        return $this
          ->redirect('user.pass');
      }
      elseif ($user
        ->isAuthenticated() && $timestamp >= $user
        ->getLastLoginTime() && $timestamp <= $current && hash_equals($hash, user_pass_rehash($user, $timestamp))) {
        $expiration_date = $user
          ->getLastLoginTime() ? $this->dateFormatter
          ->format($timestamp + $timeout) : NULL;
        return $this
          ->formBuilder()
          ->getForm('Drupal\\change_pwd_page\\Form\\ChangePasswordResetForm', $user, $expiration_date, $timestamp, $hash);
      }
      else {
        $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.'));
        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();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ChangePwdPageController::$dateFormatter protected property The date formatter service.
ChangePwdPageController::$time protected property The Datetime interface.
ChangePwdPageController::$userData protected property The user data service.
ChangePwdPageController::$userStorage protected property The user storage.
ChangePwdPageController::changePass public function Redirects users to their password change form.
ChangePwdPageController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
ChangePwdPageController::resetPass public function Returns the user password reset page.
ChangePwdPageController::__construct public function Constructs a UserController object.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.