Skip to content

Instantly share code, notes, and snippets.

@mhaagens
Last active February 15, 2019 13:34
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 mhaagens/761d5ad6ad4a4b529381142c715da240 to your computer and use it in GitHub Desktop.
Save mhaagens/761d5ad6ad4a4b529381142c715da240 to your computer and use it in GitHub Desktop.
Authentication and authorization using GraphQL Schema Directives: src/directives/requireAuthDirective.js
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;
@duncanhall
Copy link

@mhaagens Can you explain what is meant by:

const { resolve = defaultFieldResolver } = field;

on line 8?

@voluntadpear
Copy link

@duncanhall he is missing this import:
import { defaultFieldResolver } from 'graphql'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment