opcodesio / log-viewer

Fast and beautiful Log Viewer for Laravel
https://log-viewer.opcodes.io
MIT License
3.38k stars 237 forks source link

Laravel 11: Authorizing Users on page load returns Null user and Unauthorized #362

Open webdevnerdstuff opened 2 months ago

webdevnerdstuff commented 2 months ago

Issue:

On page load the auth user is null and causes the auth callback to be false.

Specs:

PHP: v8.3.3 Composer:

"require": {
    "php": "^8.2",
    "inertiajs/inertia-laravel": "^1.0",
    "laravel/framework": "^11.0",
    "laravel/jetstream": "^5.0",
    "laravel/sanctum": "^4.0",
    "laravel/tinker": "^2.9",
    "opcodesio/log-viewer": "^3.0",
    "tightenco/ziggy": "^2.0"
},
"require-dev": {
    "fakerphp/faker": "^1.23",
    "laravel/pint": "^1.13",
    "laravel/sail": "^1.26",
    "laravel/telescope": "^5.0",
    "mockery/mockery": "^1.6",
    "nunomaduro/collision": "^8.0",
    "phpunit/phpunit": "^11.0",
    "spatie/laravel-ignition": "^2.4",
    "barryvdh/laravel-debugbar": "^3.13",
    "itsgoingd/clockwork": "^5.2"
},

Problem Solving:

In Laravel 11 the providers has moved and I'm not sure if it's causing this to behave this way. Inside my AppServiceProvider I added something like the following:

LogViewer::auth(function ($request)
{
    $roles = config('log-viewer.roles');
    $hasAccess = (new RolePermissionHelper)->userHasRole($request->user(), $roles);

    return $hasAccess;
});

If I dump the $request->user() on the page load it is Null, but if I dd the user, it shows the user with all of it's data. Also if I dump($hasAccess) the result is false, and if I dd($hasAccess) the result is true, but still comes back Unauthorized. If I return true; it does work (expected since it's straight logic).

I thought that maybe the api or web middleware was blocking it somehow, so I added the following inside of bootstrap/app.php which is new in Laravel 11 to append/prepend (I tried both append/prepend) to the middleware:

$middleware->web(append: [
    \App\Http\Middleware\HandleInertiaRequests::class,
    \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
    \Opcodes\LogViewer\Http\Middleware\AuthorizeLogViewer::class,
]);

$middleware->api(append: [
    \Opcodes\LogViewer\Http\Middleware\AuthorizeLogViewer::class,
]);

This has the same result of Unauthorized. I also tried adding it to every other Provider I have to see if it would make a difference (it didn't).

Additional Info:

This problem did not occur for me in Laravel ^10. Unfortunately this is a private repo/company site so I can't share the full code. I also looked at this Issue 264 since it seemed similar, but it didn't quite apply in this situation.

I'm running out of ideas of things to try, so any help would be appreciated. Thank you!

arukompas commented 2 months ago

hey @webdevnerdstuff

can you share your config/log-viewer.php configuration? Does the middleware property include the 'web' middleware? Otherwise the authenticated user will not be resolved for Log Viewer routes.

webdevnerdstuff commented 2 months ago
<?php

return [
    'enabled' => env('LOG_VIEWER_ENABLED', true),
    'api_only' => env('LOG_VIEWER_API_ONLY', false),
    'require_auth_in_production' => true,
    'route_domain' => null,
    'route_path' => 'admin/logs',
    'back_to_system_url' => config('app.url', null),
    'back_to_system_label' => null, // Displayed by default: "Back to {{ app.name }}"
    'timezone' => null,

    'middleware' => [
        'web',
        \Opcodes\LogViewer\Http\Middleware\AuthorizeLogViewer::class,
    ],

    'roles' => env('LOG_VIEWER_ROLES') ? explode(',', env('LOG_VIEWER_ROLES')) : null,
    'api_middleware' => [
        \Opcodes\LogViewer\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        \Opcodes\LogViewer\Http\Middleware\AuthorizeLogViewer::class,
    ],
    'api_stateful_domains' => env('LOG_VIEWER_API_STATEFUL_DOMAINS') ? explode(',', env('LOG_VIEWER_API_STATEFUL_DOMAINS')) : null,
    'hosts' => [
        'local' => [
            'name' => ucfirst(env('APP_ENV', 'local')),
        ],
    ],
    'include_files' => [
        '*.log',
        '**/*.log',

        // You can include paths to other log types as well, such as apache, nginx, and more.
        '/var/log/httpd/*',
        '/var/log/nginx/*',

        // MacOS Apple Silicon logs
        '/opt/homebrew/var/log/nginx/*',
        '/opt/homebrew/var/log/httpd/*',
        '/opt/homebrew/var/log/php-fpm.log',
        '/opt/homebrew/var/log/postgres*log',
        '/opt/homebrew/var/log/redis*log',
        '/opt/homebrew/var/log/supervisor*log',

        // '/absolute/paths/supported',
        '/var/log/pbunny/*',
    ],
    'exclude_files' => [
        // 'my_secret.log'
    ],
    'hide_unknown_files' => true,
    'shorter_stack_trace_excludes' => [
        '/vendor/symfony/',
        '/vendor/laravel/framework/',
        '/vendor/barryvdh/laravel-debugbar/',
    ],
    'cache_driver' => env('LOG_VIEWER_CACHE_DRIVER', null),
    'lazy_scan_chunk_size_in_mb' => 200,
    'strip_extracted_context' => true,
];
stf-alexander commented 2 months ago

Having the same error after upgrading to Laravel 11.

stf-alexander commented 2 months ago

Sorry, in my case the Gate definition was missing in a Service Provider after the Laravel 11 update.

AlexandreCConcept commented 2 months ago

Hey 👋 I'm experiencing the same problem after upgrading to Laravel v11.x Before, everything was fine. So, what I do :

bootstrap/app.php :

return Application::configure(basePath: dirname(__DIR__))
                  ->registered(function (Application $app) {
                      $app->usePublicPath(path: base_path('/../public_html'));
                  })
                  ->withRouting(
                      web: __DIR__.'/../routes/web.php',
                      commands: __DIR__.'/../routes/console.php',
                      health: '/up',
                  )
                  ->withMiddleware(function (Middleware $middleware) {
                      $middleware->alias([
                          'role'                 => RoleMiddleware::class,
                          'permission'           => PermissionMiddleware::class,
                          'role_or_permission'   => RoleOrPermissionMiddleware::class,
                      ]);
                      $middleware->web(append: [
                         AuthorizeLogViewer::class,
                      ]);
                  })
                  ->withExceptions(function (Exceptions $exceptions) {
                      //
                  })->create();

Providers/AppServiceProvider.php :

public function boot(): void
    {
        LogViewer::auth(function ($request) {
            return $request->user()
                   && $request->user()->hasRole('super_admin');
        });
    }

If I make a dd($request->user() && $request->user()->hasRole('super_admin')); it returns true

log-viewer.php

I've also add this in the config file :

'middleware' => [
        'web', ViewLogs::class,
        AuthorizeLogViewer::class,
    ],

Did I miss something? I've a 401 😇 Thanks you

stf-alexander commented 2 months ago

@AlexandreCConcept try to set LOG_VIEWER_API_STATEFUL_DOMAINS in your .env file.

AlexandreCConcept commented 2 months ago

It's good, thanks! 😃