Quick start
On this page
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
Overview
Section titled "Overview"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.
Install and configure
Section titled "Install and configure"Permissions uses AdonisJS Bouncer under the hood to authorize actions. If you have not already installed Bouncer, run the following command first.
node ace add @adonisjs/bouncerThis 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.
node ace add @adonisplus/permissionsThe configure step makes these changes:
- Creates
start/permissions.ts, where you define your permissions. - Creates
app/middleware/authorize_middleware.tsand registers it instart/kernel.tsas the named middlewareauthorize. - Adds the
indexPermissions()hook toadonisrc.ts. The hook writes.adonisjs/client/permissions.d.ts, which your frontend imports as@generated/permissions. - Creates a
Guardcomponent ininertia/utils/permissions.tsx(React) orinertia/utils/permissions.vue(Vue), wheninertia/pagesholds.tsxor.vuefiles.
Define permissions
Section titled "Define permissions"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.
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.
Create the database tables
Section titled "Create the database tables"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.
Create the migrations
Section titled "Create the migrations"Run the following commands to generate the two migration files.
node ace make:migration rolesnode ace make:migration user_rolesDefine the roles table
Section titled "Define the roles table"Open the generated roles migration file and define the table schema. The
permissionscolumn stores a JSON array of permission keys assigned to the role.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) } }Define the user_roles pivot table
Section titled "Define the user_roles pivot table"Open the generated user_roles migration file and define the pivot table schema. The unique constraint on
user_idandrole_idprevents duplicate role assignments.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) } }Run the migrations
Section titled "Run the migrations"node ace migration:run
Set up models
Section titled "Set up models"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.
import { RoleSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withPermissions } from '@adonisplus/permissions'
export default class Role extends compose(
RoleSchema,
withPermissions()
) {}
Apply withRoles to the User model
Section titled "Apply withRoles to the User model"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.
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',
})
) {}
Seed roles
Section titled "Seed 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.
node ace make:seeder roleimport { 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)
}
}
node ace db:seedA user can hold several roles. Their permissions are the union of the permissions of every role they hold.
Register abilities with Bouncer
Section titled "Register abilities with Bouncer"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.
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.
Authorize in a controller
Section titled "Authorize in a controller"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.
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.