Fix FLEXIAPI-211 Add a JSON validation middleware + test

This commit is contained in:
Timothée Jaussoin 2024-09-11 15:52:35 +02:00
parent 1ff618d20a
commit 23e61fdc38
4 changed files with 48 additions and 0 deletions

View file

@ -6,6 +6,7 @@ v1.6
- Fix FLEXIAPI-196 Add a phone validation system by country code with configuration panels and related tests and documentation
- Fix FLEXIAPI-203 Implement domain based Linphone configuration, add documentation, complete API endpoints, complete provisioning XML
- Fix FLEXIAPI-208 Add SMS templates documentation
- Fix FLEXIAPI-211 Add a JSON validation middleware + test
v1.5
---

View file

@ -57,6 +57,7 @@ class Kernel extends HttpKernel
'api' => [
'throttle:600,1', // move to 600 instead of 60
'bindings',
'validate_json',
'localization',
],
];
@ -76,6 +77,7 @@ class Kernel extends HttpKernel
'auth.digest_or_key' => \App\Http\Middleware\AuthenticateDigestOrKey::class,
'auth.jwt' => \App\Http\Middleware\AuthenticateJWT::class,
'auth.check_blocked' => \App\Http\Middleware\CheckBlocked::class,
'validate_json' => \App\Http\Middleware\ValidateJSON::class,
'web_panel_enabled' => \App\Http\Middleware\IsWebPanelEnabled::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ValidateJSON
{
public static $message = 'Invalid JSON';
public function handle(Request $request, Closure $next)
{
if ($request->expectsJson()) {
json_decode($request->getContent());
if (json_last_error() !== JSON_ERROR_NONE) {
abort(400, self::$message . ': ' . json_last_error_msg());
}
}
return $next($request);
}
}

View file

@ -22,6 +22,7 @@ namespace Tests\Feature;
use App\Account;
use App\AccountCreationRequestToken;
use App\AccountCreationToken;
use App\Http\Middleware\ValidateJSON;
use Tests\TestCase;
use Carbon\Carbon;
@ -39,6 +40,27 @@ class ApiAccountCreationTokenTest extends TestCase
protected $pnParam = 'param';
protected $pnPrid = 'id';
public function testInvalidJSON()
{
$this->call(
$this->method,
$this->tokenRoute,
[],
[],
[],
$this->transformHeadersToServerVars(
[
'content-type' => 'application/json',
'accept' => 'application/json',
]
),
'{"first_name": "John", "last_name": "Smith", "is_alive": true, "age": 27,'
)->assertStatus(400)
->assertJsonPath(
'message',
fn ($error) => substr($error, 0, strlen(ValidateJSON::$message)) == ValidateJSON::$message
);
}
public function testCorrectParameters()
{
$this->assertSame(AccountCreationToken::count(), 0);