Skip to content

Instantly share code, notes, and snippets.

@jorislucius
Last active April 2, 2023 19:16

Revisions

  1. jorislucius revised this gist Jun 22, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion RedirectAnonymousSubscriber.php
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    <?php

    namespace Drupal\openlucius_core\EventSubscriber;
    namespace Drupal\<yourmodulename>\EventSubscriber;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  2. jorislucius created this gist Jun 22, 2017.
    44 changes: 44 additions & 0 deletions RedirectAnonymousSubscriber.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    <?php

    namespace Drupal\openlucius_core\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;
    }
    }