Authorization with GraphQL Shield

In this video we’ll explore some of the logic and input rules that come with GraphQL Shield to protect against unwanted requests.

Notes

1const { applyMiddleware } = require("graphql-middleware");
2
3const schemaWithPermissions = applyMiddleware(schema, permissions);
4
1const { shield, rule, and, inputRule, deny } = require("graphql-shield");
2
3const permissions = shield({
4 Query: {
5 "*": deny,
6 users: and(isAuthenticated, isAdmin),
7 me: isAuthenticated,
8 },
9 Mutation: {
10 createUser: isNotAlreadyRegistered,
11 },
12});
13
1const isAuthenticated = rule()(async (parent, args, ctx, info) => {
2 return !!ctx.headers["user-id"];
3});
4
5const isAdmin = rule()(async (parent, args, ctx, info) => {
6 const user = users.find(({ id }) => id === ctx.headers["user-id"]);
7
8 return user && user.role === "ADMIN";
9});
10
11const isNotAlreadyRegistered = inputRule()((yup) =>
12 yup.object({
13 input: yup.object({
14 name: yup.string().required(),
15 email: yup
16 .string()
17 .email()
18 .required()
19 .notOneOf(
20 users.map(({ email }) => email),
21 "A user exists with this email. Choose another."
22 ),
23 }),
24 })
25);
26