Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Http/Middleware/VerifyReCaptcha.php
10279 views
1
<?php
2
3
namespace Pterodactyl\Http\Middleware;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\Response;
8
use Pterodactyl\Events\Auth\FailedCaptcha;
9
use Illuminate\Contracts\Config\Repository;
10
use Illuminate\Contracts\Events\Dispatcher;
11
use Symfony\Component\HttpKernel\Exception\HttpException;
12
13
class VerifyReCaptcha
14
{
15
/**
16
* VerifyReCaptcha constructor.
17
*/
18
public function __construct(private Dispatcher $dispatcher, private Repository $config)
19
{
20
}
21
22
/**
23
* Handle an incoming request.
24
*/
25
public function handle(Request $request, \Closure $next): mixed
26
{
27
if (!$this->config->get('recaptcha.enabled')) {
28
return $next($request);
29
}
30
31
if ($request->filled('g-recaptcha-response')) {
32
$client = new Client();
33
$res = $client->post($this->config->get('recaptcha.domain'), [
34
'form_params' => [
35
'secret' => $this->config->get('recaptcha.secret_key'),
36
'response' => $request->input('g-recaptcha-response'),
37
],
38
]);
39
40
if ($res->getStatusCode() === 200) {
41
$result = json_decode($res->getBody());
42
43
if ($result->success && (!$this->config->get('recaptcha.verify_domain') || $this->isResponseVerified($result, $request))) {
44
return $next($request);
45
}
46
}
47
}
48
49
$this->dispatcher->dispatch(
50
new FailedCaptcha(
51
$request->ip(),
52
!empty($result) ? ($result->hostname ?? null) : null
53
)
54
);
55
56
throw new HttpException(Response::HTTP_BAD_REQUEST, 'Failed to validate reCAPTCHA data.');
57
}
58
59
/**
60
* Determine if the response from the recaptcha servers was valid.
61
*/
62
private function isResponseVerified(\stdClass $result, Request $request): bool
63
{
64
if (!$this->config->get('recaptcha.verify_domain')) {
65
return false;
66
}
67
68
$url = parse_url($request->url());
69
70
return $result->hostname === array_get($url, 'host');
71
}
72
}
73
74