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

Authentication Middleware does not work via Admin Dash #8046

Closed
TimCrooker opened this issue Jul 9, 2024 · 17 comments
Closed

Authentication Middleware does not work via Admin Dash #8046

TimCrooker opened this issue Jul 9, 2024 · 17 comments

Comments

@TimCrooker
Copy link

TimCrooker commented Jul 9, 2024

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
Copy link

Hey can I work on this issue?

@adrien2p
Copy link
Member

@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
Copy link
Author

@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: '[email protected]',
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
Copy link
Member

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

@TimCrooker
Copy link
Author

@adrien2p everything is running local

@adrien2p
Copy link
Member

and your cors are properly configured?

@TimCrooker
Copy link
Author

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

@adrien2p
Copy link
Member

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

@TimCrooker
Copy link
Author

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
Copy link
Author

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
Copy link
Author

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
Copy link
Author

@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
Copy link
Author

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

@EdgarSilvaAlluxi
Copy link

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

How did you solved exactly?, I'm facing the same issue, GET calls are ok, but in the POST; DELETE, I always get 401

Copy link
Contributor

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 3 days.

@github-actions github-actions bot added the Stale label Oct 15, 2024
Copy link
Contributor

This issue was closed because it has been stalled for 3 days with no activity.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Oct 19, 2024
@SalahAdDin
Copy link

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

How did you solved exactly?, I'm facing the same issue, GET calls are ok, but in the POST; DELETE, I always get 401

Did you?

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

No branches or pull requests

5 participants