Skip to content

Instantly share code, notes, and snippets.

@apostopher
Created November 14, 2018 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apostopher/c01c9e995e30592b8f67c0426ed6f3e0 to your computer and use it in GitHub Desktop.
Save apostopher/c01c9e995e30592b8f67c0426ed6f3e0 to your computer and use it in GitHub Desktop.
isAuthenticated Directive
import { SchemaDirectiveVisitor } from 'graphql-tools'
export function authenticate(resolver, { strict = true } = {}) {
return async (source, args, context, info) => {
const { req } = context
const token = getTokenFromReq(req)
try {
const currentUser = await context.loadUserFromToken(token)
context.currentUser = currentUser
context.authToken = token
} catch(error) {
if (strict) throw new Error('You are not authorized to access this resource.')
}
return resolver(source, args, context, info)
}
}
export default class AuthDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
if (field.resolve) {
// this.args contains the arguments passed to the directive.
field.resolve = authenticate(field.resolve, this.args)
// Update the description with emoji!
field.description = `🔑 ${field.description || ''}`
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment