u3id-1.0.x-dev/src/Controller/U3idUserController.php

src/Controller/U3idUserController.php
<?php

namespace Drupal\u3id\Controller;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Flood\FloodInterface;
use Drupal\Core\Url;
use Drupal\u3id\Form\U3idUserPasswordResetForm;
use Drupal\user\Controller\UserController;
use Drupal\user\UserDataInterface;
use Drupal\user\UserInterface;
use Drupal\user\UserStorageInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Controller routines for user routes.
 */
class U3idUserController extends UserController {

  /**
   * 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;

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The flood service.
   *
   * @var \Drupal\Core\Flood\FloodInterface
   */
  protected $flood;

  /**
   * The entity repository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * 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 \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Flood\FloodInterface $flood
   *   The flood service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface|null $entity_repository
   *   The entity repository service.
   * @param \Drupal\Component\Datetime\TimeInterface|null $time
   *   The time service.
   */
  public function __construct(
    DateFormatterInterface $date_formatter,
    UserStorageInterface $user_storage,
    UserDataInterface $user_data,
    LoggerInterface $logger,
    FloodInterface $flood,
    EntityRepositoryInterface $entity_repository,
    protected TimeInterface $time,
  ) {
    $this->dateFormatter = $date_formatter;
    $this->userStorage = $user_storage;
    $this->userData = $user_data;
    $this->logger = $logger;
    $this->flood = $flood;
    $this->entityRepository = $entity_repository;
  }

  /**
   * {@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('logger.factory')->get('user'),
      $container->get('flood'),
      $container->get('entity.repository'),
      $container->get('datetime.time'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function userPage() {
    $current_user = $this->userStorage->load($this->currentUser()->id());
    return $this->redirect('u3id.user_view', ['user' => $current_user->uuid()]);
  }

  /**
   * {@inheritdoc}
   */
  public function userEditPage() {
    $current_user = $this->userStorage->load($this->currentUser()->id());
    return $this->redirect('u3id.user_edit', ['user' => $current_user->uuid()], [], 301);
  }

  /**
   * {@inheritdoc}
   */
  public function resetPass(Request $request, $u3id, $timestamp, $hash) {
    $user = $this->entityRepository->loadEntityByUuid('user', $u3id);
    // !return parent::resetPass($request, $user->id(), $timestamp, $hash);
    $uid = $user->id();

    $account = $this->currentUser();
    // 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();
        // We need to begin the redirect process again because logging out will
        // destroy the session.
        return $this->redirect(
          'u3id.reset',
          [
            'u3id' => $u3id,
            'timestamp' => $timestamp,
            'hash' => $hash,
          ]
        );
      }
      // A different user is already logged in on the computer.
      else {
        /** @var \Drupal\user\UserInterface $reset_link_user */
        $reset_link_user = $this->userStorage->load($uid);
        if ($reset_link_user && $this->validatePathParameters($reset_link_user, $timestamp, $hash)) {
          $this->messenger()
            ->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. <a href=":logout">Log out</a> and try using the link again.',
              [
                '%other_user' => $account->getAccountName(),
                '%resetting_user' => $reset_link_user->getAccountName(),
                ':logout' => Url::fromRoute('user.logout')->toString(),
              ]));
        }
        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>');
      }
    }

    /** @var \Drupal\user\UserInterface $reset_link_user */
    $reset_link_user = $this->userStorage->load($uid);
    if ($redirect = $this->determineErrorRedirect($reset_link_user, $timestamp, $hash)) {
      return $redirect;
    }

    $session = $request->getSession();
    $session->set('pass_reset_hash', $hash);
    $session->set('pass_reset_timeout', $timestamp);
    return $this->redirect(
      'u3id.reset.form',
      ['u3id' => $u3id]
    );
  }

  /**
   * {@inheritdoc}
   */
  public function resetPassLogin($u3id, $timestamp, $hash, Request $request) {
    /** @var \Drupal\user\UserInterface $user */
    $user = $this->entityRepository->loadEntityByUuid('user', $u3id);
    $uid = $user->id();

    if ($redirect = $this->determineErrorRedirect($user, $timestamp, $hash)) {
      return $redirect;
    }

    $flood_config = $this->config('user.flood');
    if ($flood_config->get('uid_only')) {
      $identifier = $user->id();
    }
    else {
      $identifier = $user->id() . '-' . $request->getClientIP();
    }

    $this->flood->clear('user.failed_login_user', $identifier);
    $this->flood->clear('user.http_login', $identifier);

    user_login_finalize($user);
    $this->logger->info('User %name used one-time login link at time %timestamp.', [
      '%name' => $user->getDisplayName(),
      '%timestamp' => $timestamp,
    ]);
    $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. It is recommended that you set your password.'));
    // Let the user's password be changed without the current password
    // check.
    $token = Crypt::randomBytesBase64(55);
    $request->getSession()->set('pass_reset_' . $user->id(), $token);
    // Clear any flood events for this user.
    $this->flood->clear('user.password_request_user', $uid);
    return $this->redirect(
      'u3id.user_edit',
      ['user' => $user->uuid()],
      [
        'query' => ['pass-reset-token' => $token],
        'absolute' => TRUE,
      ]
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getResetPassForm(Request $request, $u3id) {
    $session = $request->getSession();
    $timestamp = $session->get('pass_reset_timeout');
    $hash = $session->get('pass_reset_hash');
    // As soon as the session variables are used they are removed to prevent the
    // hash and timestamp from being leaked unexpectedly. This could occur if
    // the user does not click on the log in button on the form.
    $session->remove('pass_reset_timeout');
    $session->remove('pass_reset_hash');
    if (!$hash || !$timestamp) {
      throw new AccessDeniedHttpException();
    }

    /** @var \Drupal\user\UserInterface $user */
    $user = $this->entityRepository->loadEntityByUuid('user', $u3id);
    if ($user === NULL || !$user->isActive()) {
      // 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();
    }

    // Time out, in seconds, until login URL expires.
    $timeout = $this->config('user.settings')->get('password_reset_timeout');

    $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL;
    return $this->formBuilder()->getForm(U3idUserPasswordResetForm::class, $user, $expiration_date, $timestamp, $hash);
  }

  /**
   * {@inheritdoc}
   */
  public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass = '') {
    // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
    $timeout = 86400;

    // 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.
      if ($user->id() && $this->validatePathParameters($user, $timestamp, $hashed_pass, $timeout)) {
        $edit = [
          'user_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('<front>');
      }
      else {
        $this->messenger()->addError($this->t('You have tried to use an account cancellation link that has expired. Request a new one using the form below.'));
        return $this->redirect('u3id.user_cancel_form', ['user' => $user->uuid()], ['absolute' => TRUE]);
      }
    }
    throw new AccessDeniedHttpException();
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc