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:
- Registers the provider and the Ace commands in
adonisrc.ts. - Creates
config/permissions.ts. - Scaffolds
app/models/role.tsandapp/models/permission.ts. - Creates the five migrations.
- Registers the
role,permissionandroleOrPermissionnamed middlewares instart/kernel.ts.
Flags
Every prompt can be answered up front:
node ace configure @eienjs/adonisjs-permission --teams --wildcard --migrations --models --middlewares
| Flag | Description |
|---|---|
--defaults | Skip all prompts and use the defaults. |
--teams | Enable teams / multi-tenancy columns. |
--wildcard | Enable wildcard permissions. |
--models | Scaffold the Role and Permission models. |
--migrations | Create the migration files. |
--middlewares | Register the named middlewares. |
Run the migrations
node ace migration:run
The following tables are created:
| Table | Purpose |
|---|---|
roles | Roles (name, guard_name, optional team_id). |
permissions | Permissions (name, guard_name). |
role_has_permissions | Role ↔ permission pivot. |
model_has_roles | Polymorphic model ↔ role pivot. |
model_has_permissions | Polymorphic 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
}
import { compose } from '@adonisjs/core/helpers'
import { BaseModel, column } from '@adonisjs/lucid/orm'
import { Permissible } from '@eienjs/adonisjs-permission'
export default class Permission extends compose(BaseModel, Permissible) {
@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.
