src/EventListener/JWTCreatedListener.php line 21

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\EventListener;
  3. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
  6. use MedBrief\MSR\Service\Security\SecurityTimeDelayHelperService;
  7. class JWTCreatedListener
  8. {
  9. public function __construct(private readonly SecurityTimeDelayHelperService $securityTimeDelayHelper)
  10. {
  11. }
  12. /**
  13. * Handles successful JWT creation.
  14. *
  15. * @param JWTCreatedEvent $event
  16. */
  17. public function onJWTAuthenticationSuccess(JWTCreatedEvent $event): void
  18. {
  19. $payload = $event->getData();
  20. $userId = $event->getUser()->getId();
  21. $payload['uid'] = $userId;
  22. $event->setData($payload);
  23. }
  24. /**
  25. * Handles authentication failure events.
  26. *
  27. * @param AuthenticationFailureEvent $event
  28. */
  29. public function onJWTAuthenticationFailed(AuthenticationFailureEvent $event): void
  30. {
  31. // Start time of the request processing
  32. $startTime = microtime(true);
  33. // This is for email enumeration attacks
  34. // Use the SecurityHelper to determine if the user exists
  35. $userExists = $this->securityTimeDelayHelper->determineIfUserExists();
  36. if (!$userExists) {
  37. // Add an extra delay for wrong email to match password timing
  38. usleep(600 * 1000);
  39. }
  40. // Use the SecurityHelper to add a random delay
  41. $this->securityTimeDelayHelper->addRandomDelay($startTime);
  42. $responseMessage = 'Bad credentials, please verify that your username/password are correctly set.';
  43. $response = new JWTAuthenticationFailureResponse($responseMessage);
  44. $event->setResponse($response);
  45. }
  46. }