@ooneex/role 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +479 -0
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1 +1,480 @@
1
1
  # @ooneex/role
2
+
3
+ A comprehensive role-based access control (RBAC) library for TypeScript applications with hierarchical role support. This package provides predefined roles, role hierarchy management, and utilities for checking user permissions based on role levels.
4
+
5
+ ![Browser](https://img.shields.io/badge/Browser-Compatible-green?style=flat-square&logo=googlechrome)
6
+ ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
7
+ ![Deno](https://img.shields.io/badge/Deno-Compatible-blue?style=flat-square&logo=deno)
8
+ ![Node.js](https://img.shields.io/badge/Node.js-Compatible-green?style=flat-square&logo=node.js)
9
+ ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)
10
+ ![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)
11
+
12
+ ## Features
13
+
14
+ ✅ **40+ Predefined Roles** - Comprehensive set of roles from Guest to System
15
+
16
+ ✅ **Role Hierarchy** - Hierarchical role system with inheritance
17
+
18
+ ✅ **Level-Based Access** - Check permissions based on role levels
19
+
20
+ ✅ **Type-Safe** - Full TypeScript support with proper type definitions
21
+
22
+ ✅ **Zero Dependencies** - Lightweight with no external runtime dependencies
23
+
24
+ ✅ **Domain-Specific Roles** - Specialized roles for different business domains
25
+
26
+ ✅ **Framework Integration** - Works seamlessly with Ooneex routing and controllers
27
+
28
+ ## Installation
29
+
30
+ ### Bun
31
+ ```bash
32
+ bun add @ooneex/role
33
+ ```
34
+
35
+ ### pnpm
36
+ ```bash
37
+ pnpm add @ooneex/role
38
+ ```
39
+
40
+ ### Yarn
41
+ ```bash
42
+ yarn add @ooneex/role
43
+ ```
44
+
45
+ ### npm
46
+ ```bash
47
+ npm install @ooneex/role
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ### Basic Role Checking
53
+
54
+ ```typescript
55
+ import { Role, ERole } from '@ooneex/role';
56
+
57
+ const role = new Role();
58
+
59
+ // Check if user has required role level
60
+ const userRole = ERole.MANAGER;
61
+ const requiredRole = ERole.USER;
62
+
63
+ if (role.hasRole(userRole, requiredRole)) {
64
+ console.log('Access granted');
65
+ } else {
66
+ console.log('Access denied');
67
+ }
68
+ ```
69
+
70
+ ### Getting Role Level
71
+
72
+ ```typescript
73
+ import { Role, ERole } from '@ooneex/role';
74
+
75
+ const role = new Role();
76
+
77
+ // Get numeric level for a role
78
+ const adminLevel = role.getRoleLevel(ERole.ADMIN);
79
+ const userLevel = role.getRoleLevel(ERole.USER);
80
+
81
+ console.log(`Admin level: ${adminLevel}`); // Higher number
82
+ console.log(`User level: ${userLevel}`); // Lower number
83
+
84
+ // Admin has higher level, so they have more access
85
+ ```
86
+
87
+ ### Getting Inherited Roles
88
+
89
+ ```typescript
90
+ import { Role, ERole } from '@ooneex/role';
91
+
92
+ const role = new Role();
93
+
94
+ // Get all roles a user inherits from their role
95
+ const managerRoles = role.getInheritedRoles(ERole.MANAGER);
96
+
97
+ console.log(managerRoles);
98
+ // Includes: BANNED, SUSPENDED, GUEST, TRIAL_USER, USER, MEMBER,
99
+ // SUBSCRIBER, PREMIUM_USER, VIP_USER, CONTRIBUTOR, AUTHOR, etc.
100
+ // up to and including MANAGER
101
+ ```
102
+
103
+ ### Route Protection
104
+
105
+ ```typescript
106
+ import { Route } from '@ooneex/routing';
107
+ import { ERole } from '@ooneex/role';
108
+ import type { IController, ContextType } from '@ooneex/controller';
109
+
110
+ @Route.http({
111
+ name: 'admin.users.list',
112
+ path: '/admin/users',
113
+ method: 'GET',
114
+ description: 'List all users (admin only)',
115
+ roles: [ERole.ADMIN, ERole.SUPER_ADMIN]
116
+ })
117
+ class AdminUserListController implements IController {
118
+ public async index(context: ContextType): Promise<IResponse> {
119
+ // Only accessible to ADMIN and SUPER_ADMIN roles
120
+ return context.response.json({
121
+ users: await this.userService.findAll()
122
+ });
123
+ }
124
+ }
125
+ ```
126
+
127
+ ### Multiple Role Requirements
128
+
129
+ ```typescript
130
+ import { Route } from '@ooneex/routing';
131
+ import { ERole } from '@ooneex/role';
132
+
133
+ @Route.http({
134
+ name: 'api.content.publish',
135
+ path: '/api/content/:id/publish',
136
+ method: 'POST',
137
+ description: 'Publish content',
138
+ roles: [ERole.EDITOR, ERole.CONTENT_MANAGER, ERole.ADMIN]
139
+ })
140
+ class ContentPublishController implements IController {
141
+ public async index(context: ContextType): Promise<IResponse> {
142
+ // Accessible to EDITOR, CONTENT_MANAGER, or ADMIN
143
+ const { id } = context.params;
144
+ await this.contentService.publish(id);
145
+
146
+ return context.response.json({ published: true });
147
+ }
148
+ }
149
+ ```
150
+
151
+ ## API Reference
152
+
153
+ ### Classes
154
+
155
+ #### `Role`
156
+
157
+ Main class for role-based access control operations.
158
+
159
+ **Constructor:**
160
+ ```typescript
161
+ new Role()
162
+ ```
163
+
164
+ **Methods:**
165
+
166
+ ##### `getRoleLevel(role: ERole): number`
167
+
168
+ Gets the numeric level of a role in the hierarchy.
169
+
170
+ **Parameters:**
171
+ - `role` - The role to get the level for
172
+
173
+ **Returns:** Numeric level (higher = more permissions)
174
+
175
+ **Example:**
176
+ ```typescript
177
+ const role = new Role();
178
+ const level = role.getRoleLevel(ERole.ADMIN);
179
+ console.log(level); // High number indicating admin privileges
180
+ ```
181
+
182
+ ##### `hasRole(userRole: ERole, requiredRole: ERole): boolean`
183
+
184
+ Checks if a user's role meets or exceeds the required role level.
185
+
186
+ **Parameters:**
187
+ - `userRole` - The user's current role
188
+ - `requiredRole` - The minimum required role
189
+
190
+ **Returns:** `true` if user has sufficient role level
191
+
192
+ **Example:**
193
+ ```typescript
194
+ const role = new Role();
195
+
196
+ role.hasRole(ERole.ADMIN, ERole.USER); // true - admin > user
197
+ role.hasRole(ERole.USER, ERole.ADMIN); // false - user < admin
198
+ role.hasRole(ERole.MANAGER, ERole.MANAGER); // true - equal roles
199
+ ```
200
+
201
+ ##### `getInheritedRoles(role: ERole): ERole[]`
202
+
203
+ Gets all roles that a user inherits from their role level.
204
+
205
+ **Parameters:**
206
+ - `role` - The user's role
207
+
208
+ **Returns:** Array of all inherited roles (from lowest to the given role)
209
+
210
+ **Example:**
211
+ ```typescript
212
+ const role = new Role();
213
+ const inherited = role.getInheritedRoles(ERole.EDITOR);
214
+ // Returns all roles from BANNED up to EDITOR
215
+ ```
216
+
217
+ ### Enums
218
+
219
+ #### `ERole`
220
+
221
+ Comprehensive enum of all available roles.
222
+
223
+ **User Levels:**
224
+ | Role | Value | Description |
225
+ |------|-------|-------------|
226
+ | `GUEST` | `ROLE_GUEST` | Unauthenticated visitor |
227
+ | `TRIAL_USER` | `ROLE_TRIAL_USER` | User on trial period |
228
+ | `USER` | `ROLE_USER` | Basic authenticated user |
229
+ | `MEMBER` | `ROLE_MEMBER` | Registered member |
230
+ | `SUBSCRIBER` | `ROLE_SUBSCRIBER` | Subscribed user |
231
+ | `PREMIUM_USER` | `ROLE_PREMIUM_USER` | Premium tier user |
232
+ | `VIP_USER` | `ROLE_VIP_USER` | VIP tier user |
233
+
234
+ **Content Roles:**
235
+ | Role | Value | Description |
236
+ |------|-------|-------------|
237
+ | `CONTRIBUTOR` | `ROLE_CONTRIBUTOR` | Can contribute content |
238
+ | `AUTHOR` | `ROLE_AUTHOR` | Can author content |
239
+ | `REVIEWER` | `ROLE_REVIEWER` | Can review content |
240
+ | `EDITOR` | `ROLE_EDITOR` | Can edit content |
241
+ | `CURATOR` | `ROLE_CURATOR` | Can curate content |
242
+
243
+ **Technical Roles:**
244
+ | Role | Value | Description |
245
+ |------|-------|-------------|
246
+ | `DEVELOPER` | `ROLE_DEVELOPER` | Software developer |
247
+ | `DESIGNER` | `ROLE_DESIGNER` | UI/UX designer |
248
+ | `TESTER` | `ROLE_TESTER` | QA tester |
249
+ | `TECHNICAL_LEAD` | `ROLE_TECHNICAL_LEAD` | Technical team lead |
250
+ | `DEVOPS` | `ROLE_DEVOPS` | DevOps engineer |
251
+
252
+ **Support & Analysis:**
253
+ | Role | Value | Description |
254
+ |------|-------|-------------|
255
+ | `SUPPORT_AGENT` | `ROLE_SUPPORT_AGENT` | Customer support |
256
+ | `ANALYST` | `ROLE_ANALYST` | Data analyst |
257
+ | `MODERATOR` | `ROLE_MODERATOR` | Content moderator |
258
+
259
+ **Management:**
260
+ | Role | Value | Description |
261
+ |------|-------|-------------|
262
+ | `SUPERVISOR` | `ROLE_SUPERVISOR` | Team supervisor |
263
+ | `TEAM_LEAD` | `ROLE_TEAM_LEAD` | Team leader |
264
+ | `MANAGER` | `ROLE_MANAGER` | Department manager |
265
+ | `DEPARTMENT_HEAD` | `ROLE_DEPARTMENT_HEAD` | Department head |
266
+ | `DIRECTOR` | `ROLE_DIRECTOR` | Company director |
267
+ | `OWNER` | `ROLE_OWNER` | Business owner |
268
+
269
+ **Domain Managers:**
270
+ | Role | Value | Description |
271
+ |------|-------|-------------|
272
+ | `CONTENT_MANAGER` | `ROLE_CONTENT_MANAGER` | Content management |
273
+ | `MARKETING_MANAGER` | `ROLE_MARKETING_MANAGER` | Marketing department |
274
+ | `SALES_MANAGER` | `ROLE_SALES_MANAGER` | Sales department |
275
+ | `PRODUCT_MANAGER` | `ROLE_PRODUCT_MANAGER` | Product management |
276
+ | `HR_MANAGER` | `ROLE_HR_MANAGER` | Human resources |
277
+ | `FINANCE_MANAGER` | `ROLE_FINANCE_MANAGER` | Finance department |
278
+
279
+ **Governance:**
280
+ | Role | Value | Description |
281
+ |------|-------|-------------|
282
+ | `COMPLIANCE_OFFICER` | `ROLE_COMPLIANCE_OFFICER` | Compliance oversight |
283
+ | `SECURITY_OFFICER` | `ROLE_SECURITY_OFFICER` | Security oversight |
284
+ | `AUDITOR` | `ROLE_AUDITOR` | System auditor |
285
+
286
+ **Administrative:**
287
+ | Role | Value | Description |
288
+ |------|-------|-------------|
289
+ | `ADMIN` | `ROLE_ADMIN` | Administrator |
290
+ | `SUPER_ADMIN` | `ROLE_SUPER_ADMIN` | Super administrator |
291
+ | `SYSTEM` | `ROLE_SYSTEM` | System-level access |
292
+
293
+ **Restricted:**
294
+ | Role | Value | Description |
295
+ |------|-------|-------------|
296
+ | `SUSPENDED` | `ROLE_SUSPENDED` | Temporarily suspended |
297
+ | `BANNED` | `ROLE_BANNED` | Permanently banned |
298
+
299
+ ### Constants
300
+
301
+ #### `ROLE_HIERARCHY`
302
+
303
+ Array defining the order of roles from lowest to highest privilege.
304
+
305
+ ```typescript
306
+ import { ROLE_HIERARCHY } from '@ooneex/role';
307
+
308
+ // Ordered from BANNED (lowest) to SYSTEM (highest)
309
+ console.log(ROLE_HIERARCHY);
310
+ ```
311
+
312
+ ### Types
313
+
314
+ #### `RoleType`
315
+
316
+ String literal type representing role values.
317
+
318
+ ```typescript
319
+ type RoleType = `${ERole}`;
320
+ // "ROLE_GUEST" | "ROLE_USER" | "ROLE_ADMIN" | ...
321
+ ```
322
+
323
+ #### `IRole`
324
+
325
+ Interface for role service implementations.
326
+
327
+ ```typescript
328
+ interface IRole {
329
+ getRoleLevel: (role: ERole) => number;
330
+ hasRole: (userRole: ERole, requiredRole: ERole) => boolean;
331
+ getInheritedRoles: (role: ERole) => ERole[];
332
+ }
333
+ ```
334
+
335
+ #### `RoleClassType`
336
+
337
+ Type for role class constructors.
338
+
339
+ ```typescript
340
+ type RoleClassType = new (...args: any[]) => IRole;
341
+ ```
342
+
343
+ ## Advanced Usage
344
+
345
+ ### Custom Role Checking Service
346
+
347
+ ```typescript
348
+ import { Role, ERole, type IRole } from '@ooneex/role';
349
+ import { container } from '@ooneex/container';
350
+
351
+ class CustomRoleService extends Role {
352
+ public canAccessResource(userRole: ERole, resourceType: string): boolean {
353
+ const roleLevel = this.getRoleLevel(userRole);
354
+
355
+ switch (resourceType) {
356
+ case 'public':
357
+ return roleLevel >= this.getRoleLevel(ERole.GUEST);
358
+ case 'members-only':
359
+ return roleLevel >= this.getRoleLevel(ERole.MEMBER);
360
+ case 'premium':
361
+ return roleLevel >= this.getRoleLevel(ERole.PREMIUM_USER);
362
+ case 'admin':
363
+ return roleLevel >= this.getRoleLevel(ERole.ADMIN);
364
+ default:
365
+ return false;
366
+ }
367
+ }
368
+ }
369
+
370
+ container.add(CustomRoleService);
371
+ ```
372
+
373
+ ### Role-Based UI Rendering
374
+
375
+ ```typescript
376
+ import { Role, ERole } from '@ooneex/role';
377
+
378
+ const role = new Role();
379
+ const userRole = ERole.EDITOR;
380
+
381
+ const menuItems = [
382
+ { label: 'Dashboard', minRole: ERole.USER },
383
+ { label: 'Content', minRole: ERole.CONTRIBUTOR },
384
+ { label: 'Analytics', minRole: ERole.ANALYST },
385
+ { label: 'Users', minRole: ERole.ADMIN },
386
+ { label: 'Settings', minRole: ERole.SUPER_ADMIN },
387
+ ];
388
+
389
+ const visibleItems = menuItems.filter(item =>
390
+ role.hasRole(userRole, item.minRole)
391
+ );
392
+
393
+ console.log(visibleItems);
394
+ // Shows Dashboard, Content (user is EDITOR)
395
+ ```
396
+
397
+ ### Middleware with Role Validation
398
+
399
+ ```typescript
400
+ import { decorator } from '@ooneex/middleware';
401
+ import { Role, ERole } from '@ooneex/role';
402
+ import type { IMiddleware, ContextType } from '@ooneex/middleware';
403
+
404
+ @decorator.middleware()
405
+ class RoleMiddleware implements IMiddleware {
406
+ private readonly roleService = new Role();
407
+
408
+ public async handle(context: ContextType): Promise<ContextType> {
409
+ const user = context.user;
410
+
411
+ if (!user) {
412
+ context.response.exception('Unauthorized', { status: 401 });
413
+ return context;
414
+ }
415
+
416
+ // Check if user is not banned or suspended
417
+ if (user.role === ERole.BANNED || user.role === ERole.SUSPENDED) {
418
+ context.response.exception('Account restricted', { status: 403 });
419
+ return context;
420
+ }
421
+
422
+ return context;
423
+ }
424
+ }
425
+ ```
426
+
427
+ ### Role Upgrade Logic
428
+
429
+ ```typescript
430
+ import { Role, ERole } from '@ooneex/role';
431
+
432
+ class SubscriptionService {
433
+ private readonly role = new Role();
434
+
435
+ public getRoleForPlan(plan: string): ERole {
436
+ switch (plan) {
437
+ case 'free':
438
+ return ERole.USER;
439
+ case 'basic':
440
+ return ERole.MEMBER;
441
+ case 'premium':
442
+ return ERole.PREMIUM_USER;
443
+ case 'vip':
444
+ return ERole.VIP_USER;
445
+ default:
446
+ return ERole.GUEST;
447
+ }
448
+ }
449
+
450
+ public isUpgrade(currentRole: ERole, newRole: ERole): boolean {
451
+ return this.role.getRoleLevel(newRole) > this.role.getRoleLevel(currentRole);
452
+ }
453
+ }
454
+ ```
455
+
456
+ ## License
457
+
458
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
459
+
460
+ ## Contributing
461
+
462
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
463
+
464
+ ### Development Setup
465
+
466
+ 1. Clone the repository
467
+ 2. Install dependencies: `bun install`
468
+ 3. Run tests: `bun run test`
469
+ 4. Build the project: `bun run build`
470
+
471
+ ### Guidelines
472
+
473
+ - Write tests for new features
474
+ - Follow the existing code style
475
+ - Update documentation for API changes
476
+ - Ensure all tests pass before submitting PR
477
+
478
+ ---
479
+
480
+ Made with ❤️ by the Ooneex team
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ooneex/role",
3
3
  "description": "Role type definitions and utilities for user authorization and access control",
4
- "version": "0.0.2",
4
+ "version": "0.0.3",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",