Last active
February 15, 2019 13:34
-
-
Save mhaagens/761d5ad6ad4a4b529381142c715da240 to your computer and use it in GitHub Desktop.
Authentication and authorization using GraphQL Schema Directives: src/directives/requireAuthDirective.js
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, | |
AuthenticationError | |
} = require("apollo-server"); | |
class RequireAuthDirective extends SchemaDirectiveVisitor { | |
visitFieldDefinition(field) { | |
const { resolve = defaultFieldResolver } = field; | |
const { role } = this.args; | |
field.resolve = async function(...args) { | |
const [, , ctx] = args; | |
if (ctx.req && ctx.req.user) { | |
if (role && (!ctx.req.user.role || !ctx.req.user.role.includes(role))) { | |
throw new AuthenticationError( | |
"You are not authorized to view this resource." | |
); | |
} else { | |
const result = await resolve.apply(this, args); | |
return result; | |
} | |
} else { | |
throw new AuthenticationError( | |
"You must be signed in to view this resource." | |
); | |
} | |
}; | |
} | |
} | |
module.exports = RequireAuthDirective; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mhaagens Can you explain what is meant by:
on line 8?