misc_pterodactyl-panel/app/Http/Middleware/VerifyReCaptcha.php

73 lines
2.1 KiB
PHP
Raw Normal View History

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