Skip to content

Instantly share code, notes, and snippets.

@pedroraft
Last active April 15, 2018 18:38
Show Gist options
  • Save pedroraft/343c46ce5e1caa8c3f0146b1091d3e46 to your computer and use it in GitHub Desktop.
Save pedroraft/343c46ce5e1caa8c3f0146b1091d3e46 to your computer and use it in GitHub Desktop.
medium tutorial token validation directive
const {SchemaDirectiveVisitor} = require('graphql-tools')
const {defaultFieldResolver} = require('graphql')
//...
class AuthDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
const {resolve = defaultFieldResolver} = field
const {roles: expectedRoles = []} = this.args
console.log(expectedRoles.length);
field.resolve = (...args) => {
console.log(expectedRoles.length);
const [, , context] = args
if (context.jwt) {
if (expectedRoles.length <= 0 ||
expectedRoles.some(r => context.jwt.roles.includes(r))
) {
// Call original resolver if role check has passed
return resolve.apply(this, args)
}
}
// We has two options here. throw an error or return null (if field is nullable).
throw new Error(
`You are not authorized. Expected roles: ${expectedRoles.join(', ')} for field ${field.name}`,
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment