RedirectOnAccessDeniedSubscriber.php in Opigno dashboard 3.x
File
src/EventSubscriber/RedirectOnAccessDeniedSubscriber.php
View source
<?php
namespace Drupal\opigno_dashboard\EventSubscriber;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultReasonInterface;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Http\Exception\CacheableAccessDeniedHttpException;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class RedirectOnAccessDeniedSubscriber implements EventSubscriberInterface {
protected $user;
public function __construct(AccountInterface $current_user) {
$this->user = $current_user;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_user'));
}
public function onKernelRequest(GetResponseEvent $event) {
$is_anonymous = $this->user
->isAnonymous();
$route = (string) \Drupal::routeMatch()
->getRouteName();
if ($is_anonymous && !in_array($route, [
'user.login',
'user.register',
'user.pass',
'view.frontpage.page_1',
'view.opigno_training_catalog.training_catalogue',
'system.403',
])) {
$request = $event
->getRequest();
$access_result = AccessResult::neutral();
if (!$access_result
->isAllowed()) {
if ($access_result instanceof CacheableDependencyInterface && $request
->isMethodCacheable()) {
throw new CacheableAccessDeniedHttpException($access_result, $access_result instanceof AccessResultReasonInterface ? $access_result
->getReason() : NULL);
}
else {
throw new AccessDeniedHttpException($access_result instanceof AccessResultReasonInterface ? $access_result
->getReason() : NULL);
}
}
}
}
public function redirectOn403(FilterResponseEvent $event) {
$route_name = \Drupal::routeMatch()
->getRouteName();
$status_code = $event
->getResponse()
->getStatusCode();
$is_anonymous = $this->user
->isAnonymous();
if (strpos($route_name, 'rest.') !== FALSE) {
return;
}
$auth_header = $event
->getRequest()->headers
->get('Authorization');
if ($is_anonymous && preg_match('/^Bearer (.*)/', $auth_header)) {
return;
}
if ($is_anonymous && $status_code == 403) {
$current_path = \Drupal::service('path.current')
->getPath();
$response = new RedirectResponse(\Drupal::request()
->getBasePath() . "/user/login/?prev_path={$current_path}");
$event
->setResponse($response);
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = [
'redirectOn403',
];
return $events;
}
}