Getting Started

Installation

Install and configure the package with a single Ace command.

Install

node ace add @eienjs/adonisjs-permission

This installs the package and runs node ace configure @eienjs/adonisjs-permission, which:

  1. Registers the provider and the Ace commands in adonisrc.ts.
  2. Creates config/permissions.ts.
  3. Scaffolds app/models/role.ts and app/models/permission.ts.
  4. Creates the five migrations.
  5. Registers the role, permission and roleOrPermission named middlewares in start/kernel.ts.

Flags

Every prompt can be answered up front:

node ace configure @eienjs/adonisjs-permission --teams --wildcard --migrations --models --middlewares
FlagDescription
--defaultsSkip all prompts and use the defaults.
--teamsEnable teams / multi-tenancy columns.
--wildcardEnable wildcard permissions.
--modelsScaffold the Role and Permission models.
--migrationsCreate the migration files.
--middlewaresRegister the named middlewares.

Run the migrations

node ace migration:run

The following tables are created:

TablePurpose
rolesRoles (name, guard_name, optional team_id).
permissionsPermissions (name, guard_name).
role_has_permissionsRole ↔ permission pivot.
model_has_rolesPolymorphic model ↔ role pivot.
model_has_permissionsPolymorphic model ↔ permission pivot.

Prepare your User model

app/models/user.ts
import { compose } from '@adonisjs/core/helpers'
import { BaseModel } from '@adonisjs/lucid/orm'
import { HasAuthorizable } from '@eienjs/adonisjs-permission'

export default class User extends compose(BaseModel, HasAuthorizable) {
  // your columns...
}

HasAuthorizable bundles HasRoles and HasPermissions plus helpers such as can() and hasPermissionTo(). You can apply any other model (a Company, Team, ...) the same way.

Use HasRoles or HasPermissions on their own if a model only needs one of them.

Role and Permission models

The scaffolded models use the Roleable and Permissible mixins:

import { compose } from '@adonisjs/core/helpers'
import { BaseModel, column } from '@adonisjs/lucid/orm'
import { Roleable } from '@eienjs/adonisjs-permission'

export default class Role extends compose(BaseModel, Roleable) {
  @column({ isPrimary: true })
  declare id: number | string
}

The mixins already provide name, guardName and teamId columns. Since the models are yours, you can add any extra column or relation.