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.
import Recipe from '#models/recipe'
import { Resolver, Query, Mutation, Authorized } from '@foadonis/graphql'
@Resolver(Recipe)
class RecipeResolver {
@Query(() => [Recipe])
@Authorized()
recipes() {
// ...your logic
}
@Mutation(() => [Recipe])
@Authorized()
createRecipe() {
// ...your logic
}
}The Authorized decorator accepts Bouncer abilities allowing you to ensure your user respects specific requirements.
import Recipe from '#models/recipe'
import { Resolver, Query, Authorized } from '@foadonis/graphql'
import abilities from '#abilities/main'
@Resolver(Recipe)
class RecipeResolver {
@Query(() => [Recipe])
@Authorized(abilities.isAdmin)
recipes() {
// ...your logic
}
}import { Bouncer } from '@adonisjs/bouncer'
const abilities = {
isAdmin = Bouncer.ability((user) => user.isAdmin),
}
export default abilitiesYou 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.
import { ObjectType, Authorized } from '@foadonis/graphql'
import abilities from '#abilities/main'
@ObjectType()
export default class User {
@Field()
declare id: string
@Field()
@Authorized()
declare fullName: string
@Field()
@Authorized(abilities.isAdmin)
declare email: string
}Access authenticated User
Using @CurrentUser
import Recipe from '#models/recipe'
import { Resolver, Query, CurrentUser } from '@foadonis/graphql'
@Resolver(Recipe)
class RecipeResolver {
@Query(() => [Recipe])
recipes(@CurrentUser() user: User) {
// ...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
import Recipe from '#models/recipe'
import { HttpContext } from '@adonisjs/core/http'
import { Resolver, Query, Ctx } from '@foadonis/graphql'
@Resolver(Recipe)
class RecipeResolver {
@Query(() => [Recipe])
recipes(@Ctx() ctx: HttpContext) {
const user = ctx.auth.getUserOrFail()
// ...your logic
}
}