Authentication & Authorization Flow
Relevant source files
The following files were used as context for generating this wiki page:
- apps/api/src/auth/totp.ts
- apps/api/src/auth/password.ts
- apps/api/src/modules/auth/service.ts
- apps/api/src/auth/tokens.ts
- apps/api/src/modules/auth/routes.ts
- packages/db/prisma/migrations/20261006190616_staff_invites/migration.sql
- apps/web/app/invite/invite-flow.tsx
- apps/web/app/api/session/session.test.ts
The Authentication and Authorization system manages secure access to the Digital Health Care platform for both staff members and patients. It employs distinct workflows for different user roles: staff members use a two-step password and Time-based One-Time Password (TOTP) process, while patients authenticate via mobile One-Time Password (OTP) challenges.
This system provides multi-tenant isolation using Postgres Row-Level Security (RLS), ensuring that users only access data within their assigned organization. All security-sensitive actions, including login attempts and session creation, are recorded in an audit log for compliance and monitoring.
Sources: README.md, apps/api/src/modules/auth/service.ts:1-20
Staff Authentication Workflow
Staff authentication is a multi-step process requiring both a verified password and a valid TOTP code from an authenticator app.
Step 1: Password Verification
The user provides their organization slug, identifier (email or mobile), and password. The system verifies the password using scrypt hashing. If valid, the system issues a short-lived mfaToken (valid for 5 minutes) rather than a full session.
Step 2: MFA Verification
The user submits the mfaToken along with a 6-digit code from their authenticator app. The AuthService validates the code against the stored mfaSecret. Upon success, the system creates a new session and returns a Bearer token pair.
The diagram shows the two-step sequence for staff login, transitioning from a password check to MFA verification before granting a session.
Sources: apps/api/src/modules/auth/service.ts:133-219, apps/api/src/auth/tokens.ts:60-70
Patient Authentication Workflow
Patients authenticate using a mobile-based OTP system. This flow does not require passwords but relies on possession of the registered mobile device.
- Request OTP: The patient submits their mobile number and organization slug. The system generates a 6-digit code and sends it via the
otpSender. - Verify OTP: The patient submits the
challengeIdand the received code. The system verifies the code, creates or retrieves the user record, and establishes an active membership in the organization.
This flowchart illustrates the lifecycle of a patient OTP challenge, from initial request to session creation.
Sources: apps/api/src/modules/auth/service.ts:40-129, apps/api/src/auth/phone.ts
Session and Token Management
The platform uses JWT-based access tokens and opaque, database-backed refresh tokens.
Token Types and Lifetimes
| Token Type | Purpose | Lifetime | Storage |
|---|---|---|---|
| Access Token | Authorize API requests | 15 Minutes | Memory / Bearer Header |
| Refresh Token | Obtain new access tokens | Staff: 12 Hours / Patient: 30 Days | HttpOnly Cookie (dhc_session) |
| MFA Token | Intermediate proof of password | 5 Minutes | Transient |
Sources: apps/api/src/auth/tokens.ts:13-17, apps/api/src/modules/auth/service.ts:15-18, apps/web/app/api/session/session.test.ts:38-46
Token Rotation and Security
The system implements Refresh Token Rotation. Every time a refresh token is used to obtain a new access token, the old refresh token is revoked, and a new one is issued. If a revoked refresh token is replayed, the system detects a potential breach, revokes the entire session, and logs a auth.refresh.reuse_detected audit event.
Sources: apps/api/src/modules/auth/service.ts:223-281, apps/api/src/auth/tokens.ts:100-108
Staff Invite and Setup Flow
Staff accounts cannot be created via public registration. They are initiated through admin-generated invite links.
- Creation: A Clinic Admin generates an invite for a specific email/mobile and role.
- Inspection: The invitee opens the link (carrying a token hash). The web app calls
POST /auth/invites/inspectto show organization details. - Acceptance: The invitee sets a password.
- Completion: The invitee scans a QR code for TOTP and submits the first valid code. This marks the invite as
acceptedand the membership asactive.
The flow shows the transition of a staff member from an invited state to an active, authenticated user.
Sources: apps/web/app/invite/invite-flow.tsx:40-135, packages/db/prisma/migrations/20261006190616_staff_invites/migration.sql:35-42
Authorization and Isolation
Authorization is enforced at both the API and database levels.
Role-Based Access Control (RBAC)
Roles are embedded in the Access Token JWT claims. The authenticate plugin verifies the JWT and populates the request context with userId, organisationId, and role.
- Roles:
patient,doctor,front_desk,clinic_admin. - Enforcement: Specific routes use
preHandler: authenticateand check the user's role before processing.
Sources: apps/api/src/auth/tokens.ts:5-11, apps/api/src/modules/auth/routes.ts:58-65
Tenant Isolation (RLS)
The database uses Postgres Row-Level Security. Every session in the database is associated with a specific organisation_id.
- dhc_app role: Used for standard application queries, restricted by
app_current_organisation_id(). - dhc_auth role: Used during the sign-in phase to look up users and verify invites before a full tenant context is established.
Sources: packages/db/prisma/migrations/20261006190616_staff_invites/migration.sql:26-42, README.md
Summary
The Authentication & Authorization Flow provides a secure, multi-tenant environment. Staff members are protected by mandatory MFA and admin-controlled onboarding. Patients benefit from a frictionless OTP-based entry. Both workflows culminate in a secure session management system featuring token rotation and granular audit logging.