src/App/Security/Subscriber/LoginSubscriber.php line 32

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\Security\Subscriber;
  3. use App\Entity\LoginLog;
  4. use App\Entity\User;
  5. use App\Model\UserLoginInfoInterface;
  6. use App\RabbitMq\Writer\LoginLogWriter;
  7. use App\Security\Login\LastLogin;
  8. use App\Service\LocationProvider;
  9. use Sindrive\RabbitMqTaskBundle\Service\TaskHandler;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
  12. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  13. class LoginSubscriber implements EventSubscriberInterface
  14. {
  15.     private LastLogin $lastLogin;
  16.     private TaskHandler $taskHandler;
  17.     private LocationProvider $locationProvider;
  18.     public function __construct(LastLogin $lastLoginTaskHandler $taskHandlerLocationProvider $locationProvider)
  19.     {
  20.         $this->lastLogin $lastLogin;
  21.         $this->taskHandler $taskHandler;
  22.         $this->locationProvider $locationProvider;
  23.     }
  24.     public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
  25.     {
  26.         if (($user $event->getAuthenticationToken()->getUser()) instanceof UserLoginInfoInterface) {
  27.             $this->lastLogin->updateUser($user);
  28.         }
  29.         if (!($user instanceof User) || !($event->getAuthenticationToken() instanceof RememberMeToken)) {
  30.             return;
  31.         }
  32.         $request $event->getRequest();
  33.         $loginLog = new LoginLog();
  34.         $loginLog->setStatus('success-remembered');
  35.         $loginLog->setUserAgent($request->headers->get('user-agent'));
  36.         $loginLog->setIp($request->getClientIp());
  37.         $loginLog->setCountry($this->locationProvider->getCountry());
  38.         $loginLog->setReferrer($request->headers->get('referer'));
  39.         $loginLog->setUsername($user->getUserIdentifier());
  40.         $loginLog->setPassword(null);
  41.         // getId here is right choice, because this entity is not being persisted, but being serialized.
  42.         $loginLog->setUserId($user->getId());
  43.         $this->taskHandler->sendTask(LoginLogWriter::QUEUE_NAMEserialize($loginLog));
  44.     }
  45.     /**
  46.      * @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
  47.      */
  48.     public static function getSubscribedEvents(): array
  49.     {
  50.         return [
  51.             InteractiveLoginEvent::class => 'onSecurityInteractiveLogin',
  52.         ];
  53.     }
  54. }