logicspike/docs

Authentication & Team

Workflow: Login with 2FA & OTP

This document details the authentication flow, including Two-Factor Authentication (2FA).


1. The Flow Chart


2. Step-by-Step Logic

Step 1: Initial Login

  • Endpoint: POST /auth/login
  • Body: email, password.
  • Logic:
    1. Verify password hash.
    2. Check user.is_two_factor_enabled.
    3. If False: Issue Access/Refresh Tokens immediately.
    4. If True (2FA Enabled):
      • Method A: OTP (Email/Phone)
        • Generate 6-digit OTP.
        • Send to user.
      • Method B: Authenticator App (TOTP)
        • Do nothing (User already has the code generator).
      • Return JSON: { "mfa_required": true, "temp_token": "...", "method": "totp" }.
      • temp_token: Short-lived (5m) JWT. Scope: mfa_verify.

Step 2: MFA Verification

  • Endpoint: POST /auth/mfa/verify
  • Headers: Authorization: Bearer <temp_token>
  • Body: code ("123456").
  • Logic:
    1. Verify temp_token.
    2. If Method = TOTP:
      • Fetch user.two_factor_secret (Decrypted).
      • Verify code using TOTP algorithm (Window: +/- 1 step).
    3. If Method = OTP:
      • Check verifications table for identifier=user.email and code.
    4. If valid:
    5. If valid:
      • Delete OTP (prevent replay).
      • Issue Real Tokens (Access/Refresh).

3. Email Verification (Registration)

Similar flow, but happens before user creation (as defined in Registration Workflow).

  1. POST /auth/send-otp (Email) -> Received 6-digit code.
  2. POST /auth/verify-otp (Code) -> Receive verification_token.
  3. POST /register (Data + verification_token).

4. Enabling TOTP (Authenticator App)

User wants to switch from Email OTP to Google Authenticator.

  1. Frontend: POST /auth/mfa/setup (Auth required).
  2. API:
    • Generate random secret (Base32).
    • Return secret and otpauth:// URL (for QR Code).
  3. Frontend: Shows QR Code. User scans it.
  4. Frontend: POST /auth/mfa/enable (Body: { code: "..." }).
  5. API:
    • Verify code against the pending secret.
    • Commit: Update users table -> two_factor_secret = secret, two_factor_method = totp.

4. Edge Cases

  • Lost Device: User needs recovery codes (Future Feature).
  • OTP Delay: Code valid for 10 minutes.
  • Brute Force: verifications table tracks attempts. > 3 fails -> Invalidate code.
Authentication & Team