Roles and Permissions

How to implement fully-featured role-based access control

Tensei auth ships with a fully-featured Role-based access control system. The first step is to add new roles and permissions to your application. You may do this using the role and permission methods from the auth package:

import { tensei } from '@tensei/core'
import { auth, role, permission } from '@tensei/auth'

export default tensei()
                        permission('Write Articles'),
                        permission('Read Articles'),
                        permission('Delete Articles'),

That's all you need. Now, you can use these roles and permissions to authorize your application resource or custom routes and graphql queries:

import { tensei, resource, route } from '@tensei/core'

export default tensei()
        route('Get analytics')
            .authorize(({ authUser }) => authUser?.hasRole('Writer'))
            .handle((request, response) => [])
            .canCreate(({ authUser }) => authUser?.hasPermission('Write Articles'))

User methods

The User model has a bunch of helpful methods you can use to handle access control in your application:

// Check if user has a role
authUser.hasRole('Remove Page')

// Check if user has a permission
authUser.hasPermission('Delete Product')

// Grant a role to a user
await authUser.assignRole('Marketer')

// Revoke a role from a user
await authUser.removeRole('removeRole')

// Get all the permissions for a user

// Get all the roles fro a user