src/Service/AuthenticationSuccessHandler.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Events;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse;
  6. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  12. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;
  13. class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
  14. {
  15.     private JWTTokenManagerInterface $jwtManager;
  16.     private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher;
  17.     public function __construct(
  18.         JWTTokenManagerInterface $jwtManager,
  19.         EventDispatcherInterface $dispatcher
  20.     ) {
  21.         $this->jwtManager $jwtManager;
  22.         $this->dispatcher $dispatcher;
  23.     }
  24.     /**
  25.      * {@inheritdoc}
  26.      */
  27.     public function onAuthenticationSuccess(Request $requestTokenInterface $token)
  28.     {
  29.         return $this->handleAuthenticationSuccess($token->getUser());
  30.     }
  31.     public function handleAuthenticationSuccess(UserInterface $user$jwt null)
  32.     {
  33.         if (null === $jwt) {
  34.             $jwt $this->jwtManager->create($user);
  35.         }
  36.         $response = new JWTAuthenticationSuccessResponse($jwt);
  37.         $event = new AuthenticationSuccessEvent(['token' => $jwt], $user$response);
  38.         if ($this->dispatcher instanceof ContractsEventDispatcherInterface) {
  39.             $this->dispatcher->dispatch($eventEvents::AUTHENTICATION_SUCCESS);
  40.         } else {
  41.             $this->dispatcher->dispatch(Events::AUTHENTICATION_SUCCESS$event);
  42.         }
  43.         $response->setData($event->getData());
  44.         return $response;
  45.     }
  46. }