# Two-Factor Authentication (2FA) Implementation

This document describes the implementation of Time-based One-Time Password (TOTP) two-factor authentication in the Rustelo application.

## Overview

The 2FA implementation provides an additional layer of security for user accounts by requiring a second form of authentication beyond username and password. This implementation uses TOTP (Time-based One-Time Password) compatible with popular authenticator apps like Google Authenticator, Authy, and Microsoft Authenticator.

## Features

- **TOTP Authentication**: Standards-compliant TOTP implementation (RFC 6238)
- **QR Code Generation**: Automatic QR code generation for easy setup
- **Backup Codes**: Recovery codes for account access if authenticator device is lost
- **Rate Limiting**: Protection against brute force attacks
- **Audit Trail**: Logging of 2FA attempts for security monitoring
- **Graceful Degradation**: Existing users can continue using the system without 2FA until they opt-in

## Architecture

### Backend Components

#### Database Schema
- `user_2fa`: Stores TOTP secrets and configuration
- `user_2fa_recovery_codes`: Individual recovery codes for better tracking
- `user_2fa_attempts`: Audit trail of authentication attempts
- `users`: Extended with `two_factor_required` flag
- `sessions`: Extended with `two_factor_verified` flag

#### Core Services
- `TwoFactorService`: Main 2FA business logic
- `AuthService`: Extended to handle 2FA login flow
- `AuthRepository`: Database operations for user management

#### API Endpoints
- `POST /api/auth/login`: First step login (returns 2FA requirement)
- `POST /api/auth/login/2fa`: Second step login with 2FA code
- `POST /api/auth/2fa/setup`: Initialize 2FA setup
- `POST /api/auth/2fa/verify`: Verify and enable 2FA
- `GET /api/auth/2fa/status`: Get current 2FA status
- `POST /api/auth/2fa/disable`: Disable 2FA
- `POST /api/auth/2fa/backup-codes`: Generate new backup codes

### Frontend Components

#### React Components
- `TwoFactorSetup`: Complete 2FA setup flow
- `TwoFactorLoginForm`: 2FA code input during login
- `TwoFactorLoginPage`: Full page 2FA login
- `GenerateBackupCodesComponent`: Backup code management
- `DisableTwoFactorComponent`: 2FA disabling interface

#### Auth Context
- Extended `AuthContext` to handle 2FA states
- `requires_2fa` flag to track 2FA requirement
- `pending_2fa_email` to store email during 2FA flow

## Setup Process

### 1. User Initiates 2FA Setup
```rust
POST /api/auth/2fa/setup
{
  "password": "current_password"
}
```

### 2. Server Response
```json
{
  "success": true,
  "data": {
    "secret": "BASE32_ENCODED_SECRET",
    "qr_code_url": "data:image/svg+xml;base64,QR_CODE_DATA",
    "backup_codes": ["12345678", "87654321", ...]
  }
}
```

### 3. User Scans QR Code
- User scans QR code with authenticator app
- Alternatively, manually enters the secret key

### 4. User Verifies Setup
```rust
POST /api/auth/2fa/verify
{
  "code": "123456"
}
```

### 5. 2FA Enabled
- TOTP verification successful
- 2FA is now enabled for the account
- Backup codes are active

## Login Flow

### 1. Standard Login
```rust
POST /api/auth/login
{
  "email": "user@example.com",
  "password": "password",
  "remember_me": false
}
```

### 2. 2FA Required Response
```json
{
  "success": true,
  "data": {
    "user": { ... },
    "access_token": "",
    "requires_2fa": true
  }
}
```

### 3. 2FA Code Submission
```rust
POST /api/auth/login/2fa
{
  "email": "user@example.com",
  "code": "123456",
  "remember_me": false
}
```

### 4. Complete Authentication
```json
{
  "success": true,
  "data": {
    "user": { ... },
    "access_token": "JWT_TOKEN",
    "refresh_token": "REFRESH_TOKEN",
    "requires_2fa": false
  }
}
```

## Security Features

### Rate Limiting
- Maximum 5 failed attempts per 15-minute window
- Prevents brute force attacks on 2FA codes

### Backup Codes
- 8-digit recovery codes
- Hashed storage in database
- Single-use only
- Can be regenerated

### Audit Trail
- All 2FA attempts are logged
- Includes IP address, user agent, and timestamp
- Distinguishes between TOTP and backup code usage

### Secret Management
- TOTP secrets are Base32 encoded
- Secrets are unique per user
- Secrets are generated using cryptographically secure random number generation

## Configuration

### Environment Variables
```env
# Database connection
DATABASE_URL=postgresql://localhost/rustelo_dev

# JWT configuration
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRATION=3600

# Application settings
APP_NAME=Rustelo
ISSUER_NAME=Rustelo Authentication
```

### Dependencies
```toml
[dependencies]
# 2FA specific
totp-rs = "5.6"
qrcode = { version = "0.15", features = ["svg"] }
base32 = "0.5"
sha2 = "0.10"
base64 = "0.22"
```

## Usage Examples

### Enable 2FA for a User
```rust
// Setup 2FA
let request = Setup2FARequest {
    password: "user_password".to_string(),
};
let response = auth_service.setup_2fa(user_id, request).await?;

// Verify and enable
let verify_request = Verify2FARequest {
    code: "123456".to_string(),
};
auth_service.verify_2fa_setup(user_id, verify_request, None, None).await?;
```

### Login with 2FA
```rust
// First step: regular login
let login_request = LoginCredentials {
    email: "user@example.com".to_string(),
    password: "password".to_string(),
    remember_me: false,
};
let response = auth_service.login(login_request, None).await?;

if response.requires_2fa {
    // Second step: 2FA verification
    let twofa_request = Login2FARequest {
        email: "user@example.com".to_string(),
        code: "123456".to_string(),
        remember_me: false,
    };
    let final_response = auth_service.login_with_2fa(twofa_request, None, None, None).await?;
}
```

## Testing

### Unit Tests
```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_2fa_setup() {
        let service = TwoFactorService::new(pool, "Test".to_string(), "Test".to_string());
        let response = service.setup_2fa(user_id, "user@test.com", request).await;
        assert!(response.is_ok());
    }

    #[tokio::test]
    async fn test_totp_verification() {
        // Test TOTP code verification
        let service = TwoFactorService::new(pool, "Test".to_string(), "Test".to_string());
        let result = service.verify_2fa_for_login(user_id, "123456", None, None).await;
        // Assert based on test conditions
    }
}
```

### Integration Tests
```rust
#[tokio::test]
async fn test_full_2fa_flow() {
    // Test complete 2FA setup and login flow
    // 1. Setup 2FA
    // 2. Verify setup
    // 3. Login with 2FA
    // 4. Verify successful authentication
}
```

## Migration Guide

### Database Migration
```sql
-- Run migration 002_add_2fa_support.sql
-- This adds all necessary 2FA tables and columns
```

### Existing Users
- Existing users can continue using the system without 2FA
- 2FA is opt-in for existing users
- `two_factor_enabled` field defaults to `false`

### Deployment Steps
1. Deploy database migration
2. Deploy backend code with 2FA support
3. Deploy frontend code with 2FA components
4. Update documentation and user guides

## Troubleshooting

### Common Issues

#### QR Code Not Displaying
- Check that SVG rendering is enabled
- Verify QR code generation dependencies
- Check browser console for errors

#### Invalid 2FA Code
- Ensure device time is synchronized
- Verify secret key entry
- Check for typos in manual entry

#### Backup Code Not Working
- Verify code hasn't been used before
- Check for typing errors
- Ensure user has remaining backup codes

### Debug Commands
```bash
# Check 2FA status for user
psql -d rustelo_dev -c "SELECT * FROM user_2fa WHERE user_id = 'USER_ID';"

# View recent 2FA attempts
psql -d rustelo_dev -c "SELECT * FROM user_2fa_attempts WHERE user_id = 'USER_ID' ORDER BY created_at DESC LIMIT 10;"

# Check backup codes
psql -d rustelo_dev -c "SELECT code_hash, used_at FROM user_2fa_recovery_codes WHERE user_id = 'USER_ID';"
```

## Security Considerations

### Best Practices
- Use HTTPS in production
- Implement proper session management
- Regular security audits
- Monitor 2FA attempt logs
- User education on 2FA security

### Compliance
- TOTP implementation follows RFC 6238
- Backup codes follow industry best practices
- Audit logging supports compliance requirements

## Future Enhancements

### Planned Features
- SMS-based 2FA as alternative
- Hardware security key support (WebAuthn)
- Admin-enforced 2FA policies
- Bulk 2FA management for organizations
- Advanced reporting and analytics

### Performance Optimizations
- Caching of 2FA status
- Async processing of audit logs
- Database query optimization
- CDN for QR code generation

## Support

For issues or questions regarding 2FA implementation:
1. Check this documentation
2. Review server logs
3. Check database state
4. Contact development team

---

Last Updated: 2024-01-XX
Version: 1.0.0