Roles & Permissions (RBAC)
IRolesPermissionsStore provides role-based access control with optional tenant scoping.
Interface
import { IRolesPermissionsStore } from '@nik2208/node-auth';
export class MyRbacStore implements IRolesPermissionsStore {
async addRoleToUser(userId: string, role: string, tenantId?: string): Promise<void> { /* ... */ }
async removeRoleFromUser(userId: string, role: string, tenantId?: string): Promise<void> { /* ... */ }
async getRolesForUser(userId: string, tenantId?: string): Promise<string[]> { /* ... */ }
async createRole(role: string, permissions?: string[]): Promise<void> { /* ... */ }
async deleteRole(role: string): Promise<void> { /* ... */ }
async addPermissionToRole(role: string, permission: string): Promise<void> { /* ... */ }
async removePermissionFromRole(role: string, permission: string): Promise<void> { /* ... */ }
async getPermissionsForRole(role: string): Promise<string[]> { /* ... */ }
async getPermissionsForUser(userId: string, tenantId?: string): Promise<string[]> { /* ... */ }
async userHasPermission(userId: string, permission: string, tenantId?: string): Promise<boolean> { /* ... */ }
}
Usage
// Setup
await rbac.createRole('editor', ['posts:read', 'posts:write']);
await rbac.addRoleToUser(userId, 'editor', 'tenant-acme');
// Protect a route
app.delete('/posts/:id', auth.middleware(), async (req, res) => {
const allowed = await rbac.userHasPermission(req.user!.sub, 'posts:write');
if (!allowed) return res.status(403).json({ error: 'Forbidden' });
// ... delete post
});
Embed in JWT
buildTokenPayload: async (user) => ({
roles: await rbac.getRolesForUser(user.id),
permissions: await rbac.getPermissionsForUser(user.id),
}),
Pass rbacStore to auth.router() to include roles/permissions in GET /auth/me.