Last active
April 15, 2018 18:38
-
-
Save pedroraft/343c46ce5e1caa8c3f0146b1091d3e46 to your computer and use it in GitHub Desktop.
medium tutorial token validation directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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