Created
October 19, 2019 19:30
-
-
Save jericbas/cfac92005319bb112cf615c6161fcdd8 to your computer and use it in GitHub Desktop.
Check authorization header using schema directives
This file contains hidden or 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
directive @isAuth on FIELD_DEFINITION | |
type Mutation { | |
addPost(title: String!, content: String! ): Post @isAuth | |
} |
This file contains hidden or 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 { 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