<?php
namespace App\EventListener\JWT;
use App\Entity\User;
use App\Repository\UserTokenRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
class AuthenticationListener
{
/**
* @var UserTokenRepository
*/
private $userTokenRepo;
/**
* @param UserTokenRepository $userTokenRepo
*/
public function __construct(UserTokenRepository $userTokenRepo)
{
$this->userTokenRepo = $userTokenRepo;
}
/**
* @param AuthenticationSuccessEvent $event
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
{
/** @var User $user */
$user = $event->getUser();
$tokenString = $event->getData()["token"] ?? "";
$this->userTokenRepo->disableOldTokens($user);
$this->userTokenRepo->create($user, $tokenString);
}
/**
* @param AuthenticationFailureEvent $event
*/
public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event)
{
$event->setResponse(new JWTAuthenticationFailureResponse('bad_credentials'));
}
/**
* @param JWTInvalidEvent $event
*/
public function onJWTInvalid(JWTInvalidEvent $event)
{
$event->setResponse(new JsonResponse(['message' => "token.invalid"], 401));
}
/**
* @param JWTNotFoundEvent $event
*/
public function onJWTNotFound(JWTNotFoundEvent $event)
{
$event->setResponse(new JsonResponse(['message' => "token.not_found"], 401));
}
/**
* @param JWTExpiredEvent $event
*/
public function onJWTExpired(JWTExpiredEvent $event)
{
$event->setResponse(new JsonResponse(['message' => "token.expired"], 401));
}
}