<?php
namespace App\EventListener;
use App\Security\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Security;
class RefreshTokenValidator
{
/** @var UrlGeneratorInterface */
protected $urlGenerator;
/** @var TokenStorageInterface */
protected $token;
/** @var FlashBagInterface */
protected $flashBag;
/** @var Security */
protected $security;
/** @var SessionInterface */
protected $session;
/**
* DbLoader constructor.
*
* @param UrlGeneratorInterface $urlGenerator
* @param TokenStorageInterface $token
*/
public function __construct(TokenStorageInterface $token, UrlGeneratorInterface $urlGenerator, FlashBagInterface $flashBag, Security $security, SessionInterface $session)
{
$this->token = $token;
$this->urlGenerator = $urlGenerator;
$this->flashBag = $flashBag;
$this->security = $security;
$this->session = $session;
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$token = $this->token->getToken();
if (!empty($token) && $event->getRequest()->get('_route') != 'app_login')
{
/** @var User $user */
$user = $token->getUser();
if ($user instanceof User && $user->getToken()->isRefreshFailed())
{
/* Add prefix to make this messages translatable */
$errMsg = sprintf('login.%s', 'Invalid refresh token');
$this->flashBag->add('danger', $errMsg);
$this->security->getToken()->setAuthenticated(false);
/* No session, no flashbag. */
// $this->session->invalidate();
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('app_login')));
}
}
}
}