Skip to content

Instantly share code, notes, and snippets.

@benawad
Last active June 1, 2021 15:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benawad/f553c5a1719bf3cf479cd28005ccc09c to your computer and use it in GitHub Desktop.
Save benawad/f553c5a1719bf3cf479cd28005ccc09c to your computer and use it in GitHub Desktop.
middleware role
export const hasRole: (role: string) => MiddlewareFn<MyContext> = (role: string) => async ({ context }, next) => {
if (!context.req.session!.userId) {
throw new Error("not authenticated");
}
const user = await User.findOne(context.req.session!.userId);
if (!user) {
throw new Error('not authenticated')
}
if (user.role !== role) {
throw new Error('not authorized');
}
return next();
};
@UseMiddleware(hasRole("admin"))
@Query(() => String)
async hello() {
return "Hello World!";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment