The IAM module is the central authentication, authorization, and identity management system for the TelemetryFlow SaaS platform. It implements a comprehensive multi-tenant identity management solution following Domain-Driven Design (DDD) and CQRS principles.
Business Purpose: Manages users, organizations, tenants, workspaces, roles, permissions, and groups in a hierarchical multi-tenant architecture. Provides fine-grained access control with support for RBAC (Role-Based Access Control) and direct permission assignment.
Location: /backend/src/modules/iam
iam/
├── domain/ # Core business logic
│ ├── aggregates/ # User, Role, Permission, Tenant, Organization, Workspace, Group, Region
│ ├── entities/ # MFASettings, UserProfile
│ ├── value-objects/ # UserId, Email, RoleId, TenantId, OrganizationId, etc.
│ ├── events/ # Domain events (UserCreated, RoleAssigned, etc.)
│ ├── repositories/ # Repository interfaces
│ └── services/ # Domain services (PermissionService)
├── application/ # Use cases
│ ├── commands/ # Write operations (33 commands)
│ ├── queries/ # Read operations (18 queries)
│ ├── handlers/ # Command/Query handlers with tests
│ ├── dto/ # Application DTOs
│ └── services/ # Application services
├── infrastructure/ # Technical implementation
│ ├── persistence/ # TypeORM repositories, entities, migrations, seeds
│ ├── messaging/ # IAMEventProcessor for domain events
│ └── processors/ # Background processors
└── presentation/ # API layer
├── controllers/ # REST controllers (12 controllers)
├── dto/ # Request/Response DTOs
├── decorators/ # Custom decorators
└── guards/ # Authorization guards
graph TB
subgraph Presentation Layer
A[User Controller] --> B[Role Controller]
B --> C[Tenant Controller]
C --> D[Organization Controller]
D --> E[Workspace Controller]
E --> F[Permission Controller]
F --> G[Group Controller]
G --> H[Region Controller]
H --> I[AuditLog Controller]
end
subgraph Application Layer
J[Command Handlers] --> K[Query Handlers]
K --> L[IAMEventProcessor]
end
subgraph Domain Layer
M[User Aggregate] --> N[Role Aggregate]
N --> O[Permission Aggregate]
O --> P[Tenant Aggregate]
P --> Q[Organization Aggregate]
Q --> R[Workspace Aggregate]
R --> S[Group Aggregate]
S --> T[Region Aggregate]
end
A --> J
J --> M
K --> M
L --> U[Message Bus]
The central user entity with authentication and profile information.
Key Properties:
id: UserId- Unique identifieremail: Email- Value object ensuring valid emailpasswordHash: string- Hashed passwordfirstName, lastName: string- User profilemfaEnabled: boolean- Multi-factor authentication statusmfaSecret: string | null- MFA secret keyforcePasswordChange: boolean- Password reset flagtenantId, organizationId: string | null- Multi-tenant hierarchyisActive: boolean- Account statusemailVerified: boolean- Email verification status
Domain Methods:
static create(email: Email, passwordHash: string, firstName: string, lastName: string, ...): User
changePassword(newPasswordHash: string): void
enableMFA(secret: string): void
disableMFA(): void
activate(): void
deactivate(): void
verifyEmail(): void
requirePasswordChange(): voidDomain Events Raised:
UserCreatedEvent- When user is created
Represents a role that can be assigned to users with associated permissions.
Key Responsibilities:
- Groups permissions for easier management
- Can be assigned to multiple users
- Hierarchical permission model
Associated Events:
RoleCreatedEventRoleUpdatedEventRoleAssignedEventRoleRevokedEvent
Granular access control permissions.
Key Features:
- Resource-based permissions (e.g.,
alerts:read,dashboards:write) - Can be assigned directly to users or through roles
- Supports permission inheritance
Associated Events:
PermissionCreatedEventPermissionUpdatedEventPermissionAssignedEvent(to Role)PermissionRemovedEvent(from Role)PermissionDirectlyAssignedEvent(to User)PermissionDirectlyRevokedEvent(from User)
Top-level isolation boundary for multi-tenancy.
Purpose: Provides complete data isolation between different customer organizations.
Associated Events:
TenantCreatedEventTenantUpdatedEventTenantDeletedEvent
Sub-division within a tenant.
Purpose: Allows tenants to organize users into departments or teams.
Associated Events:
OrganizationCreatedEventOrganizationUpdatedEventOrganizationDeletedEvent
Project or environment-level isolation.
Purpose: Provides workspace-based data segmentation within organizations.
Associated Events:
WorkspaceCreatedEventWorkspaceUpdatedEventWorkspaceDeletedEvent
Collection of users for simplified management.
Purpose: Enables batch permission and role assignments.
Associated Events:
GroupCreatedEventGroupUpdatedEventUserAddedToGroupEventUserRemovedFromGroupEvent
Geographic or logical region for data residency.
Purpose: Supports multi-region deployments and compliance requirements.
Associated Events:
RegionCreatedEventRegionUpdatedEvent
Multi-factor authentication configuration entity (part of User aggregate).
Extended user profile information entity.
All value objects ensure immutability and validation:
| Value Object | Purpose | Validation |
|---|---|---|
UserId |
Type-safe user identifier | UUID format |
Email |
Email address | RFC 5322 email validation |
RoleId |
Role identifier | UUID format |
PermissionId |
Permission identifier | UUID format |
TenantId |
Tenant identifier | UUID format |
OrganizationId |
Organization identifier | UUID format |
WorkspaceId |
Workspace identifier | UUID format |
GroupId |
Group identifier | UUID format |
RegionId |
Region identifier | UUID format |
UserRole |
User role enum | Predefined roles |
Handles complex permission calculation logic:
- Computes effective permissions from roles and direct assignments
- Resolves permission hierarchies
- Evaluates access control decisions
Located in: application/commands/
CreateUserCommand- Create new userUpdateUserCommand- Update user profileDeleteUserCommand- Soft delete userActivateUserCommand- Activate user accountChangePasswordCommand- Change user passwordAssignRoleToUserCommand- Assign role to userRevokeRoleFromUserCommand- Remove role from userAssignPermissionToUserCommand- Directly assign permissionRevokePermissionFromUserCommand- Remove direct permission
CreateRoleCommand- Create new roleUpdateRoleCommand- Update role detailsDeleteRoleCommand- Delete roleAssignPermissionCommand- Assign permission to roleRemovePermissionCommand- Remove permission from role
CreatePermissionCommand- Create new permissionUpdatePermissionCommand- Update permissionDeletePermissionCommand- Delete permission
CreateTenantCommand- Create new tenantUpdateTenantCommand- Update tenantDeleteTenantCommand- Delete tenant
CreateOrganizationCommand- Create organizationUpdateOrganizationCommand- Update organizationDeleteOrganizationCommand- Delete organization
CreateWorkspaceCommand- Create workspaceUpdateWorkspaceCommand- Update workspaceDeleteWorkspaceCommand- Delete workspace
CreateGroupCommand- Create groupUpdateGroupCommand- Update groupDeleteGroupCommand- Delete groupAddUserToGroupCommand- Add user to groupRemoveUserFromGroupCommand- Remove user from group
CreateRegionCommand- Create regionUpdateRegionCommand- Update regionDeleteRegionCommand- Delete region
Total Commands: 33
Located in: application/queries/
GetUserQuery- Get user by IDListUsersQuery- List users with filtersGetUserRolesQuery- Get all roles for a userGetUserPermissionsQuery- Get effective permissions for user
GetRoleQuery- Get role by IDListRolesQuery- List all rolesGetRoleUsersQuery- Get users with a specific role
GetPermissionQuery- Get permission by IDListPermissionsQuery- List all permissions
GetTenantQuery- Get tenant by IDListTenantsQuery- List all tenants
GetOrganizationQuery- Get organization by IDListOrganizationsQuery- List organizations
GetWorkspaceQuery- Get workspace by IDListWorkspacesQuery- List workspaces
GetGroupQuery- Get group by IDListGroupsQuery- List groups
GetRegionQuery- Get region by IDListRegionsQuery- List regions
Total Queries: 18
Located in: application/handlers/
Currently registered event handlers are minimal. Domain events are primarily processed by:
IAMEventProcessor(infrastructure/messaging/IAMEventProcessor.ts)
This processor publishes IAM events to the message bus for consumption by other modules (Audit, Notifications, etc.).
All repositories follow the interface-implementation pattern:
Interfaces (in domain/repositories/):
IUserRepositoryIRoleRepositoryIPermissionRepositoryITenantRepositoryIOrganizationRepositoryIWorkspaceRepositoryIGroupRepositoryIRegionRepositoryIUserRoleRepository(junction table)IUserPermissionRepository(junction table)
Implementations (in infrastructure/persistence/):
UserRepository- TypeORM-based user persistence- Similar implementations for other aggregates
Located in: infrastructure/persistence/entities/
TypeORM entities:
UserEntity- Maps User aggregate to databaseRoleEntity- Maps Role aggregateTenantEntity- Maps Tenant aggregate- Additional entities for other aggregates
Located in: infrastructure/persistence/migrations/
Database schema migrations managed by TypeORM CLI.
Located in: infrastructure/persistence/seeds/
Initial data seeding for:
- Default roles (Admin, User, Viewer)
- System permissions
- Default tenant
Processes domain events and publishes them to the messaging system:
- Listens for all IAM domain events
- Transforms domain events to integration events
- Publishes to message bus (RabbitMQ/Redis)
- Enables event-driven communication with other modules
| Method | Endpoint | Description | Handler |
|---|---|---|---|
| POST | /api/v2/users |
Create user | CreateUserCommand |
| GET | /api/v2/users |
List users (filtered by email, org) | ListUsersQuery |
| GET | /api/v2/users/:id |
Get user by ID | GetUserQuery |
| PUT | /api/v2/users/:id |
Update user | UpdateUserCommand |
| DELETE | /api/v2/users/:id |
Delete user | DeleteUserCommand |
| POST | /api/v2/users/:id/activate |
Activate user | ActivateUserCommand |
| POST | /api/v2/users/:id/deactivate |
Deactivate user | (To be implemented) |
| PUT | /api/v2/users/:id/password |
Change password | ChangePasswordCommand |
| POST | /api/v2/users/:id/roles |
Assign role | AssignRoleToUserCommand |
| DELETE | /api/v2/users/:id/roles/:roleId |
Revoke role | RevokeRoleFromUserCommand |
| GET | /api/v2/users/:id/roles |
Get user roles | GetUserRolesQuery |
| POST | /api/v2/users/:id/permissions |
Assign permission | AssignPermissionToUserCommand |
| DELETE | /api/v2/users/:id/permissions/:permissionId |
Revoke permission | RevokePermissionFromUserCommand |
| GET | /api/v2/users/:id/permissions |
Get user permissions | GetUserPermissionsQuery |
- CRUD operations for roles
- Assign/remove permissions to roles
- Get users for a role
- CRUD operations for permissions
- List all available permissions
- CRUD operations for tenants
- Multi-tenant isolation management
- CRUD operations for organizations
- Organization hierarchy management
- CRUD operations for workspaces
- Workspace-level data isolation
- CRUD operations for groups
- Add/remove users to groups
- CRUD operations for regions
- Multi-region management
- Query audit logs for IAM operations
- Compliance and security monitoring
UserCreatedEvent- New user createdUserAddedToGroupEvent- User added to groupUserRemovedFromGroupEvent- User removed from group
RoleCreatedEvent- New role createdRoleUpdatedEvent- Role modifiedRoleAssignedEvent- Role assigned to userRoleRevokedEvent- Role removed from user
PermissionCreatedEvent- New permission createdPermissionUpdatedEvent- Permission modifiedPermissionAssignedEvent- Permission added to rolePermissionRemovedEvent- Permission removed from rolePermissionDirectlyAssignedEvent- Permission directly assigned to userPermissionDirectlyRevokedEvent- Permission directly revoked from user
TenantCreatedEvent- New tenant createdTenantUpdatedEvent- Tenant updatedTenantDeletedEvent- Tenant deleted
OrganizationCreatedEvent- Organization createdOrganizationUpdatedEvent- Organization updatedOrganizationDeletedEvent- Organization deleted
WorkspaceCreatedEvent- Workspace createdWorkspaceUpdatedEvent- Workspace updatedWorkspaceDeletedEvent- Workspace deleted
GroupCreatedEvent- Group createdGroupUpdatedEvent- Group updated
RegionCreatedEvent- Region createdRegionUpdatedEvent- Region updated
Total Domain Events: 28
QueueModule- Background job processingMessagingModule- Event bus and message publishingAuditModule(indirect) - Audit log consumers listen to IAM eventsNotificationModule(indirect) - Notification triggers based on IAM events
{
"@nestjs/common": "^10.x",
"@nestjs/cqrs": "^10.x",
"@nestjs/typeorm": "^10.x",
"typeorm": "^0.3.x",
"bcrypt": "^5.x",
"class-validator": "^0.14.x",
"class-transformer": "^0.5.x",
"uuid": "^9.x"
}- Domain aggregate tests:
domain/aggregates/*.spec.ts - Handler tests:
application/handlers/__tests__/*.spec.ts - Controller tests:
presentation/controllers/*.spec.ts
- End-to-end controller tests:
presentation/controllers/*.e2e.spec.ts
# Run all IAM module tests
npm test -- iam
# Run specific test file
npm test -- User.spec.ts
# Run with coverage
npm test -- --coverage iam# Database
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=telemetryflow
DB_PASSWORD=secure_password
DB_DATABASE=telemetryflow_iam
# JWT Configuration
JWT_SECRET=your_jwt_secret
JWT_EXPIRES_IN=1h
JWT_REFRESH_EXPIRES_IN=7d
# MFA Configuration
MFA_ISSUER=TelemetryFlow
MFA_WINDOW=2
# Password Policy
PASSWORD_MIN_LENGTH=8
PASSWORD_REQUIRE_UPPERCASE=true
PASSWORD_REQUIRE_LOWERCASE=true
PASSWORD_REQUIRE_NUMBERS=true
PASSWORD_REQUIRE_SPECIAL=true
# Session
SESSION_TIMEOUT=30m
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=15m// Command
const command = new CreateUserCommand(
'john.doe@example.com',
'SecurePassword123!',
'John',
'Doe'
);
const userId = await commandBus.execute(command);// Command
const command = new AssignRoleToUserCommand(
userId,
roleId
);
await commandBus.execute(command);// Query
const query = new GetUserPermissionsQuery(userId);
const permissions = await queryBus.execute(query);
// Returns: ['alerts:read', 'alerts:write', 'dashboards:read', ...]// Create tenant-scoped user
const command = new CreateUserCommand(
'jane@acme.com',
'Password456!',
'Jane',
'Smith',
tenantId, // Tenant isolation
organizationId // Organization within tenant
);
const userId = await commandBus.execute(command);The IAM module has been fully migrated to DDD architecture. Legacy endpoints have been deprecated.
Old Endpoint → New Endpoint:
POST /api/auth/register→POST /api/v2/usersGET /api/users/:id→GET /api/v2/users/:idPUT /api/users/:id/role→POST /api/v2/users/:id/roles
See: /docs-saas-ddd/05-API-V2-MIGRATION-GUIDE.md
-
Password Security:
- Passwords are hashed using bcrypt
- Force password change on first login
- Password strength validation
-
MFA Support:
- TOTP-based multi-factor authentication
- Integration with MFA module
-
Audit Logging:
- All IAM operations are audited
- Events published for audit trail
-
Role-Based Access Control:
- Fine-grained permissions
- Role hierarchy support
- Direct permission assignment
-
Multi-Tenant Isolation:
- Tenant-level data isolation
- Organization-level segmentation
- Workspace-level boundaries
- ✅ Aggregates with proper boundaries
- ✅ Value Objects for type safety
- ✅ Domain Events
- ✅ Repository pattern
- ✅ Domain Services
- ✅ Ubiquitous Language
- ✅ Separate Commands and Queries
- ✅ Command Handlers
- ✅ Query Handlers
- ✅ Event-driven architecture
- ✅ Dependency Inversion (domain → application → infrastructure)
- ✅ Infrastructure isolated from domain
- ✅ Framework independence in domain layer
- OAuth2/OIDC Support: Integration with external identity providers
- Federated Identity: Support for identity federation
- Advanced RBAC: Attribute-Based Access Control (ABAC)
- Audit Event Sourcing: Full event sourcing for audit trail
- Password Policy Engine: Configurable password policies
- Session Management: Advanced session controls and revocation
When contributing to the IAM module:
- Follow DDD principles
- Write unit tests for domain logic
- Document domain events
- Update this README with new features
- Ensure CQRS separation is maintained
- Domain-Driven Design:
/docs-saas-ddd/02-DDD-COMPLIANCE-REPORT.md - API Migration:
/docs-saas-ddd/05-API-V2-MIGRATION-GUIDE.md - Module Assessment:
/docs-saas-ddd/01-MODULE-ASSESSMENT.md - Architecture Docs:
/backend/src/modules/iam/docs/
Module Status: ✅ Fully DDD-compliant Test Coverage: ~75% (aggregates, handlers, controllers) API Version: v2 Last Updated: 2025-11-11