<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
class JWTCreatedListener
{
public function __construct(
private RequestStack $requestStack,
private EntityManagerInterface $entityManager,
private ContainerInterface $container
) { }
public function onAuthenticationSuccessEvent(AuthenticationSuccessEvent $event)
{
}
/**
* @param JWTCreatedEvent $event
*
* @return void
*/
public function onJWTCreated(JWTCreatedEvent $event)
{
$payload = $event->getData();
if ($user = $event->getUser()) {
$payload['id'] = $user->getId();
$payload['guest'] = $user->getGuest();
$payload['uuid'] = $user->getUuid();
} else {
$payload['guest'] = true;
$payload['uuid'] = $user->getUuid();
}
$this->customExp($payload);
$event->setData($payload);
}
private function customExp(&$payload)
{
$request = new Request;
if (!$request->getContent()) {
return ;
}
if (!$exp = $request->toArray()['exp'] ?? null) {
return ;
}
$token_ttl = (int)$this->container->getParameter('lexik_jwt_authentication.token_ttl');
$expiration = new \DateTime();
$min = max(0, min($exp, $token_ttl));
$expiration->modify($min . ' min');
$payload['exp'] = $expiration->getTimestamp();
}
/**
* @param JWTExpiredEvent $event
*
* @return void
*/
public function onJWTExpired(JWTExpiredEvent $event)
{
$response = new JWTAuthenticationFailureResponse('Your token is invalid, please login again to get a new one', 403);
$event->setResponse($response);
}
/**
* @param JWTInvalidEvent $event
*
* @return void
*/
public function onJWTInvalid(JWTInvalidEvent $event)
{
$response = new JWTAuthenticationFailureResponse('Your token is invalid, please login again to get a new one', 403);
$event->setResponse($response);
}
/**
* @param AuthenticationFailureEvent $event
*
* @return void
*/
public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event)
{
$response = new JWTAuthenticationFailureResponse('Bad credentials, please verify that your login/password are correctly set', 401);
$event->setResponse($response);
}
}