I have one additional API route which starts an import proces. The route is configures in the global Payload config:
express: {
postMiddleware: [importAccess],
},
endpoints: [
{
path: "/import/run/:collection",
method: "get",
handler: importHandler,
},
],
Most works as expected, but i can't seem to get access control working within the middleware or route itself. What i would like to do is call a generic "isAdmin" function (which i already use in other places) on an user object. But the user variable within the request is always undefined. A workaround was loading the import global collection which as access control on it. According to the documentation, access control should be invoked when using req.payload.findGlobal but this is not the case. The collection object is always returned when calling the custom API route. Calling the normal API route for this collections results in a 403 error as expected.
What is the correct way to handle this? Thanks.
Did you call payload.authenticate() after payload.init()?
undefined users in the cb seem related to that common issue
https://payloadcms.com/docs/authentication/using-middleware#using-the-payload-auth-middleware
router.use(payload.authenticate);
Ah, i will test that, the official documentation states that authentication is always invoked on req.payload.find
https://payloadcms.com/docs/rest-api/overview#custom-endpoints
There seems to be a type error: throw new TypeError('Router.use() requires a middleware function')
Also, i am configuring my routes within the payload config, not directly in Express, you should say the authentication is already invoked.
Hmmm
I'm looking at
https://payloadcms.com/docs/rest-api/overview#custom-endpoints
They say that the req object applies access control
As you guys already pointed out, the authentication middleware should be called for you before your custom
endpoints
are called.
Since you are using
postMiddleware
that is going to be called at the very end, but it seems to me you would want to get your access control handled first as
preMiddleware
This is strange, it worked for a couple of minutes (had a user object within the response) and now its gone again...
To simplify why you have you, you could do this instead:
handler: [importAccess, importHandler],
@dribbens, i also tested with preMiddleware but that made no difference.
I will try that
Yeah, it shouldn't matter
well...
preMiddleware
means you won't have
req.user
assigned yet
postMiddleware
should have
req.user
as well as the suggestion I made with the
handler: [accessImport, importHandler]
. This is probably not going to fix your issue.
Thats sound logical.
It seems to work with the handler and middleware together. Will investigate what went wrong there.
That is interesting! I'm glad it works for you. There could be a bug in globals postMiddleware or something else going on that is specific to your project.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.