src/EventListener/KernelRequestListener.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\User;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\Routing\RouterInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  10. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  11. class KernelRequestListener
  12. {
  13.     /** @var TokenStorageInterface */
  14.     private $tokenStorage;
  15.     /** @var AuthorizationCheckerInterface */
  16.     private $authorizationChecker;
  17.     /** @var SessionInterface */
  18.     private $session;
  19.     /** @var RouterInterface */
  20.     private $router;
  21.     public function __construct(TokenStorageInterface $tokenStorageAuthorizationCheckerInterface $authorizationCheckerSessionInterface $sessionRouterInterface $router)
  22.     {
  23.         $this->tokenStorage         $tokenStorage;
  24.         $this->authorizationChecker $authorizationChecker;
  25.         $this->session              $session;
  26.         $this->router               $router;
  27.     }
  28.     public function onKernelRequest(RequestEvent $event)
  29.     {
  30.         return;
  31.         if (!$event->isMasterRequest() || !$this->isUserLoggedIn()){
  32.             return;
  33.         }
  34.         $sessionId $this->session->getId();
  35.         /** @var User $user */
  36.         $user $this->tokenStorage->getToken()->getUser();
  37.         if ($sessionId === $user->getSessionId()){
  38.             return;
  39.         }
  40.         $this->session->getFlashBag()->add('authentication'"Vous avez été déconnecté car une autre personne s'est connecté avec vos identifiants");
  41.         $redirectUrl $this->router->generate('security_logout');
  42.         $response = new RedirectResponse($redirectUrl);
  43.         $event->setResponse($response);
  44.     }
  45.     protected function isUserLoggedIn()
  46.     {
  47.         try {
  48.             return $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED');
  49.         }
  50.         catch (AuthenticationCredentialsNotFoundException $exception) {
  51.             // Ignoring this exception.
  52.         }
  53.         return false;
  54.     }
  55. }