# Two-Factor Authentication (2FA) Module Usage Instructions

> The `feat/two-factor-auth` branch introduces a comprehensive and secure Two-Factor Authentication system. Integrated cleanly with the `base` branch, it adds robust security layers (TOTP, Email OTP, Recovery Codes) that can be applied to any user model within the application.

---

## Table of Contents

1. [Module Overview](#1-module-overview)
2. [What You Inherit](#2-what-you-inherit)
3. [Deep Dive: Features & Functionality](#3-deep-dive-features--functionality)
4. [File Paths & Architecture](#4-file-paths--architecture)
5. [Step-by-Step Usage Guide](#5-step-by-step-usage-guide)

---

## 1. Module Overview

This branch establishes a complete 2FA lifecycle. It interrupts the standard login flow for users who have 2FA enabled, requiring them to verify their identity via a secondary method. It also includes "Forced Setup" screens to ensure mandatory enrollment, and comprehensive settings panels for users to manage their security preferences.

---

## 2. What You Inherit

By merging with the **Base** branch, this feature inherits:
- **UI Components:** Utilizes existing `<x-common.*>` and `<x-forms.otp-input>` Blade components to maintain a consistent aesthetic.
- **Unified Authentication:** Hooks directly into the base branch's `AuthenticatesUsers` trait, ensuring seamless integration with existing login logic.
- **Alpine.js Architecture:** The setup modals, OTP verification forms, and recovery code generators are all powered by reactive Alpine.js components.

---

## 3. Deep Dive: Features & Functionality

This branch brings enterprise-grade security features:

- **Multiple Authentication Methods:** 
  - **TOTP (Authenticator App):** Time-based One-Time Passwords using apps like Google Authenticator or Authy.
  - **Email OTP:** Secure 6-digit codes sent directly to the user's registered email address.
- **Recovery Codes:** 
  Automatically generates a set of 10 single-use recovery codes so users are never permanently locked out if they lose their device.
- **Mandatory Setup Workflow (Forced Setup):**
  Includes `EnsureCompleteTwoFactor` middleware. If an application policy requires a user to have 2FA, they are locked into a dedicated "Force Setup" UI until they successfully configure a method.
- **Throttling & Security Lockouts:**
  Built-in brute-force protection. After 5 failed attempts, the verification screen locks the user out for a configurable duration (default 120 seconds).
- **Device Remembering:**
  Users can check "Remember this device for 30 days" to bypass the 2FA prompt on trusted browsers.
- **Settings Management:**
  Dedicated views are provided for users to turn 2FA on/off, switch methods, and regenerate recovery codes.

---

## 4. File Paths & Architecture

Here are the key structural areas introduced:

### Configuration
- **`config/twofactorconfig.php`**: The central configuration file defining enabled methods, OTP length/expiry, throttling rules, and "remember device" durations.

### Core Architecture (`app/Models/`, `app/Http/Middleware/`)
- **`HasTwoFactor.php`**: The Eloquent trait you add to the `User` model to enable relationships and helper methods for 2FA.
- **`UserTwoFactor.php`**: The model interacting with the `user_two_factors` table to securely store secrets and backup codes.
- **`EnsureCompleteTwoFactor.php`**: Middleware to enforce setup.
- **`RedirectIfTwoFactorSetup.php`**: Middleware to prevent users from accessing the setup screens if they are already fully configured.

### Controllers & Services (`app/Http/Controllers/TwoFactor/`)
- **`VerificationController.php`**: Manages the post-login challenge screen.
- **`SetupController.php`**: Handles the logic for the initial method configuration (generating QR codes, sending setup emails).
- **`SettingsController.php`**: Manages the user's security dashboard.
- **`TwoFactorService.php`**: Centralizes the logic for TOTP generation, email dispatching, and recovery code validation.

### Views (`resources/views/pages/twofactor/`)
- **`force-setup/`**: The isolated UI for mandatory onboarding.
- **`verification/`**: The challenge screen shown after a successful password login.
- **`settings/`**: The management panels (includes both `index-admin.blade.php` and `index-user.blade.php`).

### JavaScript (`resources/js/twofactor/`)
- Dedicated Alpine.js modules for `verification.js`, `setup.js`, and `settings.js`.

---

## 5. Step-by-Step Usage Guide

### 1. Database & Environment Setup
Run the migrations to create the `user_two_factors` table:
```bash
php artisan migrate
```
Ensure your `.env` is configured for mail delivery to test the Email OTP method. You can globally toggle 2FA via:
```env
ENABLE_2FA=true
```

### 2. Implementing on Models
Ensure your `User` (or `Admin`) model uses the `HasTwoFactor` trait:
```php
use App\Models\Concerns\HasTwoFactor;

class User extends Authenticatable {
    use HasTwoFactor;
}
```

### 3. Testing the Verification Flow
- Log into the application as a user who has 2FA configured.
- You will be redirected to the `/2fa/verify` screen instead of the dashboard.
- Enter your TOTP code or request an Email OTP to proceed.
- Try entering the wrong code 5 times to see the throttling protection in action.

### 4. Testing the Settings / Setup Flow
- Navigate to the security settings page (e.g., `/user/security`).
- Enable Two-Factor Authentication. A modal will prompt you to choose an Authenticator App or Email.
- Complete the setup and securely save the generated Recovery Codes.
