<?php
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ReCaptchaValidationListener implements EventSubscriberInterface
{
/**
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
if ('login_check' !== $event->getRequest()->getPathInfo()) {
return;
}
$token = $event->getRequest()->request->get('g-recaptcha-response');
if($token){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
"secret" => "6LdbupIiAAAAAGST-LJkJyGyU5lXbow0r3si9i2W",
"response" => $token
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = json_decode(curl_exec($ch));
curl_close($ch);
if ($server_output->success) {
return;
}
}
$event->setResponse(new RedirectResponse('/login'));
// get recaptcha from request and validate it.if you want to prevent request to call next event, just set response for event. $event->setResponse($response)
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 9]
];
}
}