You are here

class Redirect in Entity Legal 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/EntityLegal/Redirect.php \Drupal\entity_legal\Plugin\EntityLegal\Redirect
  2. 4.0.x src/Plugin/EntityLegal/Redirect.php \Drupal\entity_legal\Plugin\EntityLegal\Redirect

Method class for redirecting existing users to accept a legal document.

Plugin annotation


@EntityLegal(
  id = "redirect",
  label = @Translation("Redirect every page load to legal document until accepted"),
  type = "existing_users",
)

Hierarchy

Expanded class hierarchy of Redirect

File

src/Plugin/EntityLegal/Redirect.php, line 27

Namespace

Drupal\entity_legal\Plugin\EntityLegal
View source
class Redirect extends EntityLegalPluginBase implements ContainerFactoryPluginInterface {
  use MessengerTrait;
  use RedirectDestinationTrait;
  use StringTranslationTrait;

  /**
   * The current route match service.
   *
   * @var \Drupal\Core\Routing\ResettableStackedRouteMatchInterface
   */
  protected $routeMatch;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The private temp store.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStore
   */
  protected $tempStore;

  /**
   * Constructs a new plugin instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Routing\ResettableStackedRouteMatchInterface $route_match
   *   The current route match service.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $private_temp_store_factory
   *   The private temp store factory service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ResettableStackedRouteMatchInterface $route_match, AccountProxyInterface $current_user, PrivateTempStoreFactory $private_temp_store_factory) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->routeMatch = $route_match;
    $this->currentUser = $current_user;
    $this->tempStore = $private_temp_store_factory
      ->get('entity_legal');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('current_route_match'), $container
      ->get('current_user'), $container
      ->get('tempstore.private'));
  }

  /**
   * {@inheritdoc}
   */
  public function execute(array &$context = []) {

    /** @var \Drupal\entity_legal\EntityLegalDocumentInterface $document */
    foreach ($this->documents as $document) {

      /** @var \Symfony\Component\HttpKernel\Event\GetResponseEvent $event */
      $event = $context['event'];
      $request = $event
        ->getRequest();

      // The acceptance of a legal document is applicable only to humans.
      if ($request
        ->getRequestFormat() !== 'html') {
        return FALSE;
      }

      // Don't redirect on POST requests.
      if (!$request
        ->isMethodSafe()) {
        return FALSE;
      }
      if (!($route_name = $this->routeMatch
        ->getRouteName())) {

        // Unrouted?
        return FALSE;
      }
      if ($this
        ->isExcludedRoute($route_name, $document)) {
        return FALSE;
      }

      // Do not redirect password reset.
      if ($this
        ->isPasswordReset($event
        ->getRequest())) {
        return FALSE;
      }
      if ($messages = $this
        ->messenger()
        ->all()) {

        // Save any messages set for the destination page.
        // @see \Drupal\entity_legal\Form\EntityLegalDocumentAcceptanceForm::submitForm()
        $this->tempStore
          ->set('postponed_messages', $messages);
        $this
          ->messenger()
          ->deleteAll();
      }
      $this
        ->messenger()
        ->addWarning($this
        ->t('You must accept this agreement before continuing.'));
      $entity_url = $document
        ->toUrl()
        ->setOption('query', $this
        ->getDestinationArray())
        ->setAbsolute(TRUE)
        ->toString();
      $event
        ->setResponse(new TrustedRedirectResponse($entity_url));

      // Remove destination cause the RedirectResponseSubscriber redirects and
      // in some cases it brings redirect loops.
      $request->query
        ->remove('destination');
      $request->request
        ->remove('destination');
    }
  }

  /**
   * Checks if the current route is excluded.
   *
   * @param string $route_name
   *   The route name.
   * @param \Drupal\entity_legal\EntityLegalDocumentInterface $document
   *   The legal document entity.
   *
   * @return bool
   *   If the current route is excluded.
   */
  protected function isExcludedRoute($route_name, EntityLegalDocumentInterface $document) {
    $excluded_routes = [
      'system.csrftoken',
      'user.logout',
      $document
        ->toUrl()
        ->getRouteName(),
    ];
    return in_array($route_name, $excluded_routes);
  }

  /**
   * Check if this is a valid password reset request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The HTTP request object.
   *
   * @return bool
   *   If this is a valid password reset request.
   */
  protected function isPasswordReset(Request $request) {

    // Unblock only the current user account edit form.
    if ($this->routeMatch
      ->getRouteName() !== 'entity.user.edit_form' && $this->routeMatch
      ->getRawParameter('user') != $this->currentUser
      ->id()) {
      return FALSE;
    }

    // The password reset token should be present.
    if (!($pass_reset_token = $request
      ->get('pass-reset-token'))) {
      return FALSE;
    }

    // Now we check if it's a valid token.
    // @see \Drupal\user\Controller\UserController::resetPassLogin()
    // @see \Drupal\user\AccountForm::form()
    $session_key = "pass_reset_{$this->currentUser->id()}";
    if (!isset($_SESSION[$session_key]) || !hash_equals($_SESSION[$session_key], $pass_reset_token)) {
      return FALSE;
    }
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
EntityLegalPluginBase::$documents protected property The legal documents that implement this plugin.
EntityLegalPluginBase::getDocumentsForMethod public function Get all Entity Legal Documents for this plugin.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
Redirect::$currentUser protected property The current user.
Redirect::$routeMatch protected property The current route match service.
Redirect::$tempStore protected property The private temp store.
Redirect::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
Redirect::execute public function Execute callback for Entity Legal method plugin. Overrides EntityLegalPluginInterface::execute
Redirect::isExcludedRoute protected function Checks if the current route is excluded.
Redirect::isPasswordReset protected function Check if this is a valid password reset request.
Redirect::__construct public function Constructs a new plugin instance. Overrides EntityLegalPluginBase::__construct
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. 4
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.