Allow multiple roles per query.
ernestomr87 opened this issue · comments
Ernesto Miguel Rodríguez Rodríguez commented
Allow multiple roles per query.
Jonny Green commented
Hey @ernestomr87 thanks for submitting this issue, do you have any additional context around this? E.g. examples of what you would like to see with this etc? Also, would you be interested in contributing?
Jack Burgess commented
Hi @jonnydgreen. I've just started to implement mercurius-auth
and came across this same requirement. Needing the ability to pass multiple roles to the @auth
directive. This is the solution I came up with based on the example from the README.
'use strict'
const Fastify = require('fastify')
const mercurius = require('mercurius')
const mercuriusAuth = require('mercurius-auth')
const app = Fastify()
const schema = `
directive @auth(requires: [Role]) on OBJECT | FIELD_DEFINITION
enum Role {
ADMIN
REVIEWER
USER
UNKNOWN
}
type Query {
add(x: Int, y: Int): Int @auth(requires: [ADMIN, REVIEWER, USER])
}
`
const resolvers = {
Query: {
add: async (_, { x, y }) => x + y
}
}
app.register(mercurius, {
schema,
resolvers
})
app.register(mercuriusAuth, {
// Using '@fastify/jwt' to inject the user.id and user.role
// authContext (context) { },
async applyPolicy (policy, parent, args, context, info) {
if (!context.user.id)
throw new Error(`No Authorization was found in request.headers`)
const roles = [context.user.role]
const requires = policy.arguments[0].value.values.map((roleEnum) => roleEnum.value)
const isAuthorized = roles.some((role: string) => requires.includes(role))
if (isAuthorized) return true
throw new Error(`Insufficient permission for ${info.fieldName}`)
},
authDirective: 'auth'
})
app.listen({ port: 3000 })
Jonny Green commented
Fantastic, thanks for posting your solution @ninnjak ! Would you be interested in contributing this example plus documentation to the repo?
Jack Burgess commented
Yeah sure, opened PR here #110