Skip to content

Instantly share code, notes, and snippets.

@jericbas
Created October 19, 2019 19:30
Show Gist options
  • Save jericbas/cfac92005319bb112cf615c6161fcdd8 to your computer and use it in GitHub Desktop.
Save jericbas/cfac92005319bb112cf615c6161fcdd8 to your computer and use it in GitHub Desktop.
Check authorization header using schema directives
directive @isAuth on FIELD_DEFINITION
type Mutation {
addPost(title: String!, content: String! ): Post @isAuth
}
const { ApolloServer, SchemaDirectiveVisitor } = require("apollo-server-express");
const { defaultFieldResolver } = require("graphql");
class IsAuthDirective extends SchemaDirectiveVisitor {
visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function(...args) {
const { authUser } = args[2]; // context
if (!authUser) {
throw new Error("Invalid token");
}
return await resolve.apply(this, args);
};
}
}
function context({req}) {
const token = req.headers.authorization || "";
// Insert token validation
return {authUser}
}
const server = new ApolloServer({
// other options
context,
schemaDirectives : {
isAuth: IsAuthDirective
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment