You are here

public function RedirectOnAccessDeniedSubscriber::redirectOn403 in Opigno dashboard 8

Same name and namespace in other branches
  1. 3.x src/EventSubscriber/RedirectOnAccessDeniedSubscriber.php \Drupal\opigno_dashboard\EventSubscriber\RedirectOnAccessDeniedSubscriber::redirectOn403()

Redirect if 403 and node an event.

Parameters

\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event: The route building event.

File

src/EventSubscriber/RedirectOnAccessDeniedSubscriber.php, line 49

Class

RedirectOnAccessDeniedSubscriber
Class RedirectOnAccessDeniedSubscriber.

Namespace

Drupal\opigno_dashboard\EventSubscriber

Code

public function redirectOn403(FilterResponseEvent $event) {
  $route_name = \Drupal::routeMatch()
    ->getRouteName();
  $status_code = $event
    ->getResponse()
    ->getStatusCode();
  $is_anonymous = $this->user
    ->isAnonymous();

  // Do not redirect if there is REST request.
  if (strpos($route_name, 'rest.') !== FALSE) {
    return;
  }

  // Do not redirect if there is a token authorization.
  $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);
  }
}