<?php
namespace App\EventListener;
use App\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
class KernelRequestListener
{
/** @var TokenStorageInterface */
private $tokenStorage;
/** @var AuthorizationCheckerInterface */
private $authorizationChecker;
/** @var SessionInterface */
private $session;
/** @var RouterInterface */
private $router;
public function __construct(TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authorizationChecker, SessionInterface $session, RouterInterface $router)
{
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $authorizationChecker;
$this->session = $session;
$this->router = $router;
}
public function onKernelRequest(RequestEvent $event)
{
return;
if (!$event->isMasterRequest() || !$this->isUserLoggedIn()){
return;
}
$sessionId = $this->session->getId();
/** @var User $user */
$user = $this->tokenStorage->getToken()->getUser();
if ($sessionId === $user->getSessionId()){
return;
}
$this->session->getFlashBag()->add('authentication', "Vous avez été déconnecté car une autre personne s'est connecté avec vos identifiants");
$redirectUrl = $this->router->generate('security_logout');
$response = new RedirectResponse($redirectUrl);
$event->setResponse($response);
}
protected function isUserLoggedIn()
{
try {
return $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED');
}
catch (AuthenticationCredentialsNotFoundException $exception) {
// Ignoring this exception.
}
return false;
}
}