|
| 1 | +# Basic Usage |
| 2 | + |
| 3 | +This section shows how to configure RBAC, model permissions, and integrate the library into common application layers. |
| 4 | + |
| 5 | +## Configure RBAC |
| 6 | + |
| 7 | +Create an instance by passing configuration and a role map. Configuration accepts a custom logger and a `enableLogger` flag to turn logging on or off. |
| 8 | + |
| 9 | +```ts |
| 10 | +import RBAC from '@rbac/rbac'; |
| 11 | + |
| 12 | +const rbac = RBAC({ enableLogger: true })({ |
| 13 | + guest: { can: ['products:find'] } |
| 14 | +}); |
| 15 | +``` |
| 16 | + |
| 17 | +## Define roles and permissions |
| 18 | + |
| 19 | +A role definition accepts: |
| 20 | + |
| 21 | +- `can`: An array of strings or objects with a `name` and optional `when` guard. Strings match directly, and patterns can use glob wildcards or regular expressions. |
| 22 | +- `inherits`: An optional array of roles to pull permissions from. |
| 23 | + |
| 24 | +```ts |
| 25 | +const rbac = RBAC()({ |
| 26 | + user: { can: ['products:find'] }, |
| 27 | + supervisor: { |
| 28 | + can: [ |
| 29 | + { name: 'products:edit', when: () => true }, |
| 30 | + { name: 'products:*' } // wildcard |
| 31 | + ], |
| 32 | + inherits: ['user'] |
| 33 | + } |
| 34 | +}); |
| 35 | +``` |
| 36 | + |
| 37 | +`when` guards can be synchronous, async, a returned Promise, or a callback. They receive the `params` object passed to `can`. |
| 38 | + |
| 39 | +```ts |
| 40 | +const rbac = RBAC()({ |
| 41 | + auditor: { |
| 42 | + can: [ |
| 43 | + { name: 'products:audit:callback', when: (_params, done) => done(null, true) }, |
| 44 | + { name: 'products:audit:async', when: async () => true }, |
| 45 | + { name: 'products:audit:promise', when: Promise.resolve(true) } |
| 46 | + ] |
| 47 | + } |
| 48 | +}); |
| 49 | +``` |
| 50 | + |
| 51 | +## Check permissions |
| 52 | + |
| 53 | +The `can` helper resolves inheritance, matches exact operations, globs, or regexes, and evaluates conditional guards when present: |
| 54 | + |
| 55 | +```ts |
| 56 | +await rbac.can('supervisor', 'products:find'); |
| 57 | +await rbac.can('supervisor', 'products:create'); |
| 58 | +await rbac.can('auditor', /products:audit/); |
| 59 | +await rbac.can('auditor', 'products:audit:async', { requestId: '42' }); |
| 60 | +``` |
| 61 | + |
| 62 | +## Update roles at runtime |
| 63 | + |
| 64 | +Add or merge role definitions without rebuilding your application: |
| 65 | + |
| 66 | +```ts |
| 67 | +rbac.addRole('editor', { can: ['products:update'], inherits: ['user'] }); |
| 68 | +rbac.updateRoles({ |
| 69 | + user: { can: ['products:find', 'products:share'] } |
| 70 | +}); |
| 71 | +``` |
| 72 | + |
| 73 | +## Persist and load roles with adapters |
| 74 | + |
| 75 | +Use the optional adapters to store roles in your database. Each adapter supports a customizable table/collection schema and an optional `tenantId` for multi-tenancy. |
| 76 | + |
| 77 | +```ts |
| 78 | +import { MongoRoleAdapter, MySQLRoleAdapter, PostgresRoleAdapter } from '@rbac/rbac/adapters'; |
| 79 | + |
| 80 | +const mongoAdapter = new MongoRoleAdapter({ |
| 81 | + uri: 'mongodb://localhost:27017', |
| 82 | + dbName: 'mydb', |
| 83 | + collection: 'roles' |
| 84 | +}); |
| 85 | + |
| 86 | +const mysqlAdapter = new MySQLRoleAdapter({ |
| 87 | + uri: 'mysql://user:pass@localhost:3306/app', |
| 88 | + table: 'roles' |
| 89 | +}); |
| 90 | + |
| 91 | +const pgAdapter = new PostgresRoleAdapter({ |
| 92 | + connectionString: 'postgres://user:pass@localhost:5432/app', |
| 93 | + table: 'roles' |
| 94 | +}); |
| 95 | +``` |
| 96 | + |
| 97 | +Adapters expose `getRoles`, `addRole`, and `updateRoles` to manage definitions in storage. |
| 98 | + |
| 99 | +## Multi-tenant RBAC |
| 100 | + |
| 101 | +Scope RBAC to a specific tenant by loading role definitions with a `tenantId`: |
| 102 | + |
| 103 | +```ts |
| 104 | +import { createTenantRBAC, MongoRoleAdapter } from '@rbac/rbac'; |
| 105 | + |
| 106 | +const adapter = new MongoRoleAdapter({ |
| 107 | + uri: 'mongodb://localhost:27017', |
| 108 | + dbName: 'mydb', |
| 109 | + collection: 'roles' |
| 110 | +}); |
| 111 | + |
| 112 | +const rbacTenantA = await createTenantRBAC(adapter, 'tenant-a'); |
| 113 | +await rbacTenantA.can('user', 'products:find'); |
| 114 | +``` |
| 115 | + |
| 116 | +## Web framework middleware |
| 117 | + |
| 118 | +Guard routes using the built-in middleware factories for Express, NestJS, and Fastify. Each factory accepts optional callbacks to extract the role and params or to override the default denied response. |
| 119 | + |
| 120 | +```ts |
| 121 | +import RBAC, { createExpressMiddleware } from '@rbac/rbac'; |
| 122 | + |
| 123 | +const rbac = RBAC({ enableLogger: false })({ |
| 124 | + user: { can: ['products:find'] } |
| 125 | +}); |
| 126 | + |
| 127 | +const canFindProducts = createExpressMiddleware(rbac)('products:find'); |
| 128 | +app.get('/products', canFindProducts, handler); |
| 129 | +``` |
| 130 | + |
| 131 | +Swap `createExpressMiddleware` for `createNestMiddleware` or `createFastifyMiddleware` to integrate with other frameworks. |
0 commit comments