Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions config/laratrust.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
],
],
],
],

Expand Down
10 changes: 10 additions & 0 deletions src/Middleware/LaratrustMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down