Quick start
This page walks through the whole flow with the in-memory adapter, so you can run it without a database. Swap MemoryAdapter for the Prisma or Drizzle adapter when you are ready.
1. Create the engine
import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
const rbac = createRbac({ adapter: new MemoryAdapter() })2. Define permissions and roles
Permissions describe actions. Roles are named groups of permissions.
await rbac.createPermission('edit articles')
await rbac.createPermission('delete articles')
await rbac.createPermission('publish articles')
await rbac.createRole('writer')
await rbac.createRole('editor')3. Give permissions to roles
rbac.role(name) returns a helper for a single role:
await rbac.role('writer').givePermissionTo('edit articles')
await rbac.role('editor').givePermissionTo('edit articles', 'delete articles', 'publish articles')4. Assign roles to a user
Anything with a type and an id can hold roles. rbac.for(subject) returns a helper scoped to that subject:
const user = rbac.for({ type: 'user', id: 1 })
await user.assignRole('writer')5. Check access
await user.hasRole('writer') // true
await user.hasRole('editor') // false
await user.can('edit articles') // true (through the writer role)
await user.can('delete articles') // false
await user.cannot('publish articles') // truecan() never throws. If you ask about a permission that does not exist, it returns false.
You can also give a permission to the user directly, without a role:
await user.givePermissionTo('publish articles')
await user.can('publish articles') // true6. Use it in your app
A typical server-side check in a route handler:
export async function deleteArticle(currentUser: { id: number }, articleId: number) {
if (await rbac.for({ type: 'user', id: currentUser.id }).cannot('delete articles')) {
throw new Error('Forbidden')
}
// ...delete the article
}To send the user's access to the browser (for React or Vue), use snapshot():
await user.snapshot()
// { roles: ['writer'], permissions: ['publish articles', 'edit articles'] }WARNING
Checks in the browser are for the UI only. Always check permissions on the server too.
Next steps
- Basic usage: subjects, finding and deleting roles and permissions
- Permissions via roles and direct permissions
- Super-admin, teams and wildcards
- Framework guides: Next.js, React, Vue, Express
- Storage: adapters overview
