<?php
namespace App\EventSubscriber;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Entity\User;
use Symfony\Component\HttpFoundation\RequestStack;
use App\Services\GoogleRecaptcha;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
class LoginEventSubscriber implements EventSubscriberInterface
{
private $request;
private $googleRecaptcha;
public function __construct(RequestStack $requestStack, GoogleRecaptcha $googleRecaptcha)
{
$this->request = $requestStack->getCurrentRequest();
$this->googleRecaptcha = $googleRecaptcha;
}
public static function getSubscribedEvents()
{
return [
InteractiveLoginEvent::class => 'onSecurityInteractiveLogin',
];
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
if($this->request->isMethod('POST'))
{
$recaptchaResponse = $this->request->request->get('g-recaptcha-response');
$verified = $this->googleRecaptcha->siteVerify($recaptchaResponse);
if(!$verified)
{
throw new AuthenticationException('Invalid reCAPTCHA. Please try again.');
}
}
$user = $event->getAuthenticationToken()->getUser();
if($user instanceof User)
{
$session = $this->request ? $this->request->getSession() : false;
if(!$session)
{
return;
}
$sessionId = $session->getId();
$lat = $this->request->get('latitude');
$long = $this->request->get('longitude');
if($lat && $long)
{
$session->set('latitude', $lat);
$session->set('longitude', $long);
}
}
}
}