cloud_orchestrator-3.0.0-alpha2/src/EventSubscriber/CloudOrchestratorSubscriber.php
src/EventSubscriber/CloudOrchestratorSubscriber.php
<?php
namespace Drupal\cloud_orchestrator\EventSubscriber;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Event subscriber for cloud_orchestrator profile.
*/
class CloudOrchestratorSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
private $routeMatch;
/**
* Construct a new CloudOrchestratorEventSubscriber.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* Current account.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*/
public function __construct(AccountInterface $current_user, RouteMatchInterface $route_match) {
$this->currentUser = $current_user;
$this->routeMatch = $route_match;
}
/**
* Redirect to login page if anonymous user.
*
* @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
* The response event.
*/
public function redirectIfAnon(ResponseEvent $event) {
if (!$this->currentUser->isAnonymous()) {
return;
}
$route_names = [
'user.login',
'user.pass',
'user.logout',
'user.register',
'user.reset',
'user.reset.form',
'user.reset.login',
'cloud.health_check',
'tfa.entry',
// The following are 10.1.x routes that builds aggregated CSS/JS.
// Anonymous users need to be able to access them otherwise, they can
// see a login page with no CSS/JS styling if the assets have not been
// aggregated yet.
// See https://www.drupal.org/project/drupal/issues/1014086.
'system.css_asset',
'system.js_asset',
];
if (!in_array($this->routeMatch->getRouteName(), $route_names)) {
$response = new RedirectResponse(
Url::fromRoute(
'user.login'
)->toString()
);
$event->setResponse($response);
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['redirectIfAnon'];
return $events;
}
}
