Kulcare Docs
DeveloperBilling03 api reference

Two-Factor Authentication API Integration Guide

This document provides a comprehensive guide for frontend developers to integrate the Two-Factor Authentication (2FA) APIs into the Kulcare application.

Table of Contents

Overview

The 2FA system provides enhanced security with device trust management and comprehensive metrics tracking. It supports three verification methods:

  • TOTP (Time-based One-Time Password): Using authenticator apps like Google Authenticator
  • SMS: Sending verification codes via text message
  • EMAIL: Sending verification codes via email as backup method

Key Features

  • Device Trust Management: Mark devices as trusted to skip 2FA on subsequent logins
  • Enhanced Security Metrics: Track verification attempts, success rates, and security events
  • Automatic Code Delivery: SMS and Email codes are sent automatically during login
  • IP Address Tracking: All 2FA events include IP address logging for security
  • Session Management: Device trust revocation invalidates all sessions for that device

API Endpoints

Base URL: {{url}}/auth/two_factor

MethodEndpointPurpose
GET/statusCheck current 2FA status
POST/enableEnable 2FA (TOTP, SMS, or EMAIL)
POST/confirmConfirm 2FA setup with verification code
POST/verifyVerify 2FA code during login
POST/disableDisable 2FA with password confirmation
POST/regenerate_recovery_codesGenerate new recovery codes

⚠️ Breaking Change: The /send_email endpoint has been removed. Email codes are now sent automatically during login when EMAIL 2FA is enabled.

Device Management Endpoints

Base URL: {{url}}/auth/devices

MethodEndpointPurpose
GET/List user's devices
POST/:device_id/trustTrust a device
DELETE/:device_id/revoke_trustRevoke device trust

⚠️ Breaking Change: Device endpoints now use device_id instead of device_uuid as the URL parameter.

Initial Setup Flow

1. Check Current 2FA Status

GET {{url}}/auth/two_factor/status
Authorization: Bearer {{auth_token}}

Response example:

{
  "success": true,
  "message": "2FA status retrieved successfully",
  "data": {
    "enabled": false,
    "method": "SMS",
    "enabled_at": "2025-08-14T07:05:28.747Z",
    "recovery_codes_remaining": 8
  }
}

2. Enable TOTP 2FA

POST {{url}}/auth/two_factor/enable
Authorization: Bearer {{auth_token}}
Content-Type: application/json

{
  "method": "TOTP"
}

Response:

{
  "success": true,
  "message": "2FA setup initiated",
  "data": {
    "method": "TOTP",
    "setup_data": {
      "qr_code": "<svg>...</svg>",
      "secret": "JBSWY3DPEHPK3PXP",
      "provisioning_uri": "otpauth://totp/..."
    }
  }
}

UI Implementation:

  • Display the QR code for users to scan with their authenticator app
  • Show instructions for setting up authenticator apps

3. Enable SMS 2FA

POST {{url}}/auth/two_factor/enable
Authorization: Bearer {{auth_token}}
Content-Type: application/json

{
  "method": "SMS"
}

Response:

{
  "success": true,
  "data": {
    "method": "SMS",
    "setup_data": {
      "phone_number": "***-***-34"
    }
  },
  "message": "2FA setup initiated"
}

UI Implementation:

  • Show masked phone number where SMS will be sent
  • Display input field for verification code
  • Show "Resend SMS" option if needed

4. Confirm 2FA Setup

POST {{url}}/auth/two_factor/confirm
Authorization: Bearer {{auth_token}}
Content-Type: application/json

{
  "code": "123456"
}

Response:

{
  "success": true,
  "data": {
    "recovery_codes": [
      "abcd1234",
      "efgh5678",
      "ijkl9012",
      "mnop3456",
      "qrst7890"
    ]
  },
  "message": "2FA enabled successfully"
}

UI Implementation:

  • Display recovery codes prominently
  • Force user to download or copy codes before proceeding
  • Show warning about storing codes securely
  • Provide checkbox confirmation that codes are saved

Login Flow with 2FA

Step 1: Initial Sign In

POST {{url}}/auth/sign_in
Content-Type: application/json

{
  "user_signin_form": {
    "country_code": "+1",
    "phone_number": "1234567890",
    "password": "user_password",
    "platform": "web"
  },
  "device_details": {
    "device_uuid": "unique-device-id",
    "device_type": "iOS",
    "app_type": "mobile",
    "device_version": "14.0",
    "app_version": "1.0.0"
  }
}

Response A: No 2FA Required (Normal Login)

{
  "success": true,
  "data": {
    "id": 123,
    "auth_token": "eyJ...",
    "refresh_token": "eyJ...",
    "user": { ... }
  }
}

UI Implementation:

  • Store tokens securely
  • Redirect to dashboard
  • No additional steps needed

Response B: 2FA Required (TOTP)

{
  "success": true,
  "data": {
    "two_factor_method": "TOTP",
    "temp_auth_token": "eyJ..."
  },
  "type": "requires_2fa",
  "message": "2FA verification required"
}

UI Implementation:

  • Show 2FA verification screen
  • Display 6-digit code input field
  • Store temp_auth_token temporarily
  • Show "Use recovery code" option

Response C: 2FA Required (SMS - Code Auto-Sent)

{
  "success": true,
  "data": {
    "two_factor_method": "SMS",
    "temp_auth_token": "eyJ...",
    "masked_phone": "***-***-34"
  },
  "type": "requires_2fa",
  "message": "2FA verification required - SMS sent"
}

Response D: 2FA Required (Email - Code Auto-Sent)

{
  "success": true,
  "data": {
    "two_factor_method": "EMAIL",
    "temp_auth_token": "eyJ...",
    "masked_email": "jo***@example.com"
  },
  "type": "requires_2fa",
  "message": "2FA verification required - Email sent"
}

UI Implementation:

  • Show SMS verification screen
  • Display masked phone number
  • Show 6-digit code input field
  • Include "Resend SMS" button
  • Show "Use recovery code" option

Step 2: Verify 2FA Code

Option A: TOTP Verification

POST {{url}}/auth/two_factor/verify
Authorization: Bearer {{temp_auth_token}}
Content-Type: application/json

{
  "code": "123456",
  "method": "TOTP"
}

Option B: SMS Verification

POST {{url}}/auth/two_factor/verify
Authorization: Bearer {{temp_auth_token}}
Content-Type: application/json

{
  "code": "123456",
  "method": "SMS"
}

Option C: Email Verification

POST {{url}}/auth/two_factor/verify
Authorization: Bearer {{temp_auth_token}}
Content-Type: application/json

{
  "code": "123456",
  "method": "EMAIL",
  "device_uuid": "unique-device-id",
  "trust_device": true
}

Option D: Recovery Code Verification

POST {{url}}/auth/two_factor/verify
Authorization: Bearer {{temp_auth_token}}
Content-Type: application/json

{
  "code": "MBSA-P2XC",
  "method": "recovery",
  "device_uuid": "unique-device-id",
  "trust_device": true
}

Recovery Code Format:

  • 8-character alphanumeric codes (e.g., MBSA-P2XC, X7K9-M2RP)
  • Case-insensitive
  • One-time use only
  • Generated during 2FA setup

Success Response (All Methods):

{
  "success": true,
  "data": {
    "id": 123,
    "auth_token": "eyJ...",
    "refresh_token": "eyJ...",
    "user": { ... }
  },
  "type": "sign_in",
  "message": "2FA verification successful"
}

UI Implementation:

  • Store final tokens securely
  • Clear temporary token
  • Redirect to dashboard
  • Show success message

UI Implementation:

  • Disable "Resend" button for 30-60 seconds
  • Show countdown timer
  • Display confirmation message

Device Trust Management

Overview

Device trust allows users to mark devices as trusted, reducing 2FA friction on subsequent logins. When a device is trusted:

  • User can skip 2FA verification on that device
  • Trust can be established during 2FA verification by setting trust_device: true
  • Device trust can be revoked to force 2FA on next login
  • Revoking trust invalidates all active sessions for that device

Device Trust During Login

When verifying 2FA codes, you can simultaneously trust the device:

POST {{url}}/auth/two_factor/verify
Authorization: Bearer {{temp_auth_token}}
Content-Type: application/json

{
  "code": "123456",
  "method": "SMS",
  "device_uuid": "unique-device-id",
  "trust_device": true,
  "device_details": {
    "device_uuid": "unique-device-id",
    "device_type": "web",
    "app_type": "web",
    "device_version": "Chrome 120.0",
    "app_version": "2.1.0"
  }
}

List Trusted Devices

GET {{url}}/auth/devices
Authorization: Bearer {{auth_token}}

Enhanced Response:

{
  "success": true,
  "message": "Devices retrieved successfully",
  "data": {
    "devices": [
      {
        "id": 1,
        "device_uuid": "abc-123-def",
        "device_name": "iPhone 15",
        "device_type": "iOS", 
        "app_version": "2.1.0",
        "trusted_at": "2025-08-14T10:30:00Z",
        "last_trusted_ip": "192.168.1.100",
        "created_at": "2025-08-10T12:00:00Z",
        "updated_at": "2025-08-15T09:15:00Z"
      }
    ]
  }
}

Trust Device

POST {{url}}/auth/devices/1/trust
Authorization: Bearer {{auth_token}}

Revoke Device Trust

DELETE {{url}}/auth/devices/1/revoke_trust
Authorization: Bearer {{auth_token}}

Important: Revoking device trust will:

  • Mark device as untrusted
  • Invalidate all active sessions for that device
  • Force 2FA verification on next login from that device

Recovery Code Management

Using Recovery Codes During Login

Recovery codes are backup authentication methods when your primary 2FA method is unavailable.

When to Use Recovery Codes:

  • Lost or broken phone (SMS 2FA)
  • Lost authenticator app (TOTP)
  • Authenticator app out of sync
  • Emergency access situations

Regenerate Recovery Codes

POST {{url}}/auth/two_factor/regenerate_recovery_codes
Authorization: Bearer {{auth_token}}
Content-Type: application/json

{
  "password": "user_password"
}

Response:

{
  "success": true,
  "data": {
    "recovery_codes": [
      "MBSA-P2XC",
      "X7K9-M2RP",
      "Q3T8-HN6V",
      "R5Y2-KL9P",
      "M8B4-W3XZ"
    ]
  },
  "message": "New recovery codes generated"
}

UI Implementation:

  • Require password confirmation
  • Show warning that old codes become invalid
  • Force user to download/save new codes
  • Don't allow proceeding without confirmation

Recovery Code Status Monitoring:

Check Remaining Codes:

GET {{url}}/auth/two_factor/status
Authorization: Bearer {{auth_token}}

Response includes remaining codes:

{
  "success": true,
  "data": {
    "enabled": true,
    "method": "TOTP",
    "recovery_codes_remaining": 3
  }
}

UI Implementation:

  • Show warning when codes are running low (< 3 remaining)
  • Prompt user to generate new codes
  • Display remaining count in account settings

Disable 2FA

POST {{url}}/auth/two_factor/disable
Authorization: Bearer {{auth_token}}
Content-Type: application/json

{
  "password": "user_password"
}

UI Implementation:

  • Require password confirmation
  • Show warning about security implications
  • Confirm action with explicit user consent
  • Automatically revokes trust for all user devices

Security Metrics & Monitoring

Event Types Tracked

The system now tracks comprehensive 2FA metrics for security analysis:

  • verification_success: Successful 2FA code verification
  • verification_failure: Failed 2FA code verification
  • enable_attempt: User initiated 2FA setup
  • enable_success: User successfully enabled 2FA
  • disable_success: User disabled 2FA
  • device_trusted: Device marked as trusted
  • device_revoked: Device trust revoked

Metric Data Structure

Each metric includes:

{
  "user_id": 123,
  "event_type": "verification_success",
  "method": "SMS",
  "device_uuid": "abc-123-def",
  "ip_address": "192.168.1.100",
  "created_at": "2025-08-15T10:30:00Z"
}

Frontend Analytics Integration

Frontend should track these events for user behavior analysis:

// Example tracking events
const securityEvents = {
  '2fa_method_selected': { method: 'EMAIL' },
  '2fa_verification_attempted': { method: 'SMS', device_trusted: false },
  '2fa_verification_success': { method: 'TOTP', duration_ms: 1250 },
  'device_trusted': { device_uuid: 'abc-123' },
  'device_trust_revoked': { device_uuid: 'def-456' },
  '2fa_setup_completed': { method: 'EMAIL', recovery_codes_saved: true }
};

Enhanced Security Features

Email 2FA (Auto-Send)

⚠️ Breaking Change: Email codes are now sent automatically during login when EMAIL 2FA is enabled. The standalone /send_email endpoint has been removed.

Automatic Email Code Delivery

When a user with EMAIL 2FA attempts to sign in:

  1. System automatically sends verification code to user's email
  2. Response includes masked email address
  3. No manual "send email" step required

Enable Email 2FA

POST {{url}}/auth/two_factor/enable
Authorization: Bearer {{auth_token}}
Content-Type: application/json

{
  "method": "EMAIL"
}

Verify Email Code

POST {{url}}/auth/two_factor/verify
Authorization: Bearer {{temp_auth_token}}
Content-Type: application/json

{
  "method": "EMAIL",
  "code": "123456",
  "device_uuid": "unique-device-id",
  "trust_device": true
}

Frontend Implementation Requirements

Critical Breaking Changes

  1. Device ID Parameter: Device endpoints now use device_id instead of device_uuid
  2. Email Auto-Send: /send_email endpoint removed - codes sent automatically during login
  3. Enhanced Device Detection: Improved device identification logic for web vs mobile
  4. Response Structure: Masked contact info moved into data object

Device Fingerprinting

Frontend must generate and send comprehensive device data:

// Enhanced device details for all auth requests
const deviceDetails = {
  device_uuid: "unique-device-identifier",     // Required for web
  device_token: "push-notification-token",   // Required for mobile
  device_type: "web" | "ios" | "android",    // Required
  app_type: "web" | "mobile",               // Required
  device_name: "User's iPhone",             // Optional display name
  device_version: "iOS 17.0" | "Chrome 120", // Required
  app_version: "2.1.0",                     // Required
  browser_fingerprint: JSON.stringify({     // Required for web only
    userAgent: navigator.userAgent,
    language: navigator.language,
    platform: navigator.platform,
    screenResolution: `${screen.width}x${screen.height}`,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
  })
};

Device Identification Logic

The backend uses different identification strategies:

// Web devices: Use device_uuid
if (deviceType === 'web') {
  deviceIdentifier = deviceDetails.device_uuid;
}

// Mobile devices: Use device_token + device_type + app_type combination  
if (['ios', 'android'].includes(deviceType)) {
  deviceIdentifier = `${deviceType}-${deviceDetails.device_token}`;
}

Enhanced 2FA Verification Flow

// All 2FA verification requests now support device trust
const verifyRequest = {
  method: "SMS" | "EMAIL" | "TOTP" | "recovery", // Note: uppercase for SMS/EMAIL/TOTP
  code: "123456",
  device_uuid: deviceDetails.device_uuid,      // Required
  trust_device: true,                          // Optional: trust after verification
  device_details: deviceDetails                // Required for device identification
};

Device Management UI Requirements

1. Device List Interface

Display user devices with enhanced information:

interface DeviceListItem {
  id: number;                    // Use this for trust/revoke API calls
  device_uuid: string;
  device_name: string;           // Display name
  device_type: string;           // "iOS", "Android", "web"
  app_version: string;
  trusted_at: string | null;     // ISO timestamp if trusted
  last_trusted_ip: string;
  created_at: string;
  updated_at: string;
}

2. Trust/Revoke Controls

// Trust device - use device.id, not device_uuid
POST /auth/devices/{device.id}/trust

// Revoke trust - use device.id, not device_uuid
DELETE /auth/devices/{device.id}/revoke_trust

3. Security Alerts

  • Show notifications when new devices are detected
  • Display trust status changes
  • Alert when devices are revoked (sessions will be terminated)

Automatic Code Delivery

SMS 2FA

  • Code automatically sent during login
  • Display masked phone number from response
  • Show "Resend SMS" option with cooldown

Email 2FA

  • Code automatically sent during login
  • Display masked email from response
  • No manual send email step required

Error Handling Updates

// Handle new error types
const errorHandling = {
  'device.not_found': 'Device not found',
  'device.access_denied': 'Access denied to device',
  'email.is_required': 'Email address required for email 2FA',
  'email.failed to send': 'Failed to send email verification code',
  'account.is_temporarily_locked': 'Account temporarily locked due to failed attempts'
};

Session Management

// After successful 2FA verification:
// - Other sessions are invalidated (except current device)
// - Device can be automatically trusted
// - Regular auth tokens are issued
// - Temp auth token is no longer valid

Security Monitoring Integration

Track these enhanced events:

const securityEvents = {
  // 2FA Events
  '2fa_method_selected': { method: 'EMAIL' },
  '2fa_verification_attempted': { method: 'SMS', device_trusted: false },
  '2fa_verification_success': { method: 'TOTP', duration_ms: 1250 },
  '2fa_setup_initiated': { method: 'EMAIL' },
  '2fa_setup_completed': { method: 'SMS', recovery_codes_saved: true },
  
  // Device Trust Events
  'device_trusted': { device_id: 123, device_uuid: 'abc-123' },
  'device_trust_revoked': { device_id: 456, sessions_invalidated: true },
  'trusted_device_login': { device_id: 123, skipped_2fa: true },
  
  // Recovery Events
  'recovery_code_used': { codes_remaining: 3 },
  'recovery_codes_regenerated': { old_codes_invalidated: true }
};

On this page