You are here

AnonymousCsrfTokenGenerator.php in Anonymous CSRF Token 2.x

File

src/Access/AnonymousCsrfTokenGenerator.php
View source
<?php

namespace Drupal\anonymous_token\Access;

use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\PrivateKey;
use Drupal\Core\Session\MetadataBag;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * Class AnonymousCsrfTokenGenerator.
 *
 * @package Drupal\anonymous_token\Access
 */
class AnonymousCsrfTokenGenerator extends CsrfTokenGenerator {

  /**
   * The session.
   *
   * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
   */
  protected $session;

  /**
   * A configuration object containing settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

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

  /**
   * Constructs the token generator.
   *
   * @param \Drupal\Core\PrivateKey $private_key
   *   The private key service.
   * @param \Drupal\Core\Session\MetadataBag $session_metadata
   *   The session metadata bag.
   * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
   *   The session.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Session\AccountProxyInterface $account_proxy
   *   The account proxy.
   */
  public function __construct(PrivateKey $private_key, MetadataBag $session_metadata, SessionInterface $session, ConfigFactoryInterface $config_factory, AccountProxyInterface $account_proxy) {
    parent::__construct($private_key, $session_metadata);
    $this->session = $session;
    $this->config = $config_factory
      ->get('anonymous_token.settings');
    $this->currentUser = $account_proxy;
  }

  /**
   * {@inheritdoc}
   *
   * We need to set a value in the session for anonymous users so that the
   * session is persistent across multiple requests.
   *
   * @see https://drupal.stackexchange.com/questions/222353
   */
  public function get($value = '') {
    if ($this->session
      ->isStarted() === FALSE) {
      $this->session
        ->set('anon_session_id', $this->session
        ->getId());
    }
    return parent::get($value);
  }

  /**
   * {@inheritdoc}
   *
   * To leverage single use CSRF tokens, we reset the CSRF seed after a match.
   */
  public function validate($token, $value = '') {
    $valid = parent::validate($token, $value);
    if ($valid === TRUE && $this->currentUser
      ->isAnonymous() && (bool) $this->config
      ->get('force_single_use') === TRUE) {
      $this->sessionMetadata
        ->clearCsrfTokenSeed();
    }
    return $valid;
  }

}

Classes

Namesort descending Description
AnonymousCsrfTokenGenerator Class AnonymousCsrfTokenGenerator.