lthn.io/app/Http/Middleware/ValidateJsonRequest.php

40 lines
1 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* Validates API request body JSON content type and size limit.
*
* Applied to POST/PUT/PATCH API routes to prevent abuse.
*/
class ValidateJsonRequest
{
private const MAX_BODY_SIZE = 65536; // 64KB
public function handle(Request $request, Closure $next): mixed
{
if (in_array($request->method(), ['POST', 'PUT', 'PATCH'])) {
$contentType = $request->header('Content-Type', '');
if (! str_contains($contentType, 'application/json')) {
return response()->json([
'error' => 'Content-Type must be application/json.',
], 415);
}
if (strlen($request->getContent()) > self::MAX_BODY_SIZE) {
return response()->json([
'error' => 'Request body too large. Maximum 64KB.',
], 413);
}
}
return $next($request);
}
}