Skip to main content

Authentication Module

The Authentication module provides comprehensive authentication and authorization functionality for the Comdeall platform. It implements frontend-driven authentication with backend token validation, multiple OAuth strategies, OTP-based verification, and role-based access control to ensure secure access to child development and therapy management resources.

Table of Contents

  1. Module Structure
  2. Authentication Endpoints
  3. Authentication Strategies
  4. Authorization Features
  5. Authentication Flows
  6. Integration Points
  7. Technical Implementation
  8. Security Considerations
  9. Error Handling
  10. Conclusion

Module Structure

The Authentication module follows a streamlined architecture focused on token validation and user management:

@Module({
imports: [JwtModule.register({}), BackgroundModule, DBModule],
controllers: [AuthController],
providers: [AuthService, CustomJwtService, { provide: APP_GUARD, useClass: AuthGuard }],
})
export class AuthModule {}

Core Components:

  1. Controller Layer (auth.controller.ts): Handles OAuth token verification, OTP flows, admin authentication, and token management

  2. Service Layer (auth.service.ts): Implements OAuth provider verification, OTP logic, user registration, and background job integration

  3. Guards (guards/auth.guard.ts): Validates JWT tokens and implements role-based route protection

  4. Custom JWT Service: Generates Hasura-compatible tokens and manages verification

  5. Database Layer: Coordinates database operations for users, OTP, and device tokens

Authentication Endpoints

EndpointMethodDescriptionAuth Type
/auth/googlePOSTVerify Google OAuth token from frontendNone
/auth/facebookPOSTVerify Facebook OAuth token from frontendNone
/auth/applePOSTVerify Apple OAuth token from frontendNone
/auth/signin/email/adminPOSTAdmin email/password authenticationNone
/auth/signup/email/adminPOSTCreate admin accountNone
/auth/signout/adminPOSTAdmin logoutJWT
/auth/signout/userPOSTUser logout with device cleanupJWT
/auth/access-token-renewalPOSTRefresh access tokenRefresh
/auth/save-device-tokenPOSTRegister device for notificationsJWT
/auth/send-otpPOSTSend OTP for verificationNone
/auth/verify-otpPOSTVerify OTP and authenticate userNone
/auth/signupPOSTRegister new parent or therapistNone

Authentication Strategies

JWT Authentication

The primary authentication mechanism uses JWT tokens generated by the frontend and validated by the backend. The AuthGuard extracts Bearer tokens, verifies signatures, and populates user context from Hasura claims.

Key Features:

  • Frontend handles initial authentication and token creation
  • Backend validates token signature and extracts user context
  • Hasura-compatible claims for GraphQL access
  • User role and associated IDs embedded in token claims
  • Automatic user context attachment to request object

JWT Payload Structure:

  • email: User's email address
  • https://hasura.io/jwt/claims: Contains role, user ID, therapist ID, and parent ID
  • Role-based access control information
  • Device and session tracking data

Usage in Controllers:

@Auth(AuthType.JWT)   // Require JWT authentication
@Auth(AuthType.NONE) // Public endpoint
@Auth(AuthType.REFRESH) // Require refresh token

Refresh Token

The module implements refresh tokens for maintaining user sessions without frequent re-authentication. Refresh tokens have longer expiration times (7 days vs 15 minutes for access tokens) and use separate secret keys for enhanced security.

Refresh Flow:

  1. Client sends refresh token in Authorization header
  2. System validates token signature and expiration
  3. System verifies user still exists and is not deleted
  4. System generates new access token with updated user information
  5. System returns new access token for continued authentication

Security Features:

  • Separate secret key from access tokens
  • Database validation ensures user account status
  • Automatic cleanup of expired refresh tokens

OAuth Social Authentication

The module supports verification of OAuth tokens generated by frontend social authentication for Google, Facebook, and Apple providers.

Authentication Flow:

  1. Frontend handles OAuth flow with provider
  2. Frontend receives access token and user profile
  3. Frontend sends token and profile to backend for verification
  4. Backend verifies token validity with respective OAuth provider
  5. Backend creates or updates user account based on verified profile
  6. Backend generates JWT tokens for application access

Social Login Processing:

  • New users return registration required response
  • Existing users complete login flow with token generation
  • Device token registration for push notifications
  • User profile updates from social provider data

OTP-Based Authentication

For users preferring email/phone verification, the module implements OTP-based authentication with comprehensive rate limiting and security features.

OTP Features:

  • Rate limiting: Maximum 5 attempts per hour per identifier
  • Time-based expiry: OTP valid for 15 minutes
  • Test account support: Fixed OTP '000111' for test users
  • Background job integration: Asynchronous email/SMS delivery
  • Count reset logic: Automatic reset after 60 minutes

OTP Verification Process:

  • Validates OTP exists and matches submitted value
  • Checks expiration against 15-minute time limit
  • Processes user registration or login based on existing account status
  • Generates JWT tokens for authenticated sessions

Authorization Features

Role-Based Access Control

The module implements role-based access control through user roles embedded in JWT tokens:

export enum UserRole {
ADMIN = "ADMIN",
PARENT = "PARENT",
THERAPIST = "THERAPIST",
GUEST = "GUEST",
}

Authorization Logic:

  • User role extracted from JWT token during authentication
  • Role information validated against route requirements
  • Multiple roles can be specified for flexible access control
  • Role hierarchy can be implemented for cascading permissions

Hasura Claims Integration

The module generates Hasura-compatible JWT claims for seamless GraphQL integration:

Hasura Claims Structure:

  • x-hasura-default-role: User's primary role
  • x-hasura-allowed-roles: Array of permitted roles
  • x-hasura-user-id: Unique user identifier
  • x-hasura-therapist-id: Therapist ID or 'NA'
  • x-hasura-parent-id: Parent ID or 'NA'

Integration Benefits:

  • Direct GraphQL access without additional backend calls
  • Row-level security with automatic query filtering
  • Role-based schema access control
  • Database-level permission enforcement

Authentication Flows

OTP Registration & Verification

The OTP-based registration flow handles both parents and therapists with role-specific processing:

Registration Process:

  1. User provides email/phone and basic information
  2. System sends OTP for verification with rate limiting
  3. User verifies OTP and provides additional role-specific details
  4. System creates appropriate user type (Parent or Therapist)
  5. System generates JWT tokens and queues welcome notifications

Therapist Registration Specifics:

  • Unique therapist code generation using phone country code and sequence
  • Training credential validation and media file linking
  • Professional license and degree verification
  • Specialized onboarding flow for healthcare professionals

OAuth Social Login

Social login flow handles token verification and user account management:

OAuth Processing:

  1. Frontend completes OAuth flow with provider
  2. Frontend sends access token and user data to backend
  3. Backend verifies token with OAuth provider APIs
  4. Backend creates/updates user account with social profile data
  5. Backend generates application JWT tokens
  6. Backend registers device for push notifications

Admin Authentication

Admin authentication uses traditional email/password authentication with enhanced security:

Admin Features:

  • Argon2 password hashing with custom salt for secure storage
  • Single admin policy: Only one admin account allowed per system
  • Enhanced security validation with additional verification steps
  • Separate admin endpoints with specialized authentication logic

Token Refresh

Token refresh maintains user sessions without re-authentication:

Token Refresh Process:

  1. Validates refresh token exists in database
  2. Verifies token signature and expiration
  3. Extracts user payload from Hasura claims
  4. Generates new access token with updated information
  5. Returns new token for continued application access

Integration Points

Frontend Authentication

The module is designed to work with frontend-driven authentication:

Frontend Responsibilities:

  • Handle OAuth flows with social providers
  • Generate and manage initial authentication tokens
  • Send tokens to backend for verification and user management
  • Handle token refresh and secure storage

Backend Responsibilities:

  • Verify OAuth tokens with respective providers
  • Validate user accounts and generate application-specific tokens
  • Manage user sessions and device registration
  • Provide secure API access through token validation

Background Jobs

Authentication integrates with the background job system for notifications and maintenance:

Background Job Integration:

  • Email notifications: OTP delivery, welcome messages, password resets
  • Push notifications: User engagement, inactivity reminders, policy updates
  • Scheduled tasks: Token cleanup, device management, audit log rotation
  • User lifecycle events: Registration confirmations, account status changes

Device Management

The module tracks user devices for security and notification purposes:

Device Management Features:

  • Device registration for push notification targeting
  • Duplicate prevention to avoid multiple registrations
  • Logout cleanup to remove device tokens on sign-out
  • Security monitoring to track device usage patterns

Security Benefits:

  • Suspicious activity detection across multiple devices
  • Individual session termination capability
  • Administrative forced logout functionality
  • Automatic session expiration for inactive devices

Technical Implementation

Guards and Decorators

The authentication system uses a clean decorator-based approach:

// Auth decorator and user extraction
export const Auth = (type: AuthType = AuthType.JWT) => SetMetadata(AUTH_TYPE_KEY, type);

export const User = createParamDecorator((data: keyof UserInfo, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return data ? request.user?.[data] : request.user;
});

Usage Examples:

  • Public endpoints: @Auth(AuthType.NONE)
  • JWT required: @Auth(AuthType.JWT)
  • User extraction: @User() user: UserInfo or @User('email') email: string

Custom JWT Service

The custom JWT service handles token generation and verification with Hasura compatibility:

Core Methods:

  • generateAccessToken: Creates JWT access tokens with Hasura claims
  • generateRefreshToken: Creates refresh tokens with extended expiry
  • verifyAccessToken: Validates token signatures and expiration
  • verifyRefreshToken: Validates refresh token authenticity

Security Features:

  • Different secret keys for different token types
  • Configurable expiration times per token type
  • Token type embedded in payload for validation
  • Hasura-compatible claim structure for GraphQL integration

Database Layer

The authentication module uses a layered database approach:

Database Architecture:

  • Service Layer: Coordinates database operations and business logic
  • Repository Layer: Handles direct database interactions using Prisma
  • Model Layer: Prisma schema definitions for type safety
  • Migration Layer: Database schema evolution and versioning

Security Considerations

Token Security

The module implements multiple layers of token security:

Security Configuration:

  • Separate key pairs for access and refresh tokens
  • Short token expiry (15-minute access tokens) to minimize exposure risk
  • Algorithm specification with explicit HMAC SHA-256 requirement
  • Token type validation to prevent confusion attacks

Rate Limiting

OTP and authentication endpoints implement comprehensive rate limiting:

Rate Limiting Features:

  • OTP limits: Maximum 5 OTP requests per hour per identifier
  • Progressive lockouts with increasing delays for repeated failures
  • Time-based reset with automatic count reset after 60 minutes
  • Test account exemption for development and testing

Device Tracking

The module tracks devices for security monitoring and session management:

Device Tracking Benefits:

  • Session management across multiple user devices
  • Suspicious activity detection through usage pattern analysis
  • Remote logout capability for individual device sessions
  • Automatic session expiration for inactive devices

Error Handling

The module implements comprehensive error handling with specific error codes:

Error Categories:

  • Authentication errors: Invalid credentials, expired tokens, email mismatches
  • Authorization errors: Insufficient permissions, blocked accounts
  • Validation errors: Invalid input format, missing required fields
  • Rate limiting errors: Too many attempts, temporary lockouts
  • System errors: Database connectivity, external service failures

Error Response Format: All errors include appropriate HTTP status codes, descriptive messages, and structured error codes for frontend handling.

Conclusion

The Authentication module provides a robust, secure, and scalable authentication system for the Comdeall platform. Key strengths include:

Frontend-Driven Design:

  • Clean separation of concerns between client and server
  • Frontend handles OAuth flows and initial token generation
  • Backend focuses on verification and user management

Multi-Strategy Authentication:

  • OAuth social login support for major providers
  • OTP-based email/phone verification with comprehensive security
  • Traditional admin authentication with enhanced security features
  • Seamless token refresh mechanism for session continuity

Security Features:

  • Hasura-compatible JWT tokens for GraphQL integration
  • Role-based access control with fine-grained permissions
  • Comprehensive rate limiting and device tracking
  • Secure password hashing with industry-standard algorithms

Integration Benefits:

  • Background job system integration for notifications and maintenance
  • Device management system for push notification targeting
  • Comprehensive audit logging for security monitoring
  • Clean API design with decorator-based route protection

The module's architecture supports the diverse needs of the child development platform, accommodating parents, therapists, and administrators while maintaining high security standards and optimal user experience.