Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(LaratrustMiddleware@unauthorized): Add JSON response handling for unauthorized access #691

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Nicodav28
Copy link

What’s New?

  • Added JSON response handling to unauthorized() method in LaratrustMiddleware.
  • If laratrust.middleware.handling is set to json, the middleware will return a structured JSON response instead of redirecting or aborting.

Why This Change?

  • Improves API support by providing standardized JSON responses.
  • Enhances maintainability and scalability by allowing response customization via config/laratrust.php.

Changes Made

  • Updated unauthorized() to support JSON response.
  • Introduced a new json handling option in config/laratrust.php, with:
    • Customizable HTTP status code (code).
    • Optional timestamp inclusion (include_timestamp).
    • Flexible response structure (structure).
  • Maintained full compatibility with existing abort and redirect handlers.

How to Test?

  1. Update config/laratrust.php:
     'middleware' => [
         /**
          * Define if the laratrust middleware are registered automatically in the service provider.
          */
         'register' => true,
    
         /**
          * Method to be called in the middleware return case.
          * Available: abort|redirect.
          */
         'handling' => 'json',
    
         /**
          * Handlers for the unauthorized method in the middlewares.
          * The name of the handler must be the same as the handling.
          */
         'handlers' => [
             /**
              * Aborts the execution with a 403 code and allows you to provide the response text.
              */
             'abort' => [
                 'code' => 403,
                 'message' => 'User does not have any of the necessary access rights.',
             ],
    
             /**
              * Redirects the user to the given url.
              * If you want to flash a key to the session,
              * you can do it by setting the key and the content of the message
              * If the message content is empty it won't be added to the redirection.
              */
             'redirect' => [
                 'url' => '/home',
                 'message' => [
                     'key' => 'error',
                     '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' => false,
                 'structure'         => [
                     'status'  => 'error',
                     'message' => 'User does not have the necessary access rights to perform this action.',
                 ],
             ],
         ],
     ],
  2. Run php artisan config:clear to apply the changes.
  3. Trigger an unauthorized request (e.g., accessing a protected route without permissions).
  4. You should receive a JSON response like:
    {
        "status": "error",
        "message": "User does not have the necessary access rights to perform this action.",
        "timestamp": "2024-07-01T12:34:56.789Z"
    }

Let me know if you need any adjustments

…format for unauthorized access

🔧 (laratrust.php): Update configuration to include new 'json' key with custom response structure
The changes were made to provide a more detailed and structured response when unauthorized access is attempted. This is particularly useful when dealing with API endpoints where a JSON response is more appropriate than a redirect or abort. The configuration file was updated to include a new 'json' key that defines the structure of the response, including a custom message and the option to include a timestamp. The middleware was updated to handle this new configuration and return the custom JSON response when necessary.
@Nicodav28 Nicodav28 changed the title feat(LaratrustMiddleware.php@unauthorized): Add JSON response handling for unauthorized access feat(LaratrustMiddleware@unauthorized): Add JSON response handling for unauthorized access Mar 4, 2025
… readability and consistency

The changes were made to improve the readability of the code and to ensure consistency across the codebase. The alignment of the array elements in 'laratrust.php' was adjusted to make the code cleaner and easier to read. In 'LaratrustMiddleware.php', the strict equality operator was replaced with a loose equality operator to allow for type coercion, which can prevent potential bugs in the future.
@Nicodav28
Copy link
Author

The continuous-integration/styleci/pr checks have failed, but I can't see the details of the error to determine what’s wrong, if anyone has access or knows how to fix this, I’d appreciate the help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant