src/Event/JWTDecodedEventListener.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\Event;
  3. use App\Entity\Shop;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
  7. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent;
  8. /**
  9.  * @see https://gist.github.com/benjaminrau/865f94d142605eb72a23a34ccdd0617a
  10.  */
  11. class JWTDecodedEventListener
  12. {
  13.     /**
  14.      * @var EntityManagerInterface
  15.      */
  16.     private $entityManager;
  17.     /**
  18.      * @param EntityManagerInterface $entityManager
  19.      */
  20.     public function __construct(EntityManagerInterface $entityManager)
  21.     {
  22.         $this->entityManager $entityManager;
  23.     }
  24.     /**
  25.      * @param JWTDecodedEvent $event
  26.      *
  27.      * @throws \Exception
  28.      *
  29.      * @return void
  30.      */
  31.     public function onLexikJwtAuthenticationOnJwtDecoded(JWTDecodedEvent $event)
  32.     {
  33.         $payload $event->getPayload();
  34.         /**
  35.          * As a mechanism to invalidate issued tokes we force token issue date to be higher than a date stored on User::tokenValidAfter
  36.          * By updating the User::tokenValidAfter to current date all previously issued tokens become invalid
  37.          *
  38.          * Its intended we dont mark as invalid if user isnt found on persistence level because we rely on core JWT
  39.          * implementation to handle this case. We want to handle only the validation of tokenValidAfter here.
  40.          *
  41.          * @var $user User
  42.          */
  43.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  44.             'tel' => $payload['username'],
  45.         ]);
  46.         if ($user) {
  47.             if (
  48.                 $user->getTokenValidAfter() instanceof \DateTime &&
  49.                 $payload['iat'] < $user->getTokenValidAfter()->getTimestamp()
  50.             ) {
  51.                 $event->markAsInvalid();
  52.             }
  53.         } else {
  54.             $shop $this->entityManager->getRepository(Shop::class)->findOneBy([
  55.                 'email' => $payload['username'],
  56.             ]);
  57.             if ($shop) {
  58.                 if (
  59.                     $shop->getTokenValidAfter() instanceof \DateTime &&
  60.                     $payload['iat'] < $shop->getTokenValidAfter()->getTimestamp()
  61.                 ) {
  62.                     $event->markAsInvalid();
  63.                 }
  64.             }
  65.         }
  66.     }
  67. }