src/EventSubscriber/LoginSubscriber.php line 35

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Event\BadPasswordLoginEvent;
  5. use App\Repository\UserRepository;
  6. use App\Service\LoginAttemptService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  10. class LoginSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(private LoginAttemptService $service, private UserRepository $repository){}
  13.     /**
  14.      * @return array<string, string>
  15.      */
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             BadPasswordLoginEvent::class => 'onAuthenticationFailure',
  20.             InteractiveLoginEvent::class => 'onLogin',
  21.         ];
  22.     }
  23.     public function onAuthenticationFailure(BadPasswordLoginEvent $event): void
  24.     {
  25.         $this->service->addAttempt($event->getUser());
  26.     }
  27.     public function onLogin(InteractiveLoginEvent $event): void
  28.     {
  29.         $user $event->getAuthenticationToken()->getUser();
  30.         $event->getRequest()->getClientIp();
  31.         if ($user instanceof User) {
  32.             $ip $event->getRequest()->getClientIp();
  33.             if ($ip !== $user->getLastLoginIp()) $user->setLastLoginIp($ip);
  34.             $user->setLastLoginAt(new \DateTimeImmutable());
  35.             $this->repository->save($usertrue);
  36.         }
  37.     }
  38. }