Created
November 14, 2018 14:10
-
-
Save apostopher/c01c9e995e30592b8f67c0426ed6f3e0 to your computer and use it in GitHub Desktop.
isAuthenticated 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
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