This guide walks you through setting up Permissions from scratch. By the end, you will have:

  • A set of permission definitions
  • A Role model that stores permissions
  • A User model with role assignments
  • Authorization checks in a controller using Bouncer

You need an AdonisJS 7 app with Lucid and the auth package. Your project must point at the AdonisJS Plus registry. See Installation and setup.

Permissions uses AdonisJS Bouncer under the hood to authorize actions. If you have not already installed Bouncer, run the following command first.

Terminal
node ace add @adonisjs/bouncer

This command installs the package, creates the app/abilities/main.ts file, generates the Bouncer middleware at app/middleware/initialize_bouncer_middleware.ts, and registers it in your HTTP kernel.

Next, install Permissions. The command installs the package and runs its configure step.

Terminal
node ace add @adonisplus/permissions

The configure step makes these changes:

  1. Creates start/permissions.ts, where you define your permissions.
  2. Creates app/middleware/authorize_middleware.ts and registers it in start/kernel.ts as the named middleware authorize.
  3. Adds the indexPermissions() hook to adonisrc.ts. The hook writes .adonisjs/client/permissions.d.ts, which your frontend imports as @generated/permissions.
  4. Creates a Guard component in inertia/utils/permissions.tsx (React) or inertia/utils/permissions.vue (Vue), when inertia/pages holds .tsx or .vue files.

Permissions represent the actions a user can perform in your application. You define them in a single file so that every part of your codebase references the same set of keys.

The configure command already created the start/permissions.ts file for you. Open it and declare your permissions using the definePermissions function. Each permission follows the resource.action pattern.

start/permissions.ts
import { definePermissions } from '@adonisplus/permissions'

export const permissions = definePermissions({
  product: {
    create: 'Create new products',
    update: 'Update existing products',
    delete: 'Delete products permanently',
  },
  billing: {
    refund: 'Issue refunds to customers',
  },
})

export type PermissionKey = ReturnType<typeof permissions.keys>[number]

This produces four permission keys: product.create, product.update, product.delete, and billing.refund. All keys are type-safe and autocompleted by your editor.

Keep the PermissionKey export. The authorize middleware and your frontend types import it.

You need two database tables to store roles and their assignments:

  • roles: Stores role names and the permissions assigned to each role as a JSON column.
  • user_roles: A pivot table that links users to their roles.
  1. Run the following commands to generate the two migration files.

    Terminal
    node ace make:migration roles
    Terminal
    node ace make:migration user_roles
  2. Open the generated roles migration file and define the table schema. The permissions column stores a JSON array of permission keys assigned to the role.

    database/migrations/xxxx_create_roles.ts
    import { BaseSchema } from '@adonisjs/lucid/schema'
    
    export default class extends BaseSchema {
      protected tableName = 'roles'
    
      async up() {
        this.schema.createTable(this.tableName, (table) => {
          table.increments('id')
          table.string('name').unique().notNullable()
          table.text('permissions').defaultTo('[]')
          table.timestamp('created_at')
          table.timestamp('updated_at')
        })
      }
    
      async down() {
        this.schema.dropTable(this.tableName)
      }
    }
    
  3. Open the generated user_roles migration file and define the pivot table schema. The unique constraint on user_id and role_id prevents duplicate role assignments.

    database/migrations/xxxx_create_user_roles.ts
    import { BaseSchema } from '@adonisjs/lucid/schema'
    
    export default class extends BaseSchema {
      protected tableName = 'user_roles'
    
      async up() {
        this.schema.createTable(this.tableName, (table) => {
          table.increments('id')
          table.integer('user_id').notNullable().unsigned()
          table.integer('role_id').notNullable().unsigned()
          table.unique(['user_id', 'role_id'])
        })
      }
    
      async down() {
        this.schema.dropTable(this.tableName)
      }
    }
    
  4. Terminal
    node ace migration:run

Permissions provides two mixins that add role and permission management to your Lucid models.

Apply withPermissions to the Role model

Section titled "Apply withPermissions to the Role model"

The withPermissions mixin teaches the Role model how to read and write the permissions JSON column. It adds methods like givePermissions, syncPermissions, and revokePermissions to role instances.

app/models/role.ts
import { RoleSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withPermissions } from '@adonisplus/permissions'

export default class Role extends compose(
  RoleSchema,
  withPermissions() 
) {}

The withRoles mixin connects users to roles through the pivot table. It adds methods like assignRole, syncRoles, and hasRole to user instances. You must tell the mixin which model represents roles and which table stores the assignments.

app/models/user.ts
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withRoles } from '@adonisplus/permissions'
import Role from '#models/role'

export default class User extends compose(
  UserSchema,
  withRoles({
    roleModel: () => Role,
    pivotTable: 'user_roles',
  })
) {}

Create the roles in a seeder, give them permissions, and assign one to a user. Use permissions.getKey() to reference permission keys with full type safety. givePermissions adds keys to a role. syncPermissions replaces the role's keys with the list you pass. permissions.active() returns every active key. The admin role keeps the keys that exist when the seeder runs. Sync it again after you add a permission.

Terminal
node ace make:seeder role
database/seeders/role_seeder.ts
import { BaseSeeder } from '@adonisjs/lucid/seeders'
import Role from '#models/role'
import User from '#models/user'
import { permissions } from '#start/permissions'

export default class extends BaseSeeder {
  async run() {
    const editor = await Role.create({ name: 'editor' })
    await editor.givePermissions([
      permissions.getKey('product.create'),
      permissions.getKey('product.update'),
    ])

    const admin = await Role.create({ name: 'admin' })
    await admin.syncPermissions(permissions.active())

    const user = await User.findOrFail(1)
    await user.assignRole(editor)
  }
}
Terminal
node ace db:seed

A user can hold several roles. Their permissions are the union of the permissions of every role they hold.

Permissions integrates with Bouncer by converting your permission definitions into Bouncer abilities. This lets you use the same bouncer.authorize API for both hand-written abilities and role-based permissions.

Open your Bouncer middleware and spread the generated abilities into the Bouncer constructor alongside your existing abilities.

app/middleware/initialize_bouncer_middleware.ts
import * as abilities from '#abilities/main'
import { policies } from '#generated/policies'
import { permissions } from '#start/permissions'

import { Bouncer } from '@adonisjs/bouncer'
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'

const allAbilities = {
  ...abilities,
  ...permissions.abilities(),
}

export default class InitializeBouncerMiddleware {
  async handle(ctx: HttpContext, next: NextFn) {
    ctx.bouncer = new Bouncer(
      () => ctx.auth.user || null,
      abilities, 
      allAbilities, 
      policies
    ).setContainerResolver(ctx.containerResolver)

    if ('view' in ctx) {
      ctx.view.share(ctx.bouncer.edgeHelpers)
    }

    return next()
  }
}

declare module '@adonisjs/core/http' {
  export interface HttpContext {
    bouncer: Bouncer<
      Exclude<HttpContext['auth']['user'], undefined>,
      typeof abilities, 
      typeof allAbilities, 
      typeof policies
    >
  }
}

The permissions.abilities() call is placed outside the middleware class so it runs once at import time, not on every request.

You can now protect controller actions using bouncer.authorize. Pass the permission key as a string, and Bouncer checks whether the logged-in user holds a role with that permission. If the check fails, Bouncer responds with a 403. With the seeded roles, an editor can create products and gets a 403 on delete. An admin can do both.

app/controllers/products_controller.ts

import type { HttpContext } from '@adonisjs/core/http'

export default class ProductsController {
  async store({ bouncer }: HttpContext) {
    await bouncer.authorize('product.create')

    // User has permission, proceed
  }

  async destroy({ bouncer }: HttpContext) {
    await bouncer.authorize('product.delete')

    // User has permission, proceed
  }
}

You can also check a permission on the route, with the authorize middleware. See Authorizing routes.

Defining permissions

Prefixes, aliases and inactive permissions.

Managing roles

Assign, sync and revoke roles.

Managing permissions

Give permissions to a user without a role.

Checking access

Check permissions in code, and scope them to a token.

Bouncer integration

Authorize controllers and routes, and mix in your own abilities.

Team permissions

Give a user different roles in different teams.