GraphQL
Beginner
1 min read
Role-Based Access Control in GraphQL
Example
// Role enum matches schema enum Role { ADMIN EDITOR VIEWER }
// Utility: assert role
function requireRole(currentUser, ...roles) {
if (!currentUser) {
throw new GraphQLError('Unauthenticated', {
extensions: { code: 'UNAUTHENTICATED' },
});
}
if (!roles.includes(currentUser.role)) {
throw new GraphQLError('Forbidden', {
extensions: { code: 'FORBIDDEN' },
});
}
}
// CASL integration
import { AbilityBuilder, createMongoAbility } from '@casl/ability';
function defineAbilityFor(user) {
const { can, cannot, build } = new AbilityBuilder(createMongoAbility);
if (user.role === 'ADMIN') {
can('manage', 'all');
} else if (user.role === 'EDITOR') {
can('read', 'Post');
can('create', 'Post');
can('update', 'Post', { authorId: user.id }); // own posts only
cannot('delete', 'Post');
} else {
can('read', 'Post', { published: true });
}
return build();
}
// In resolver
const resolvers = {
Mutation: {
deletePost: async (_, { id }, { currentUser, db }) => {
const ability = defineAbilityFor(currentUser);
const post = await db.posts.findById(id);
if (ability.cannot('delete', post)) throw new GraphQLError('Forbidden', { extensions: { code: 'FORBIDDEN' } });
return db.posts.delete(id);
},
},
};
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL