> ## Documentation Index
> Fetch the complete documentation index at: https://docs.adhdsimple.co.uk/llms.txt
> Use this file to discover all available pages before exploring further.

# Two-Factor Authentication (2FA) Implementation

> Simple TOTP-based 2FA using Supabase Auth

## Overview

The application requires all users to set up 2FA using TOTP (Time-based One-Time Password) via Supabase Auth. Users cannot access the app without completing 2FA setup.

## How It Works

### User Flow

1. User logs in with email/password
2. If no 2FA → redirected to `/mfa-setup`
3. If 2FA exists but not verified → redirected to `/mfa-verify`
4. If 2FA complete → access granted

### Setup Process

1. User scans QR code with authenticator app
2. User enters 6-digit code to verify
3. 2FA is enabled and required for future logins

## Components

### MfaSetupPage.tsx

* Generates QR code via Supabase
* Shows manual secret as fallback
* Verifies setup with 6-digit code
* Redirects to home when complete

### MfaVerifyPage.tsx

* Prompts for 6-digit code during login
* Verifies code via Supabase
* Redirects to home when verified

### MfaManagement.tsx

* Lists user's 2FA devices
* Allows removing devices
* Handles cleanup when last device removed

## Route Protection

**ProtectedRoute.tsx** handles the redirects:

```typescript theme={null}
// If user doesn't have MFA enabled, redirect to setup
if (!user.hasMfaEnabled) {
  return <Navigate to="/mfa-setup" replace />;
}

// If user has MFA but needs verification, redirect to verify
if (user.needsMfaVerification) {
  return <Navigate to="/mfa-verify" replace />;
}

// Otherwise, allow access
return <>{children}</>;
```

## AuthContext Methods

The following methods are available in `AuthContext`:

* **`enrollMfa()`** - Returns QR code and secret for setup
* **`verifyMfaEnrollment(factorId, code)`** - Verifies setup code
* **`verifyMfaLogin(code)`** - Verifies login code
* **`getMfaFactors()`** - Lists user's 2FA devices
* **`unenrollMfa(factorId)`** - Removes a 2FA device

## Technical Details

* Uses Supabase Auth's built-in TOTP implementation
* QR codes are generated server-side
* 30-second code rotation (standard TOTP)
* Works with any RFC 6238 compatible app (Google Authenticator, Authy, etc.)

## Error Handling

Simple error handling for:

* Invalid verification codes
* Network errors
* Missing factors

Most error handling is managed by Supabase Auth automatically.

<Note>
  This is a straightforward implementation. Users who lose access to their authenticator app will need admin assistance to reset their account.
</Note>
