Authorization

Control data and query access in a GraphQL API

The graphQL API provides a simple way to authorize incoming requests. Each GraphQLQuery instance has a authorize method, that takes in a function that must return true or false to indicate if the current request should be authorized or not.

The authorization function receives the current graphQL context. This contains all the information about the current request, including a manager instance for easy database access.

Authorize

You may call the authorize method on a GraphQLQuery instance to add a new authorization function. You may call this method as many times as you need. All of the authorization functions will be run, and if any of them return false, the request will throw an Unauthorized error.

const { tensei, graphQlQuery } = require('@tensei/core')

tensei()
    .graphQlQueries([
        graphQlQuery('Get Purchases')
            .query()
            .path('get_customer_purchases')
            .authorize(({ user }) => ! user.public)
            .authorize(async ({ user }) => user?.permissions?.includes('has:purchases'))
            .handle(async (parent, args, ctx, info) => ctx.user.purchases)
    ])

If you are using the auth plugin, the context passed to the authorize function will contain the currently authenticated user.

Authorizing existing queries

You may wish to add custom authorization functions on queries automatically generated by Tensei. To do this, first you need to get the query, and call the authorize function with your own authorization function. A good place to do this is in the tensei().register() function.

const { tensei } = require('@tensei/core')

tensei()
    .register(({ getQuery }) => {
        getQuery('update_comment')
            ?.authorize(({ user, body }) => body.comment.user !== user.id)
    })