Anda dapat menguji status pengguna sangat awal dengan pelanggan acara dalam modul khusus yang berlangganan KernelEvents :: REQUEST.
Pertama, Anda mendaftarkan pelanggan acara di mymodule.services.yml
dalam folder modul Anda:
services:
mymodule.event_subscriber:
class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber
arguments: []
tags:
- {name: event_subscriber}
Kemudian tambahkan RedirectAnonymousSubscriber.php
untuk pelanggan acara kustom Anda di modul Anda di /src/EventSubscriber/
folder.
namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Event subscriber subscribing to KernelEvents::REQUEST.
*/
class RedirectAnonymousSubscriber implements EventSubscriberInterface {
public function __construct() {
$this->account = \Drupal::currentUser();
}
public function checkAuthStatus(GetResponseEvent $event) {
if ($this->account->isAnonymous() && \Drupal::routeMatch()->getRouteName() != 'user.login') {
// 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('/user/login', 301);
$event->setResponse($response);
$event->stopPropagation();
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('checkAuthStatus');
return $events;
}
}
KernelEvents::REQUEST
acara dan kemudian mengatur respons ke RedirectResponse untuk halaman login.