src/Listeners/AuthenticationSuccessListener.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\Listeners;
  3. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse;
  5. use Symfony\Component\HttpFoundation\Cookie;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. class AuthenticationSuccessListener
  9. {
  10.     private $jwtTokenTTL;
  11.     private $secureCookie false;
  12.     public function __construct($ttl)
  13.     {
  14.         $this->jwtTokenTTL $ttl;
  15.     }
  16.     /**
  17.      * This function is responsible for the authentication part
  18.      *
  19.      * @param AuthenticationSuccessEvent $event
  20.      * @return JWTAuthenticationSuccessResponse
  21.      */
  22.     public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
  23.     {
  24.         /** @var JWTAuthenticationSuccessResponse $response */
  25.         $response $event->getResponse();
  26.         $data $event->getData();
  27.         $tokenJWT $data['token'];
  28.         unset($data['token']);
  29.         unset($data['refresh_token']);
  30.         $user $event->getUser();
  31.         $data['user'] = [
  32.             'id' => $user->getId(),
  33.             'username' => $user->getUsername(),
  34.             'displayname' => $user->getDisplayName(),
  35.             'firstname' => $user->getFirstName(),
  36.             'prefix' => $user->getPrefix(),
  37.             'lastname' => $user->getLastName(),
  38.             'email' => $user->getEmail(),
  39.             'roles' => $user->getRoles(),
  40.             'isAdmin' => $user->getIsAdmin(),
  41.             'isEditor' => $user->getIsEditor(),
  42.             'isViewer' => $user->getIsViewer()
  43.         ];
  44.         $event->setData($data);
  45.         $response->headers->setCookie(new Cookie('JWT'$tokenJWT, (
  46.         new \DateTime())
  47.             ->add(new \DateInterval('PT' $this->jwtTokenTTL 'S')), '/'null$this->secureCookie));
  48.         return $response;
  49.     }
  50. }