<?php
/*
* This file is part of the nellapp-core package.
*
* (c) Benjamin Georgeault
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nellapp\Bundle\SDKBundle\Auth\Security\OAuth;
use Nellapp\Bundle\SDKBundle\Auth\Controller\Security\LogoutAction;
use Nellapp\Bundle\SDKBundle\Auth\Entity\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
/**
* For now, User must be logged out if there token expired.
* TODO LATER Auto refresh token.
*
* @author Benjamin Georgeault
*/
class HandleExpireTokenSubscriber implements EventSubscriberInterface
{
public function __construct(
private Security $security,
private UrlGeneratorInterface $urlGenerator,
) {}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event)
{
if (HttpKernelInterface::MAIN_REQUEST !== $event->getRequestType()) {
return;
}
$user = $this->security->getUser();
if (!($user instanceof UserInterface) || (null === $token = $user->getToken()) || !$token->isExpired()) {
return;
}
$event->setResponse(new RedirectResponse($this->urlGenerator->generate(LogoutAction::ROUTE_NAME)));
}
}