src/Component/AuditLog/EventSubscriber/AuditLogSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Component\AuditLog\EventSubscriber;
  4. use App\Component\AuditLog\Action;
  5. use App\Component\AuditLog\Message\Command\AuditLogEntry;
  6. use App\Entity\User;
  7. use Scheb\TwoFactorBundle\Security\TwoFactor\Event\TwoFactorAuthenticationEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Messenger\MessageBusInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  12. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  13. class AuditLogSubscriber implements EventSubscriberInterface
  14. {
  15.     public function __construct(private readonly MessageBusInterface $messageBus)
  16.     {
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             SwitchUserEvent::class => 'onSecuritySwitchUser',
  22.             LoginSuccessEvent::class => 'onLoginSuccess',
  23.             'scheb_two_factor.authentication.complete' => 'onTwoFactorAuthenticationComplete',
  24.         ];
  25.     }
  26.     public function onTwoFactorAuthenticationComplete(TwoFactorAuthenticationEvent $event): void
  27.     {
  28.         $this->loginEntry($event->getToken());
  29.     }
  30.     public function onSecuritySwitchUser(SwitchUserEvent $event): void
  31.     {
  32.         $user $event->getToken()?->getUser();
  33.         /** @var int $userId */
  34.         $userId $user instanceof User $user->getId() : 0;
  35.         /** @var User $targetUser */
  36.         $targetUser $event->getTargetUser();
  37.         $targetUserId $targetUser->getId();
  38.         if ($userId !== $targetUserId) {
  39.             $this->messageBus->dispatch(new AuditLogEntry($userIdAction::USER_SWITCH->value, (string) $targetUserId));
  40.         }
  41.     }
  42.     public function onLoginSuccess(LoginSuccessEvent $event): void
  43.     {
  44.         $this->loginEntry($event->getAuthenticatedToken());
  45.     }
  46.     private function loginEntry(TokenInterface $token): void
  47.     {
  48.         $user $token->getUser();
  49.         /** @var int $userId */
  50.         $userId $user instanceof User $user->getId() : 0;
  51.         $this->messageBus->dispatch(new AuditLogEntry($userIdAction::USER_LOGIN->value));
  52.     }
  53. }