Authorization

Authentication and Authorization are supported out of the box using @adonisjs/auth (authentication) and @adonisjs/bouncer (authorization).

You can find more information about Middlewares on the Official TypeGraphQL documentation

Secure operations

You can secure your queries to only allow authenticated users to use them by using the @Authorized decorator.

app/graphql/resolvers/recipe_resolver.ts
import  from '#models/recipe'
import { , , ,  } from '@foadonis/graphql'

@()
class  {
  @(() => [])
  @()
  () {
    // ...your logic
  }

  @(() => [])
  @()
  () {
    // ...your logic
  }
}

The Authorized decorator accepts Bouncer abilities allowing you to ensure your user respects specific requirements.

import  from '#models/recipe'
import { , ,  } from '@foadonis/graphql'
import  from '#abilities/main'

@()
class  {
  @(() => [])
  @(.isAdmin)
  () {
    // ...your logic
  }
}
import {  } from '@adonisjs/bouncer'

const  = {
   = .(() => .isAdmin),
}

export default 

You can pass multiple abilities to @Authorized. The user will be authorized only if all of them pass.

Secure objects

The @Authorized decorator also works on fields allowing you to protect only certain fields. With the following example, only authenticated user can access the fullName and only admins can access email.

app/models/user.ts
import { ,  } from '@foadonis/graphql'
import  from '#abilities/main'

@()
export default class  {
  @Field()
  declare : string

  @Field()
  @()
  declare : string

  @Field()
  @(.isAdmin)
  declare : string
}

Access authenticated User

Using @CurrentUser

app/graphql/resolvers/recipe_resolver.ts
import  from '#models/recipe'
import { , ,  } from '@foadonis/graphql'

@()
class  {
  @(() => [])
  (@() : ) {
    // ...your logic
  }
}

The @CurrentUser decorator makes your operation only available to authenticated users. If you still want to allow guest, you must use the context.

Using the context

app/graphql/resolvers/recipe_resolver.ts
import  from '#models/recipe'
import {  } from '@adonisjs/core/http'
import { , ,  } from '@foadonis/graphql'

@()
class  {
  @(() => [])
  (@() : ) {
    const  = .auth.getUserOrFail()
    // ...your logic
  }
}

On this page