|
| 1 | +import gql from 'graphql-tag' |
| 2 | +import { defaultFieldResolver } from 'graphql' |
| 3 | +import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils' |
| 4 | +import { GqlAuthorizationError } from '@/lib/error' |
| 5 | + |
| 6 | +const DIRECTIVE_NAME = 'auth' |
| 7 | + |
| 8 | +export const typeDef = gql` |
| 9 | + directive @${DIRECTIVE_NAME}(allow: [Role!]!) on FIELD_DEFINITION |
| 10 | + enum Role { |
| 11 | + ADMIN |
| 12 | + OWNER |
| 13 | + USER |
| 14 | + } |
| 15 | +` |
| 16 | + |
| 17 | +export function apply (schema) { |
| 18 | + return mapSchema(schema, { |
| 19 | + [MapperKind.OBJECT_FIELD]: fieldConfig => { |
| 20 | + const upperDirective = getDirective(schema, fieldConfig, DIRECTIVE_NAME)?.[0] |
| 21 | + if (upperDirective) { |
| 22 | + const { resolve = defaultFieldResolver } = fieldConfig |
| 23 | + const { allow } = upperDirective |
| 24 | + return { |
| 25 | + ...fieldConfig, |
| 26 | + resolve: async function (parent, args, context, info) { |
| 27 | + checkFieldPermissions(allow, parent, args, context, info) |
| 28 | + return await resolve(parent, args, context, info) |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + }) |
| 34 | +} |
| 35 | + |
| 36 | +function checkFieldPermissions (allow, parent, args, { me }, { parentType }) { |
| 37 | + // TODO: should admin users always have access to all fields? |
| 38 | + |
| 39 | + if (allow.indexOf('OWNER') >= 0) { |
| 40 | + if (!me) { |
| 41 | + throw new GqlAuthorizationError('you must be logged in to access this field') |
| 42 | + } |
| 43 | + |
| 44 | + switch (parentType.name) { |
| 45 | + case 'User': |
| 46 | + if (me.id !== parent.id) { |
| 47 | + throw new GqlAuthorizationError('you must be the owner to access this field') |
| 48 | + } |
| 49 | + break |
| 50 | + default: |
| 51 | + // we could just try the userId column and not care about the type |
| 52 | + // but we want to be explicit and throw on unexpected types instead |
| 53 | + // to catch potential issues in our authorization layer fast |
| 54 | + throw new GqlAuthorizationError('failed to check owner: unknown type') |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments