src/EventSubscriber/LoginEventSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use App\Entity\User;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use App\Services\GoogleRecaptcha;
  8. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  9. class LoginEventSubscriber implements EventSubscriberInterface
  10. {
  11.     private $request;
  12.     private $googleRecaptcha;
  13.     public function __construct(RequestStack $requestStackGoogleRecaptcha $googleRecaptcha)
  14.     {
  15.         $this->request $requestStack->getCurrentRequest();
  16.         $this->googleRecaptcha $googleRecaptcha;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             InteractiveLoginEvent::class => 'onSecurityInteractiveLogin',
  22.         ];
  23.     }
  24.     public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
  25.     {
  26.         if($this->request->isMethod('POST'))
  27.         {
  28.             $recaptchaResponse $this->request->request->get('g-recaptcha-response');
  29.             $verified $this->googleRecaptcha->siteVerify($recaptchaResponse);
  30.             if(!$verified)
  31.             {
  32.                 throw new AuthenticationException('Invalid reCAPTCHA. Please try again.');
  33.             }
  34.         }
  35.         $user $event->getAuthenticationToken()->getUser();
  36.         if($user instanceof User)
  37.         {
  38.             $session $this->request $this->request->getSession() : false;
  39.             if(!$session)
  40.             {
  41.                 return;
  42.             }
  43.             $sessionId $session->getId();
  44.             $lat $this->request->get('latitude');
  45.             $long $this->request->get('longitude');
  46.             if($lat && $long)
  47.             {
  48.                 $session->set('latitude'$lat);
  49.                 $session->set('longitude'$long);
  50.             }
  51.         }
  52.     }
  53. }