@nestdevx/role
v1.0.1
Published
Role and permission module for multi-tenant NestJS applications.
Maintainers
Readme
@nestdevx/role
Role and permission module for multi-tenant NestJS applications. Provides role-based access control (RBAC), permission management, and event-driven automation for new tenants.
Features
- Multi-tenant role and permission management (MongoDB/Mongoose)
- Role and permission entities, DTOs, and services
- CQRS event handlers for tenant onboarding
- Dynamic role/permission assignment and querying
- Integration with @nestdevx/user and @nestdevx/auth
Installation
npm install @nestdevx/role
# or
yarn add @nestdevx/role
# or
pnpm add @nestdevx/roleUsage
1. Import the Module
import { RoleModule } from '@nestdevx/role';
@Module({
imports: [RoleModule.register()], // Use .register() for dynamic providers
})
export class AppModule {}2. Use the RoleService & PermissionService
import { RoleService, PermissionService } from '@nestdevx/role';
@Injectable()
export class SomeService {
constructor(
private readonly roleService: RoleService,
private readonly permissionService: PermissionService,
) {}
async addPermissions(roleId: string, tenantId: string, permissions: string[]) {
await this.roleService.addPermissionsToRole(roleId, tenantId, permissions);
}
async createPermission(tenantId: string, name: string) {
await this.permissionService.createPermissionForNewlyCreatedTenant(tenantId, name);
}
}3. Entities & DTOs
RoleEntityandPermissionEntityare Mongoose schemas with multi-tenant support.- Use
RoleDtoandNewRoleDtofor API and validation.
4. Event Handlers
CreateTenantAdminRoleEventHandlerautomatically creates base permissions and a super-admin role for new tenants, and assigns them to the admin user.GetRoleQueryHandlersupports CQRS queries for role details.
5. Decorators and Guards (Coming soon)
- Use
@Roles('admin')decorator on controllers/routes - Use
RolesGuardto protect endpoints
API Reference
RoleModule.register()– Register the module with dynamic providersRoleService.addPermissionsToRole(roleId, tenantId, permissions)– Add permissions to a rolePermissionService.createPermissionForNewlyCreatedTenant(tenantId, name)– Create a permission for a tenantRoleService.create(dto)– Create a new roleRoleService.assignRole(userId, role)– Assign role to user
Example: Create Tenant Admin Role (Event Driven)
// When a new tenant is onboarded, the event handler will:
// 1. Create all base permissions for the tenant
// 2. Create a 'super-admin' role
// 3. Assign all permissions to the role
// 4. Assign the role to the tenant's admin user
// This is handled automatically by CreateTenantAdminRoleEventHandlerLicense
MIT
