diff --git a/config/laratrust.php b/config/laratrust.php index 552a76ae..a1e04605 100644 --- a/config/laratrust.php +++ b/config/laratrust.php @@ -226,6 +226,23 @@ 'content' => '', ], ], + + /** + * Defines a custom JSON response format for unauthorized access. + * This can be used when a JSON response is preferred over a redirect or abort. + * + * - 'code': The HTTP status code to return (default: 403). + * - 'include_timestamp': Whether to include a timestamp in the response (true/false). + * - 'structure': Defines the JSON response format. + */ + 'json' => [ + 'code' => 403, + 'include_timestamp' => true, + 'structure' => [ + 'status' => 'error', + 'message' => 'User does not have the necessary access rights to perform this action.', + ], + ], ], ], diff --git a/src/Middleware/LaratrustMiddleware.php b/src/Middleware/LaratrustMiddleware.php index 3354b5cf..fdb59a60 100644 --- a/src/Middleware/LaratrustMiddleware.php +++ b/src/Middleware/LaratrustMiddleware.php @@ -49,6 +49,16 @@ protected function unauthorized(): mixed return App::abort($handler['code'], $handler['message'] ?? $defaultMessage); } + if ($handling == 'json') { + $responseData = $handler['structure'] ?? []; + + if (! empty($handler['include_timestamp']) && boolval($handler['include_timestamp'])) { + $responseData['timestamp'] = now()->toISOString(); + } + + return response()->json($responseData, $handler['code'] ?? 403); + } + $redirect = Redirect::to($handler['url']); if (! empty($handler['message']['content'])) { $redirect->with($handler['message']['key'], $handler['message']['content']);