<?php
namespace App\EventSubscriber;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class UserLoginRedirectSubscriber implements EventSubscriberInterface
{
public const REDIRECT_TO_MS_LOGIN = 'app_rtmsl';
private $security;
private $router;
private $parameterBag;
public function __construct(Security $security, UrlGeneratorInterface $router, ParameterBagInterface $parameterBag)
{
$this->security = $security;
$this->router = $router;
$this->parameterBag = $parameterBag;
}
public function onRequest(RequestEvent $event): void
{
if (!$event->isMasterRequest() ||
!$this->parameterBag->get('app_redirect_to_ms_on_login') ||
'sonata_user_admin_security_login' !== $event->getRequest()->get('_route') ||
$event->getRequest()->cookies->get(self::REDIRECT_TO_MS_LOGIN) ||
$this->security->getUser()
) {
return;
}
$response = new RedirectResponse(
$this->router->generate(
'hwi_oauth_service_redirect',
['service' => 'azure']
)
);
$response->headers->setCookie(Cookie::create(self::REDIRECT_TO_MS_LOGIN, '1'));
$response->send();
exit();
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onRequest', 20]],
];
}
}