hsynlms / fastify-guard

A simple user role and scope check plugin to protect endpoints for Fastify
MIT License
49 stars 9 forks source link

Cannot read property 'role' of undefined #1

Closed YuriFontella closed 3 years ago

YuriFontella commented 3 years ago

preHandler: [fastify.guard.role(['admin'])] -> In this way, preHandler is already called upon startup. And not on the route call.

image

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"

hsynlms commented 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.

YuriFontella commented 3 years ago

image image image

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.

hsynlms commented 3 years ago

@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

YuriFontella commented 3 years ago

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

image image

This is what I find very strange

YuriFontella commented 3 years ago
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.