Closed YuriFontella closed 3 years ago
Hello @YuriFontella
fastify-guard checks user roles and scopes in the user
object defined in the request. If it does not exist, the plugin throws exceptions.
I attached an example below. You can parse and set the request user object before preHandler hook runs. To do that please check this documentation which tells us more about it.
request.user = {
name: 'john doe',
age: 28,
roles: [...],
scopes: [..]
}
Could you please be sure that when this preHandler (in the image of yours) function is invoked, the user object does exist in the request.
The error happens without having made a request for the route. The route preHandler runs when I start the server. The addHook has not been run before.
@YuriFontella it looks like the plugin has not been initialized at that moment so guard
decorator is undefined. Are you setting up Fastify Server in the below order?
https://www.fastify.io/docs/latest/Getting-Started/#loading-order-of-your-plugins
So that's it, according to the life cycle, hooks come after plugins. And how would I do to authenticate the user before registering the plugin?
https://gist.github.com/YuriFontella/1a3bc5a2da9ee005aa5fc3f44b247af4 demo project
This is what I find very strange
fastify.after(() => {
fastify.get('/', {
preHandler: [fastify.guard.role('guest')]
},
async (request, reply) => {
let data = await fastify.knex .select() .from('users')
reply.send(data)
})
})
it worked using the after function ... I don't know if this was the best solution.
Thanks for attention.
preHandler: [fastify.guard.role(['admin'])] -> In this way, preHandler is already called upon startup. And not on the route call.
Inside the preHandler function... fastify.guard.role(['admin']) don't work.
If you can correct me if I did something wrong.
"fastify": "^3.8.0"