@@ -14,6 +14,7 @@ The RBAC system provides fine-grained access control through roles and permissio
1414## Default Roles
1515
1616### Global Administrator (` global_admin ` )
17+
1718- ** Description** : Full system access with user management capabilities
1819- ** Permissions** :
1920 - ` users.list ` - List all users
@@ -25,6 +26,7 @@ The RBAC system provides fine-grained access control through roles and permissio
2526 - ` system.admin ` - Administrative system access
2627
2728### Global User (` global_user ` )
29+
2830- ** Description** : Standard user with basic profile access
2931- ** Permissions** :
3032 - ` profile.view ` - View own profile
@@ -33,6 +35,7 @@ The RBAC system provides fine-grained access control through roles and permissio
3335## Database Schema
3436
3537### Roles Table
38+
3639``` sql
3740CREATE TABLE roles (
3841 id TEXT PRIMARY KEY , -- Role identifier (e.g., 'global_admin')
@@ -46,7 +49,9 @@ CREATE TABLE roles (
4649```
4750
4851### User Role Assignment
52+
4953The ` authUser ` table includes a ` role_id ` column that references the ` roles ` table:
54+
5055``` sql
5156ALTER TABLE authUser ADD COLUMN role_id TEXT DEFAULT ' global_user' REFERENCES roles(id);
5257```
@@ -56,12 +61,14 @@ ALTER TABLE authUser ADD COLUMN role_id TEXT DEFAULT 'global_user' REFERENCES ro
5661### Role Management
5762
5863#### List Roles
64+
5965``` http
6066GET /api/roles
6167Authorization: Required (roles.manage permission)
6268```
6369
6470** Response:**
71+
6572``` json
6673{
6774 "success" : true ,
@@ -80,12 +87,14 @@ Authorization: Required (roles.manage permission)
8087```
8188
8289#### Get Role by ID
90+
8391``` http
8492GET /api/roles/:id
8593Authorization: Required (roles.manage permission)
8694```
8795
8896#### Create Role
97+
8998``` http
9099POST /api/roles
91100Authorization: Required (roles.manage permission)
@@ -100,6 +109,7 @@ Content-Type: application/json
100109```
101110
102111#### Update Role
112+
103113``` http
104114PUT /api/roles/:id
105115Authorization: Required (roles.manage permission)
@@ -115,16 +125,19 @@ Content-Type: application/json
115125** Note:** System roles (` is_system_role: true ` ) cannot be updated or deleted.
116126
117127#### Delete Role
128+
118129``` http
119130DELETE /api/roles/:id
120131Authorization: Required (roles.manage permission)
121132```
122133
123134** Restrictions:**
135+
124136- Cannot delete system roles
125137- Cannot delete roles that are assigned to users
126138
127139#### Get Available Permissions
140+
128141``` http
129142GET /api/roles/permissions
130143Authorization: Required (roles.manage permission)
@@ -133,18 +146,21 @@ Authorization: Required (roles.manage permission)
133146### User Management
134147
135148#### List Users
149+
136150``` http
137151GET /api/users
138152Authorization: Required (users.list permission)
139153```
140154
141155#### Get User by ID
156+
142157``` http
143158GET /api/users/:id
144159Authorization: Required (own profile or system.admin permission)
145160```
146161
147162#### Update User
163+
148164``` http
149165PUT /api/users/:id
150166Authorization: Required (own profile or system.admin permission)
@@ -160,20 +176,24 @@ Content-Type: application/json
160176```
161177
162178** Restrictions:**
179+
163180- Users cannot change their own role (only admins can)
164181- Email and username must be unique
165182
166183#### Delete User
184+
167185``` http
168186DELETE /api/users/:id
169187Authorization: Required (users.delete permission)
170188```
171189
172190** Restrictions:**
191+
173192- Cannot delete your own account
174193- Cannot delete the last global administrator
175194
176195#### Assign Role to User
196+
177197``` http
178198PUT /api/users/:id/role
179199Authorization: Required (users.edit permission)
@@ -185,21 +205,25 @@ Content-Type: application/json
185205```
186206
187207** Restrictions:**
208+
188209- Cannot change your own role
189210
190211#### Get Current User Profile
212+
191213``` http
192214GET /api/users/me
193215Authorization: Required (authenticated user)
194216```
195217
196218#### Get User Statistics
219+
197220``` http
198221GET /api/users/stats
199222Authorization: Required (users.list permission)
200223```
201224
202225#### Get Users by Role
226+
203227``` http
204228GET /api/users/role/:roleId
205229Authorization: Required (users.list permission)
@@ -226,6 +250,7 @@ Authorization: Required (users.list permission)
226250The system provides several ways to check permissions:
227251
228252#### Middleware Functions
253+
229254``` typescript
230255import { requirePermission , requireRole , requireGlobalAdmin } from ' ../middleware/roleMiddleware' ;
231256
@@ -246,6 +271,7 @@ fastify.get('/global-admin', {
246271```
247272
248273#### Utility Functions
274+
249275``` typescript
250276import { checkUserPermission , getUserRole } from ' ../middleware/roleMiddleware' ;
251277
@@ -259,14 +285,18 @@ const userRole = await getUserRole(userId);
259285## User Registration Flow
260286
261287### First User
288+
262289When the first user registers in the system:
290+
2632911 . They are automatically assigned the ` global_admin ` role
2642922 . This ensures there's always at least one administrator
265293
266294### Subsequent Users
295+
267296All subsequent users are assigned the ` global_user ` role by default.
268297
269298### Registration Code Example
299+
270300``` typescript
271301// Check if this is the first user
272302const allUsers = await db .select ().from (authUserTable ).limit (1 );
@@ -283,24 +313,28 @@ await db.insert(authUserTable).values({
283313## Security Considerations
284314
285315### Role Protection
316+
286317- ** System Roles** : Cannot be modified or deleted
287318- ** Last Admin Protection** : Cannot delete the last global administrator
288319- ** Self-Role Protection** : Users cannot change their own roles
289320- ** Self-Delete Protection** : Users cannot delete their own accounts
290321
291322### Permission Validation
323+
292324- All permissions are validated against a whitelist
293325- Invalid permissions are rejected during role creation/update
294326- Database constraints ensure referential integrity
295327
296328### Session Security
329+
297330- Role information is fetched fresh for each permission check
298331- No role caching to prevent stale permission issues
299332- Lucia v3 handles secure session management
300333
301334## Adding New Roles
302335
303336### 1. Define Permissions
337+
304338First, add any new permissions to the available permissions list:
305339
306340``` typescript
@@ -314,6 +348,7 @@ export const AVAILABLE_PERMISSIONS = [
314348```
315349
316350### 2. Create Role via API
351+
317352Use the role creation API to add new roles:
318353
319354``` http
@@ -327,6 +362,7 @@ POST /api/roles
327362```
328363
329364### 3. Update Default Permissions (Optional)
365+
330366If you want to include the role in default setups:
331367
332368``` typescript
@@ -343,6 +379,7 @@ static getDefaultPermissions() {
343379## Migration and Setup
344380
345381### Database Migration
382+
346383The role system is set up through migration ` 0003_huge_prism.sql ` (generated using ` npm run db:generate ` ):
347384
3483851 . Creates the ` roles ` table
@@ -352,6 +389,7 @@ The role system is set up through migration `0003_huge_prism.sql` (generated usi
3523895 . Promotes the first user to ` global_admin `
353390
354391### Manual Setup
392+
355393If you need to manually set up roles:
356394
357395``` sql
@@ -370,16 +408,19 @@ UPDATE authUser SET role_id = 'global_admin' WHERE id = (SELECT id FROM authUser
370408### Common Issues
371409
372410#### Permission Denied Errors
411+
373412- Verify the user has the required permission
374413- Check if the user's role includes the necessary permission
375414- Ensure the role exists and is properly assigned
376415
377416#### Role Assignment Failures
417+
378418- Verify the target role exists
379419- Check if you're trying to assign a role to yourself (not allowed)
380420- Ensure you have ` users.edit ` permission
381421
382422#### Migration Issues
423+
383424- Ensure the database is properly initialized
384425- Check that previous migrations have been applied
385426- Verify foreign key constraints are working
@@ -403,13 +444,15 @@ console.log('All roles:', allRoles);
403444## Future Enhancements
404445
405446### Planned Features
447+
406448- ** Hierarchical Roles** : Parent-child role relationships
407449- ** Temporary Permissions** : Time-limited access grants
408450- ** Permission Groups** : Logical grouping of related permissions
409451- ** Audit Logging** : Track role and permission changes
410452- ** Role Templates** : Predefined role configurations
411453
412454### Extension Points
455+
413456The system is designed to be extensible:
414457
415458- Add new permissions by updating the ` AVAILABLE_PERMISSIONS ` array
@@ -420,23 +463,27 @@ The system is designed to be extensible:
420463## Best Practices
421464
422465### Role Design
466+
423467- Keep roles focused and specific
424468- Use descriptive names and descriptions
425469- Group related permissions logically
426470- Avoid overly broad permissions
427471
428472### Permission Naming
473+
429474- Use dot notation for hierarchy (` users.edit ` , ` content.moderate ` )
430475- Be specific about the action (` view ` , ` edit ` , ` delete ` , ` create ` )
431476- Use consistent naming patterns
432477
433478### Security
479+
434480- Always check permissions at the API level
435481- Don't rely solely on frontend permission checks
436482- Regularly audit role assignments
437483- Monitor for privilege escalation attempts
438484
439485### Performance
486+
440487- Permission checks are lightweight but avoid excessive calls
441488- Consider caching user roles for high-frequency operations
442489- Use middleware for route-level protection
0 commit comments