oidc-1.0.0-alpha2/src/EventSubscriber/AccessDeniedSubscriber.php

src/EventSubscriber/AccessDeniedSubscriber.php
<?php

namespace Drupal\oidc\EventSubscriber;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\oidc\Routing\ImmutableTrustedRedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Event subscriber to redirect to the login page on access denied.
 */
class AccessDeniedSubscriber extends KernelSubscriberBase {

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

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(ConfigFactoryInterface $config_factory, AccountInterface $current_user) {
    parent::__construct($config_factory);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 100];

    return $events;
  }

  /**
   * Redirect to the login page on access denied.
   *
   * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event
   *   The exception event.
   */
  public function onException(ExceptionEvent $event) {
    // Only respond to access denied.
    if (!$event->getThrowable() instanceof AccessDeniedHttpException) {
      return;
    }

    // Only respond to HTML requests, don't affect AJAX, JSON API, etc.
    if ($event->getRequest()->getRequestFormat() !== 'html') {
      return;
    }

    // Ignore if authenticated.
    if ($this->currentUser->isAuthenticated()) {
      return;
    }

    // Ignore if the redirect isn't enabled.
    if (!$this->settings->get('redirect_403')) {
      return;
    }

    // Redirect.
    $redirect = new ImmutableTrustedRedirectResponse(
      $this->getLoginUrl($event->getRequest()->getRequestUri())
    );

    $redirect->getCacheableMetadata()->addCacheContexts(['user.roles:anonymous']);

    $event->setResponse($redirect);
  }

}

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

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