Skip to content

Instantly share code, notes, and snippets.

@druman
Created February 24, 2018 11:42
Show Gist options
  • Save druman/26c126434ca4cb849d169cbb03040082 to your computer and use it in GitHub Desktop.
Save druman/26c126434ca4cb849d169cbb03040082 to your computer and use it in GitHub Desktop.
Drupal 8
<?php
// Make sure we are not on the user login route.
if (\Drupal::routeMatch()->getRouteName() == 'user.login') {
return;
}
// Check if the current user is logged in.
if (\Drupal::currentUser()->isAnonymous()) {
return;
}
// Redirect to user/login page
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestSubscriber implements EventSubscriberInterface {
// ....
$url = Url::fromRoute('user.login')->toString();
$redirect = new RedirectResponse($url);
// Set the redirect response on the event, cancelling default response.
$event->setResponse($redirect);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment