Show a better error when JSON data cannot be parsed in the request

This commit is contained in:
Dane Everitt 2020-06-30 20:05:11 -07:00
parent 655a751ef3
commit fde8465f35
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53
2 changed files with 41 additions and 0 deletions

View File

@ -9,6 +9,7 @@ use Pterodactyl\Http\Middleware\TrimStrings;
use Pterodactyl\Http\Middleware\TrustProxies; use Pterodactyl\Http\Middleware\TrustProxies;
use Illuminate\Session\Middleware\StartSession; use Illuminate\Session\Middleware\StartSession;
use Pterodactyl\Http\Middleware\EncryptCookies; use Pterodactyl\Http\Middleware\EncryptCookies;
use Pterodactyl\Http\Middleware\Api\IsValidJson;
use Pterodactyl\Http\Middleware\VerifyCsrfToken; use Pterodactyl\Http\Middleware\VerifyCsrfToken;
use Pterodactyl\Http\Middleware\VerifyReCaptcha; use Pterodactyl\Http\Middleware\VerifyReCaptcha;
use Pterodactyl\Http\Middleware\AdminAuthenticate; use Pterodactyl\Http\Middleware\AdminAuthenticate;
@ -69,6 +70,7 @@ class Kernel extends HttpKernel
], ],
'api' => [ 'api' => [
'throttle:240,1', 'throttle:240,1',
IsValidJson::class,
ApiSubstituteBindings::class, ApiSubstituteBindings::class,
SetSessionDriver::class, SetSessionDriver::class,
'api..key:' . ApiKey::TYPE_APPLICATION, 'api..key:' . ApiKey::TYPE_APPLICATION,
@ -80,6 +82,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
SetSessionDriver::class, SetSessionDriver::class,
AuthenticateSession::class, AuthenticateSession::class,
IsValidJson::class,
SubstituteClientApiBindings::class, SubstituteClientApiBindings::class,
'api..key:' . ApiKey::TYPE_ACCOUNT, 'api..key:' . ApiKey::TYPE_ACCOUNT,
AuthenticateIPAccess::class, AuthenticateIPAccess::class,

View File

@ -0,0 +1,38 @@
<?php
namespace Pterodactyl\Http\Middleware\Api;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class IsValidJson
{
/**
* Throw an exception if the request should be valid JSON data but there is an error while
* parsing the data. This avoids confusing validation errors where every field is flagged and
* it is not immediately clear that there is an issue with the JSON being passed.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($request->isJson() && ! empty($request->getContent())) {
json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadRequestHttpException(
sprintf(
'The JSON data passed in the request appears to be malformed. err_code: %d err_message: "%s"',
json_last_error(),
json_last_error_msg()
)
);
}
}
return $next($request);
}
}