Skip to content

Commit fde8465

Browse files
committed
Show a better error when JSON data cannot be parsed in the request
1 parent 655a751 commit fde8465

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

app/Http/Kernel.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Pterodactyl\Http\Middleware\TrustProxies;
1010
use Illuminate\Session\Middleware\StartSession;
1111
use Pterodactyl\Http\Middleware\EncryptCookies;
12+
use Pterodactyl\Http\Middleware\Api\IsValidJson;
1213
use Pterodactyl\Http\Middleware\VerifyCsrfToken;
1314
use Pterodactyl\Http\Middleware\VerifyReCaptcha;
1415
use Pterodactyl\Http\Middleware\AdminAuthenticate;
@@ -69,6 +70,7 @@ class Kernel extends HttpKernel
6970
],
7071
'api' => [
7172
'throttle:240,1',
73+
IsValidJson::class,
7274
ApiSubstituteBindings::class,
7375
SetSessionDriver::class,
7476
'api..key:' . ApiKey::TYPE_APPLICATION,
@@ -80,6 +82,7 @@ class Kernel extends HttpKernel
8082
StartSession::class,
8183
SetSessionDriver::class,
8284
AuthenticateSession::class,
85+
IsValidJson::class,
8386
SubstituteClientApiBindings::class,
8487
'api..key:' . ApiKey::TYPE_ACCOUNT,
8588
AuthenticateIPAccess::class,
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Pterodactyl\Http\Middleware\Api;
4+
5+
use Closure;
6+
use Illuminate\Http\Request;
7+
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
8+
9+
class IsValidJson
10+
{
11+
/**
12+
* Throw an exception if the request should be valid JSON data but there is an error while
13+
* parsing the data. This avoids confusing validation errors where every field is flagged and
14+
* it is not immediately clear that there is an issue with the JSON being passed.
15+
*
16+
* @param \Illuminate\Http\Request $request
17+
* @param \Closure $next
18+
* @return mixed
19+
*/
20+
public function handle(Request $request, Closure $next)
21+
{
22+
if ($request->isJson() && ! empty($request->getContent())) {
23+
json_decode($request->getContent(), true);
24+
25+
if (json_last_error() !== JSON_ERROR_NONE) {
26+
throw new BadRequestHttpException(
27+
sprintf(
28+
'The JSON data passed in the request appears to be malformed. err_code: %d err_message: "%s"',
29+
json_last_error(),
30+
json_last_error_msg()
31+
)
32+
);
33+
}
34+
}
35+
36+
return $next($request);
37+
}
38+
}

0 commit comments

Comments
 (0)