src/EventListener/JWTCreatedListener.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Resident;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
  5. use Symfony\Component\Security\Core\Security;
  6. class JWTCreatedListener
  7. {
  8.     private Security $security;
  9.     /**
  10.      * @param Security $security
  11.      */
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     /**
  17.      * @param JWTCreatedEvent $event
  18.      *
  19.      * @return void
  20.      */
  21.     public function onJWTCreated(JWTCreatedEvent $event): void
  22.     {
  23.         $payload       $event->getData();
  24.         $buildingIds = [];
  25.         $user $this->security->getUser();
  26.         if ($user instanceof Resident) {
  27.             $flats $user->getFlats();
  28.             foreach ($flats as $flat) {
  29.                 $buildingId $flat->getBuilding()->getId();
  30.                 if (!in_array($buildingId$buildingIds)) {
  31.                     $buildingIds[] = $buildingId;
  32.                 }
  33.             }
  34.             $payload['buildingId'] = $buildingIds;
  35.             $event->setData($payload);
  36.         }
  37.         $header        $event->getHeader();
  38.         $header['cty'] = 'JWT';
  39.         $event->setHeader($header);
  40.     }
  41. }