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

61 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Pterodactyl\Http\Middleware;
use Closure;
2017-04-01 00:48:35 +00:00
use Pterodactyl\Events\Auth\FailedCaptcha;
class VerifyReCaptcha
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
2017-04-01 01:12:49 +00:00
* @return \Illuminate\Http\RediectResponse
*/
public function handle($request, Closure $next)
{
2017-04-01 00:48:35 +00:00
if (! config('recaptcha.enabled')) {
return $next($request);
}
if ($request->has('g-recaptcha-response')) {
$client = new \GuzzleHttp\Client();
2017-04-01 01:12:49 +00:00
$res = $client->post(config('recaptcha.domain'), [
'form_params' => [
'secret' => config('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());
2017-04-01 01:12:49 +00:00
$verified = function ($result, $request) {
if (! config('recaptcha.verify_domain')) {
return false;
}
2017-04-01 01:12:49 +00:00
$url = parse_url($request->url());
2017-04-01 01:16:00 +00:00
if (! array_key_exists('host', $url)) {
return false;
2017-04-01 01:12:49 +00:00
}
2017-04-01 01:16:00 +00:00
return $result->hostname === $url['host'];;
2017-04-01 01:12:49 +00:00
};
2017-04-01 01:12:49 +00:00
if ($result->success && (! config('recaptcha.verify_domain') || $verified($result, $request))) {
return $next($request);
}
}
}
2017-04-01 00:48:35 +00:00
// Emit an event and return to the previous view with an error (only the captcha error will be shown!)
2017-04-01 01:12:49 +00:00
event(new FailedCaptcha($request->ip(), (! isset($result->hostname) ?: $result->hostname)));
2017-04-01 00:48:35 +00:00
return back()->withErrors(['g-recaptcha-response' => trans('strings.captcha_invalid')])->withInput();
}
}