src/EventListener/JWT/AuthenticationListener.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\EventListener\JWT;
  3. use App\Entity\User;
  4. use App\Repository\UserTokenRepository;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTExpiredEvent;
  7. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTInvalidEvent;
  8. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTNotFoundEvent;
  9. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
  10. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
  11. use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
  12. class AuthenticationListener
  13. {
  14.     /**
  15.      * @var UserTokenRepository
  16.      */
  17.     private $userTokenRepo;
  18.     /**
  19.      * @param UserTokenRepository $userTokenRepo
  20.      */
  21.     public function __construct(UserTokenRepository $userTokenRepo)
  22.     {
  23.         $this->userTokenRepo $userTokenRepo;
  24.     }
  25.     /**
  26.      * @param AuthenticationSuccessEvent $event
  27.      * @throws \Doctrine\ORM\ORMException
  28.      * @throws \Doctrine\ORM\OptimisticLockException
  29.      */
  30.     public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
  31.     {
  32.         /** @var User $user */
  33.         $user $event->getUser();
  34.         $tokenString $event->getData()["token"] ?? "";
  35.         $this->userTokenRepo->disableOldTokens($user);
  36.         $this->userTokenRepo->create($user$tokenString);
  37.     }
  38.     /**
  39.      * @param AuthenticationFailureEvent $event
  40.      */
  41.     public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event)
  42.     {
  43.         $event->setResponse(new JWTAuthenticationFailureResponse('bad_credentials'));
  44.     }
  45.     /**
  46.      * @param JWTInvalidEvent $event
  47.      */
  48.     public function onJWTInvalid(JWTInvalidEvent $event)
  49.     {
  50.         $event->setResponse(new JsonResponse(['message' => "token.invalid"], 401));
  51.     }
  52.     /**
  53.      * @param JWTNotFoundEvent $event
  54.      */
  55.     public function onJWTNotFound(JWTNotFoundEvent $event)
  56.     {
  57.         $event->setResponse(new JsonResponse(['message' => "token.not_found"], 401));
  58.     }
  59.     /**
  60.      * @param JWTExpiredEvent $event
  61.      */
  62.     public function onJWTExpired(JWTExpiredEvent $event)
  63.     {
  64.         $event->setResponse(new JsonResponse(['message' => "token.expired"], 401));
  65.     }
  66. }