SimplesamlSubscriber.php in simpleSAMLphp Authentication 8.3
File
src/EventSubscriber/SimplesamlSubscriber.php
View source
<?php
namespace Drupal\simplesamlphp_auth\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\simplesamlphp_auth\Service\SimplesamlphpAuthManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
class SimplesamlSubscriber implements EventSubscriberInterface {
protected $simplesaml;
protected $account;
protected $config;
protected $logger;
protected $routeMatch;
public function __construct(SimplesamlphpAuthManager $simplesaml, AccountInterface $account, ConfigFactoryInterface $config_factory, LoggerInterface $logger, RouteMatchInterface $route_match) {
$this->simplesaml = $simplesaml;
$this->account = $account;
$this->config = $config_factory
->get('simplesamlphp_auth.settings');
$this->logger = $logger;
$this->routeMatch = $route_match;
}
public function checkAuthStatus(GetResponseEvent $event) {
if ($this->account
->isAnonymous()) {
return;
}
if (!$this->simplesaml
->isActivated()) {
return;
}
if ($this->simplesaml
->isAuthenticated()) {
return;
}
if ($this->config
->get('allow.default_login')) {
$allowed_uids = explode(',', $this->config
->get('allow.default_login_users'));
if (in_array($this->account
->id(), $allowed_uids)) {
return;
}
$allowed_roles = $this->config
->get('allow.default_login_roles');
if (array_intersect($this->account
->getRoles(), $allowed_roles)) {
return;
}
}
if ($this->config
->get('debug')) {
$this->logger
->debug('User %name not authorized to log in using local account.', [
'%name' => $this->account
->getAccountName(),
]);
}
user_logout();
$response = new RedirectResponse('/', RedirectResponse::HTTP_FOUND);
$event
->setResponse($response);
$event
->stopPropagation();
}
public function login_directly_with_external_IdP(GetResponseEvent $event) {
if ($this->config
->get('allow.default_login')) {
return;
}
if ($this->account
->isAnonymous() && $this->routeMatch
->getRouteName() == 'user.login') {
$saml_login_path = Url::fromRoute('simplesamlphp_auth.saml_login')
->toString();
$response = new RedirectResponse($saml_login_path, RedirectResponse::HTTP_FOUND);
$event
->setResponse($response);
$event
->stopPropagation();
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'checkAuthStatus',
];
$events[KernelEvents::REQUEST][] = [
'login_directly_with_external_IdP',
];
return $events;
}
}