Kyon147/laravel-shopify

Auth user returns null on Inertia

ignacio-dev opened this issue · 6 comments

For bug reporting only! If you're posting a feature request or discussion, please ignore.

Expected Behavior

Being able to call $request->user() from HandleInertiaRequests 's share() method and get the Shopify shop.

Current Behavior

Returns null.

Failure Information

I can only get the $request->user() from my controllers.

Steps to Reproduce

  1. Call $request->user() from HandleInertiaRequests.

Context

  • Package Version: ^21.1
  • Laravel Version: ^11.0
  • PHP Version: 8.3.6
  • Template Engine: React
  • Using a toolset (Docker, Laradock, Vagrant, etc.): Docker/Sail

Failure Logs

--

Inertia is a community included feature, so someone would need to have a look at this as I've not used Interia so would not be the best person to understand what is needed here.

I think the issue is that, if you have any middleware appended to the routes from the bootstrap/app.php file like this:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ## HERE ##
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Those middlewares are running before the Shopify middlewares, so they don't have access to Shopify's auth user.

I'll try appending the shopify middleware from there instead of the routes file, and see if I have any success.

The issue is that the verify.shopify middleware is applied after HandleInertiaRequests is processed, and that's causes user to not be logged in. To fix this issue, you need to apply verify.shopify before Inertia middleware.

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            'verify.shopify',
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Note: this will cause any routes in web to be authenticated. Most likely it's what you want, in other cases you might need to create a new routes file and exclude verify.shopify from the middleware lists.

Indeed, this solves the issue. Thank you!