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

91 lines
2.5 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Pterodactyl\Http\Middleware;
use Closure;
2017-11-04 22:16:44 +00:00
use stdClass;
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
/**
* @var \Illuminate\Contracts\Config\Repository
*/
private $config;
/**
* @var \Illuminate\Contracts\Events\Dispatcher
*/
private $dispatcher;
2017-10-29 17:37:25 +00:00
/**
* VerifyReCaptcha constructor.
*/
public function __construct(Dispatcher $dispatcher, Repository $config)
2017-10-29 17:37:25 +00:00
{
$this->config = $config;
$this->dispatcher = $dispatcher;
2017-10-29 17:37:25 +00:00
}
/**
* Handle an incoming request.
*
2017-08-22 03:10:48 +00:00
* @param \Illuminate\Http\Request $request
2021-01-23 20:33:34 +00:00
*
2017-10-29 17:37:25 +00:00
* @return \Illuminate\Http\RedirectResponse|mixed
*/
public function handle($request, Closure $next)
{
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.
*/
2017-11-04 22:16:44 +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');
}
}