medusajs / medusa

Building blocks for digital commerce
https://medusajs.com
MIT License
24.45k stars 2.4k forks source link

Authentication Middleware does not work via Admin Dash #8046

Open TimCrooker opened 1 month ago

TimCrooker commented 1 month ago

Bug report

Describe the bug

I created the below middleware based on the guide in the documentation with the goal of accessing the user details inside services. The authenticate() middware consumed from the medusa package works perfectly when using the API but when performing the same actions via the Admin Dash they are blocked with a 401 error. This is the same account with the same credentials.

middleware code:

const registerLoggedInUser = async (
    req: MedusaRequest,
    res: MedusaResponse,
    next: MedusaNextFunction
) => {
    let loggedInUser: User | null = null

    console.log('registerLoggedInUser', req.user)
    if (req.user && req.user.userId) {
        console.log('registerLoggedInUser', req.user.userId)
        const userService = req.scope.resolve('userService') as UserService
        loggedInUser = await userService.retrieve(req.user.userId)

        console.log('registerLoggedInUser', loggedInUser)
    }

    req.scope.register({
        loggedInUser: {
            resolve: () => loggedInUser,
        },
    })

    next()
}

middleware config:

export const config: MiddlewaresConfig = {
    routes: [
        {
            matcher: /^\/admin\/(?!auth\/).*$/,
            middlewares: [
                authenticate(),
                 registerLoggedInUser],
        },
    ],
}

System information

Medusa version (including plugins):

Screenshot 2024-07-09 at 11 42 09 AM

Node.js version: 18.19.0 Database: Postgres Operating system: MacOs Browser (if relevant): Chrome

Steps to reproduce the behavior

add product via api after authentication it works.

add product via admin after authentication it is rejected with a 401 error

Expected behavior

Expected the auth middleware to allow the call

SanjanaSogimatt commented 1 month ago

Hey can I work on this issue?

adrien2p commented 1 month ago

@TimCrooker there is no user on the req, have you looked at the auth middleware by any change? could you log auth_context from req please

TimCrooker commented 1 month ago

@adrien2p

There is not a req.user by default yes but that is what the authenticate middleware does is attaches the user onto the request object. I tested this and it works via postman.

Here are some logs from the middleware that runs AFTER authenticate for product creation

auth_context undefined req.user { userId: 'usr_01J279R1YBK0AE2G4HYNWYVVV5' } req.user.userId usr_01J279R1YBK0AE2G4HYNWYVVV5 fetch user details for userId User { id: 'usr_01J279R1YBK0AE2G4HYNWYVVV5', created_at: 2024-07-07T19:11:48.676Z, updated_at: 2024-07-07T19:11:48.676Z, deleted_at: null, role: 'member', email: 'chef2@example.com', first_name: null, last_name: null, api_token: null, metadata: null, store_id: 'store_01J279R1Y5PDA7W1E78N2Z1BDC', role_id: null }

this worked properly and as you can see the user details are attached to the context as expected and the product is created.

When using the admin UI the flow stops in the authenticate middleware and returns a 401 dispite being logged in with the same creds.

I created a logger middleware to log out some details BEFORE authenticate middleware and there is no auth context or req.user

auth_context undefined req.user undefined

auth_context never exists on the req object

adrien2p commented 1 month ago

My bad i thought you were using medusa v2 😅 are you testing everything on your local machine?

TimCrooker commented 1 month ago

@adrien2p everything is running local

adrien2p commented 1 month ago

and your cors are properly configured?

TimCrooker commented 1 month ago

@adrien2p yes. If it was not then I would be unable to log in.

adrien2p commented 1 month ago

So with those information it sounds like the cookie is not sent to the api, could you check that please

TimCrooker commented 1 month ago

Cookies provided from the network tab headers:

lng=en; ajs_user_id=usr_01J279R1YBK0AE2G4HYNWYVVV5; ajs_anonymous_id=7f3288f3-671e-41bd-8b08-a3d18b865648; connect.sid=s%3AW73EcOcNNezelIypTmmvW7Owc9ZoXf6e.OOfG6VZ92CAn8%2F2G7jUAgCZafCuQklmRqwj0MmteXxM

Cookies recieved in my logger middleware before authentication call on server:

cookies { lng: 'en', ajs_user_id: 'usr_01J279R1YBK0AE2G4HYNWYVVV5', ajs_anonymous_id: '7f3288f3-671e-41bd-8b08-a3d18b865648', 'connect.sid': 's:W73EcOcNNezelIypTmmvW7Owc9ZoXf6e.OOfG6VZ92CAn8/2G7jUAgCZafCuQklmRqwj0MmteXxM' }

TimCrooker commented 1 month ago

Weirdly it seems that for all GET calls everything works as expected but for all POST calls where i have the authentication middleware registered it fails and looks like this in network tools:

Screenshot 2024-07-12 at 9 31 30 AM

'connect.sid': 's:W73EcOcNNezelIypTmmvW7Owc9ZoXf6e.OOfG6VZ92CAn8/2G7jUAgCZafCuQklmRqwj0MmteXxM' }

TimCrooker commented 1 month ago

After even further investigation seems that in the UI the GET call for products works and logs the cookies but cookies are undefined for the POST call to create a product

TimCrooker commented 1 month ago

@adrien2p Anything on this? This is acting as a bit of a road block for me at the moment. Seems only POST calls have what looks like CORS issues when using this middleware. When not using the middleware its fine but i cant get user context

TimCrooker commented 1 month ago

I was able to resolve this myself by digging into the req object and finding that user_id exists in session['user_id']

You should probably remove the invalid tutorial for implementing this functionality though. it simply does not work and wasted a ton of time

here is is:

https://docs.medusajs.com/development/api-routes/example-logged-in-user