2017-03-31 12:19:44 +02:00
|
|
|
<?php
|
|
|
|
|
|
2024-03-12 22:39:16 -04:00
|
|
|
namespace App\Http\Middleware;
|
2017-03-31 12:19:44 +02:00
|
|
|
|
2017-10-29 12:37:25 -05:00
|
|
|
use GuzzleHttp\Client;
|
|
|
|
|
use Illuminate\Http\Request;
|
2019-12-15 16:13:44 -08:00
|
|
|
use Illuminate\Http\Response;
|
2024-03-12 22:39:16 -04:00
|
|
|
use App\Events\Auth\FailedCaptcha;
|
2019-12-15 16:13:44 -08:00
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
2017-03-31 12:19:44 +02:00
|
|
|
|
|
|
|
|
class VerifyReCaptcha
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* Handle an incoming request.
|
|
|
|
|
*/
|
2023-02-23 12:30:16 -07:00
|
|
|
public function handle(Request $request, \Closure $next): mixed
|
2017-03-31 12:19:44 +02:00
|
|
|
{
|
2024-03-19 04:59:19 -04:00
|
|
|
if (!config('recaptcha.enabled')) {
|
2017-03-31 20:48:35 -04:00
|
|
|
return $next($request);
|
|
|
|
|
}
|
|
|
|
|
|
2017-12-17 13:07:38 -06:00
|
|
|
if ($request->filled('g-recaptcha-response')) {
|
2017-10-29 12:37:25 -05:00
|
|
|
$client = new Client();
|
2024-03-19 04:59:19 -04:00
|
|
|
$res = $client->post(config('recaptcha.domain'), [
|
2017-03-31 12:19:44 +02:00
|
|
|
'form_params' => [
|
2024-03-19 04:59:19 -04:00
|
|
|
'secret' => config('recaptcha.secret_key'),
|
2017-03-31 21:12:49 -04:00
|
|
|
'response' => $request->input('g-recaptcha-response'),
|
2017-03-31 12:19:44 +02:00
|
|
|
],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if ($res->getStatusCode() === 200) {
|
|
|
|
|
$result = json_decode($res->getBody());
|
|
|
|
|
|
2024-03-19 04:59:19 -04:00
|
|
|
if ($result->success && (!config('recaptcha.verify_domain') || $this->isResponseVerified($result, $request))) {
|
2017-03-31 12:19:44 +02:00
|
|
|
return $next($request);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-03-31 20:48:35 -04:00
|
|
|
|
2024-03-19 16:14:24 -04:00
|
|
|
event(new FailedCaptcha($request->ip(), $result->hostname ?? null));
|
2017-10-29 12:37:25 -05:00
|
|
|
|
2021-01-23 12:33:34 -08:00
|
|
|
throw new HttpException(Response::HTTP_BAD_REQUEST, 'Failed to validate reCAPTCHA data.');
|
2017-10-29 12:37:25 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Determine if the response from the recaptcha servers was valid.
|
|
|
|
|
*/
|
2023-02-23 12:30:16 -07:00
|
|
|
private function isResponseVerified(\stdClass $result, Request $request): bool
|
2017-10-29 12:37:25 -05:00
|
|
|
{
|
2024-03-19 04:59:19 -04:00
|
|
|
if (!config('recaptcha.verify_domain')) {
|
2017-10-29 12:37:25 -05:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$url = parse_url($request->url());
|
2017-03-31 20:48:35 -04:00
|
|
|
|
2017-10-29 12:37:25 -05:00
|
|
|
return $result->hostname === array_get($url, 'host');
|
2017-03-31 12:19:44 +02:00
|
|
|
}
|
|
|
|
|
}
|