Forked from jorislucius/RedirectAnonymousSubscriber.php
Created
February 6, 2018 11:17
-
-
Save kabanon/2e647b18082516bbd6d33d3f8ab5f1a4 to your computer and use it in GitHub Desktop.
Drupal 8 | Redirect all anonymous users to login page. With a few needed exceptions like /user/password
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\<yourmodulename>\EventSubscriber; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\HttpKernel\KernelEvents; | |
/** | |
* Event subscriber subscribing to KernelEvents::REQUEST. | |
*/ | |
class RedirectAnonymousSubscriber implements EventSubscriberInterface { | |
public function checkAuthStatus(GetResponseEvent $event) { | |
global $base_url; | |
if ( | |
\Drupal::currentUser()->isAnonymous() && | |
\Drupal::routeMatch()->getRouteName() != 'user.login' && | |
\Drupal::routeMatch()->getRouteName() != 'user.reset' && | |
\Drupal::routeMatch()->getRouteName() != 'user.reset.form' && | |
\Drupal::routeMatch()->getRouteName() != 'user.reset.login' && | |
\Drupal::routeMatch()->getRouteName() != 'user.pass' ) { | |
// add logic to check other routes you want available to anonymous users, | |
// otherwise, redirect to login page. | |
$route_name = \Drupal::routeMatch()->getRouteName(); | |
if (strpos($route_name, 'view') === 0 && strpos($route_name, 'rest_') !== FALSE) { | |
return; | |
} | |
$response = new RedirectResponse($base_url . '/user/login', 301); | |
$event->setResponse($response); | |
$event->stopPropagation(); | |
return; | |
} | |
} | |
public static function getSubscribedEvents() { | |
$events[KernelEvents::REQUEST][] = array('checkAuthStatus'); | |
return $events; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment