src/EventSubscriber/UserLoginRedirectSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Cookie;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Security;
  11. class UserLoginRedirectSubscriber implements EventSubscriberInterface
  12. {
  13.     public const REDIRECT_TO_MS_LOGIN 'app_rtmsl';
  14.     private $security;
  15.     private $router;
  16.     private $parameterBag;
  17.     public function __construct(Security $securityUrlGeneratorInterface $routerParameterBagInterface $parameterBag)
  18.     {
  19.         $this->security $security;
  20.         $this->router $router;
  21.         $this->parameterBag $parameterBag;
  22.     }
  23.     public function onRequest(RequestEvent $event): void
  24.     {
  25.         if (!$event->isMasterRequest() ||
  26.             !$this->parameterBag->get('app_redirect_to_ms_on_login') ||
  27.             'sonata_user_admin_security_login' !== $event->getRequest()->get('_route') ||
  28.             $event->getRequest()->cookies->get(self::REDIRECT_TO_MS_LOGIN) ||
  29.             $this->security->getUser()
  30.         ) {
  31.             return;
  32.         }
  33.         $response = new RedirectResponse(
  34.             $this->router->generate(
  35.                 'hwi_oauth_service_redirect',
  36.                 ['service' => 'azure']
  37.             )
  38.         );
  39.         $response->headers->setCookie(Cookie::create(self::REDIRECT_TO_MS_LOGIN'1'));
  40.         $response->send();
  41.         exit();
  42.     }
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [
  46.             KernelEvents::REQUEST => [['onRequest'20]],
  47.         ];
  48.     }
  49. }