src/EventSubscriber/LogoutSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\EventSubscriber;
  3. use MedBrief\MSR\Entity\AuditRecord\User as UserAuditRecord;
  4. use MedBrief\MSR\Event\AuditRecordEvent;
  5. use MedBrief\MSR\Factory\AuditRecordEventFactory;
  6. use MedBrief\MSR\Factory\AuditRecordFactory;
  7. use Override;
  8. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Http\Event\LogoutEvent;
  13. class LogoutSubscriber implements EventSubscriberInterface
  14. {
  15. public function __construct(private readonly SessionInterface $session, private readonly EventDispatcherInterface $eventDispatcher)
  16. {
  17. }
  18. /**
  19. * @inheritDoc
  20. */
  21. #[Override]
  22. public static function getSubscribedEvents()
  23. {
  24. return [
  25. LogoutEvent::class => 'onLogout',
  26. ];
  27. }
  28. /**
  29. * Invalidates the current session, but retains any flashes to display
  30. *
  31. * @param LogoutEvent $event
  32. */
  33. public function onLogout(LogoutEvent $event): void
  34. {
  35. $flashes = $this->session->getFlashBag()->all();
  36. // This will effectively log out the user by clearing all session data
  37. // associated with the user's session.
  38. $this->session->invalidate();
  39. // Re-add the flashes back to the new session
  40. $this->session->getFlashBag()->setAll($flashes);
  41. $this->logLogoutEvent($event);
  42. }
  43. /**
  44. * Logs an audit record of the logout event.
  45. *
  46. * @param LogoutEvent $event
  47. */
  48. private function logLogoutEvent(LogoutEvent $event): void
  49. {
  50. $token = $event->getToken();
  51. // Check if there is a token, this will prevent an error being thrown when $token->getUser() runs
  52. if (!$token instanceof TokenInterface) {
  53. return;
  54. }
  55. $user = $token->getUser();
  56. $auditRecord = AuditRecordFactory::create(
  57. UserAuditRecord::class,
  58. $user,
  59. null,
  60. UserAuditRecord::VERB_LOGOUT
  61. );
  62. $this->eventDispatcher->dispatch(
  63. AuditRecordEventFactory::create($auditRecord),
  64. AuditRecordEvent::AUDIT
  65. );
  66. }
  67. }