adonis-rbac
Install
adonis install adonis-rbac --yarn
Setup
-
Add provider in
/start/app.js
const providers =//...'adonis-rbac/providers/RbacProvider' -
Add trait in
/app/Models/User.js
static {return'@provider:Rbac/Traits/Rbac'}//...or if you need to customize the field name...static {superthis}
Usage
-
Define
roles
in/config/rbac.js
/**** Configurations for adonis-rbac** Permission format: <resource>.<operation>* e.g: posts.index, posts.update, posts.delete** tip: define roles sorting by permissions asc.*/moduleexports =roles:// <roleName>: [...<permissions>]user: 'posts.index' 'posts.show'// use `role:<roleName>` to grant all permissions for <roleName>editor: 'role:user' 'posts.create' 'posts.update'// use `posts.*` to allow all operations for postsadmin: 'role:editor' 'posts.*'// use `*` to grant all permissionssystem: '*' -
Set
roles
on useruserroles = 'admin'/* or string split by comma*/userroles = 'admin,editor' -
Use
.can()
in middleware or controller actions.const HttpException =if !authuserthrow 'Forbidden.' 403