Skip to content

Instantly share code, notes, and snippets.

@southpolesteve
Last active February 6, 2018 21:57
Show Gist options
  • Save southpolesteve/e190e9572d060b515836666610b858a9 to your computer and use it in GitHub Desktop.
Save southpolesteve/e190e9572d060b515836666610b858a9 to your computer and use it in GitHub Desktop.
graphQL schema auth
// Search every field and swap out the resolvers if an `authorize` key is present
export function authorize (schema) {
// We require auth for all mutations
const mutations = (schema._mutationType && Object.keys(schema._mutationType._fields)) || []
mutations.forEach(mutationName => {
const field = schema._mutationType._fields[mutationName]
invariant(field.authorize, `Mutation: "${mutationName}" must have an "authorize" property. Use "*" for no auth`)
})
// Walk the type map and all the fields and wrap resolvers in an auth check
Object.keys(schema._typeMap).forEach((typName) => {
const typ = schema._typeMap[typName]
if (!typ._fields) {
return
}
Object.keys(typ._fields).forEach((fieldName) => {
const field = typ._fields[fieldName]
if (field.authorize) {
typ._fields[fieldName] = wrapResolver(field)
}
})
})
return schema
}
function wrapResolver (field) {
const {
resolve: oldResolver = defaultFieldResolver,
authorize: fieldAuthorize,
description: oldDescription
} = field
const resolve = async function (root, args, { auth }, info) {
await auth.checkAuthorization(fieldAuthorize, ...arguments)
return oldResolver(...arguments)
}
const description = oldDescription || 'This field requires authorization.'
return { ...field, resolve, description, authorize, isAuthorized: true }
}
export const User = new GraphQLObjectType({
name: 'User',
fields: () => {
return {
name: {
authorize: 'admin' // Accepts a string. Checks if the current user in admin
type: GraphQLString
},
email: {
authorize: currentUser => { return false } // Also accepts a custom function that can do more complicated things
type: GraphQLString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment