From 5e94726ec19c498a51270ed2034e5caedb868260 Mon Sep 17 00:00:00 2001 From: Brady Wetherington Date: Tue, 8 Feb 2022 12:05:05 -0800 Subject: [PATCH 1/2] Properly alert when invalid JSON is submitted to something that wants JSON --- app/Exceptions/Handler.php | 8 ++++++++ app/Http/Requests/Request.php | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 7fd552f57d..3b396ee7c7 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -8,6 +8,7 @@ use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use App\Helpers\Helper; use Illuminate\Validation\ValidationException; use Log; +use JsonException; class Handler extends ExceptionHandler @@ -26,6 +27,7 @@ class Handler extends ExceptionHandler \Illuminate\Validation\ValidationException::class, \Intervention\Image\Exception\NotSupportedException::class, \League\OAuth2\Server\Exception\OAuthServerException::class, + JsonException::class ]; /** @@ -60,6 +62,12 @@ class Handler extends ExceptionHandler return redirect()->back()->with('error', trans('general.token_expired')); } + // Invalid JSON exception + // TODO: don't understand why we have to do this when we have the invalidJson() method, below, but, well, whatever + if ($e instanceof JsonException) { + return response()->json(Helper::formatStandardApiResponse('error', null, 'invalid JSON'), 422); + } + // Handle Ajax requests that fail because the model doesn't exist if ($request->ajax() || $request->wantsJson()) { diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 35bfcdee93..95c70fa3f9 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -8,6 +8,14 @@ abstract class Request extends FormRequest { protected $rules = []; + public function json($key = null, $default = null) + { + if ($this->ajax() || $this->wantsJson()) { + json_decode($this->getContent(), false, 512, \JSON_THROW_ON_ERROR); // ignore output, just throw + } + return parent::json($key, $default); + } + public function rules() { return $this->rules; From 9a66f6a2541fa675e9a9505684cc7f2562cc4395 Mon Sep 17 00:00:00 2001 From: Brady Wetherington Date: Tue, 8 Feb 2022 12:09:40 -0800 Subject: [PATCH 2/2] Remove extraneous backslash --- app/Http/Requests/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 95c70fa3f9..54a7b81adf 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -11,7 +11,7 @@ abstract class Request extends FormRequest public function json($key = null, $default = null) { if ($this->ajax() || $this->wantsJson()) { - json_decode($this->getContent(), false, 512, \JSON_THROW_ON_ERROR); // ignore output, just throw + json_decode($this->getContent(), false, 512, JSON_THROW_ON_ERROR); // ignore output, just throw } return parent::json($key, $default); }