# Two-Factor Authentication (2FA) System

## Overview

The Two-Factor Authentication system provides an additional layer of security to your Laravel Livewire application. It supports multiple authentication methods and integrates seamlessly with your existing Microsoft OAuth authentication.

## Features

### ✅ Supported Authentication Methods

1. **TOTP (Time-based One-Time Password)**
   - Google Authenticator, Microsoft Authenticator, Authy, etc.
   - QR code generation for easy setup
   - Manual secret key entry option
   - Clock skew tolerance

2. **SMS Verification**
   - 6-digit verification codes
   - Phone number validation
   - Resend functionality
   - 10-minute expiration

3. **Email Verification**
   - 6-digit verification codes
   - Email delivery via Laravel mail system
   - Resend functionality
   - 10-minute expiration

### ✅ Security Features

- **Recovery Codes**: 8 backup codes for account recovery
- **Session Management**: Secure session handling
- **Encrypted Storage**: All secrets and codes encrypted at rest
- **Rate Limiting**: Protection against brute force attacks
- **Middleware Integration**: Automatic 2FA enforcement

## Installation

### 1. Dependencies

The system requires the following packages:
```bash
composer require bacon/bacon-qr-code
```

### 2. Database Migration

Run the migration to add 2FA fields to the users table:
```bash
php artisan migrate
```

### 3. Middleware Registration

The 2FA middleware is automatically registered in `bootstrap/app.php`:
```php
$middleware->alias([
    '2fa' => \App\Http\Middleware\TwoFactorAuthMiddleware::class,
]);
```

## Configuration

### Environment Variables

Add these optional variables to your `.env` file:

```env
# 2FA Configuration (Optional)
TWO_FACTOR_SESSION_LIFETIME=120
TWO_FACTOR_RECOVERY_CODES_COUNT=8
TWO_FACTOR_CODE_EXPIRATION_MINUTES=10

# Trusted IP Addresses (bypass 2FA for office/VPN networks)
# Separate multiple IPs/ranges with commas
# Supports single IPs: 192.168.1.100
# Supports CIDR ranges: 192.168.1.0/24, 10.0.0.0/8
TWO_FACTOR_TRUSTED_IPS=192.168.1.100,192.168.1.0/24,10.0.0.0/8

# Enable or disable IP bypass feature (default: true)
TWO_FACTOR_ENABLE_IP_BYPASS=true
```

### Database Fields

The following fields are added to the `users` table:

| Field | Type | Description |
|-------|------|-------------|
| `two_factor_secret` | text | Encrypted TOTP secret |
| `two_factor_recovery_codes` | text | Encrypted recovery codes |
| `two_factor_enabled` | boolean | Whether 2FA is enabled |
| `two_factor_confirmed_at` | timestamp | When 2FA was confirmed |
| `two_factor_method` | string | 2FA method (totp, sms, email) |
| `phone_number` | string | Phone number for SMS 2FA |
| `two_factor_required` | boolean | Whether 2FA is mandatory |

## Usage

### For End Users

#### Setting Up 2FA

1. **Login** to your account
2. **Navigate** to "Two-Factor Authentication" in the user menu
3. **Choose** your preferred method:
   - **Authenticator App**: Scan QR code or enter secret manually
   - **SMS**: Enter your phone number
   - **Email**: Use your registered email address
4. **Verify** your setup with the provided code
5. **Store** your recovery codes securely

#### Using 2FA

1. **Login** with your username/password or Microsoft OAuth
2. **Enter** your 2FA code when prompted
3. **Access** the application

#### Recovery Process

1. **Click** "Use Recovery Code Instead" on the 2FA screen
2. **Enter** one of your 8 recovery codes
3. **Access** your account
4. **Re-enable** 2FA with a new method

### For Administrators

#### Managing User 2FA

1. **Access** user management panel
2. **View** 2FA status for each user
3. **Require** 2FA for specific users
4. **Monitor** 2FA adoption rates

#### Enforcing 2FA

Set `two_factor_required = true` for users who must use 2FA:
```php
$user->update(['two_factor_required' => true]);
```

#### Trusted IP Addresses (Bypass 2FA)

For users connecting from trusted networks (office networks, VPNs), you can configure IP addresses that automatically bypass 2FA verification.

**Configuration:**

1. Add trusted IP addresses to your `.env` file:
```env
# Single IP address
TWO_FACTOR_TRUSTED_IPS=192.168.1.100

# Multiple IP addresses or ranges
TWO_FACTOR_TRUSTED_IPS=192.168.1.100,192.168.1.0/24,10.0.0.0/8

# Disable IP bypass entirely (set to false)
TWO_FACTOR_ENABLE_IP_BYPASS=false
```

**Supported Formats:**

- **Single IP**: `192.168.1.100`
- **IPv4 CIDR Range**: `192.168.1.0/24` (entire subnet)
- **IPv6 CIDR Range**: `2001:db8::/32`
- **Multiple entries**: Comma-separated or JSON array

**How It Works:**

1. When a user with 2FA enabled logs in from a trusted IP, the 2FA challenge is automatically bypassed
2. The session is marked as verified for the duration of the session
3. All bypass events are logged for security auditing
4. Users still need to authenticate with their username/password

**Security Considerations:**

- Only configure IP ranges for networks you fully trust (e.g., office networks, VPNs)
- Regularly review the trusted IP list
- Monitor logs for unexpected bypass events
- Consider additional security measures for highly sensitive data

## API Reference

### User Model Methods

```php
// Check if user has 2FA enabled
$user->hasTwoFactorEnabled();

// Check if 2FA is required
$user->isTwoFactorRequired();

// Get 2FA method
$user->getTwoFactorMethod();

// Check specific 2FA types
$user->hasTotpTwoFactor();
$user->hasSmsTwoFactor();
$user->hasEmailTwoFactor();

// Recovery codes
$user->getRecoveryCodes();
$user->hasRecoveryCodes();
$user->getRemainingRecoveryCodesCount();
```

### TwoFactorAuthService

```php
$service = app(TwoFactorAuthService::class);

// Generate TOTP secret
$secret = $service->generateSecret($user);

// Generate QR code
$qrCode = $service->generateQrCode($user, $secret);

// Generate recovery codes
$codes = $service->generateRecoveryCodes($user);

// Verify codes
$verified = $service->verifyTotp($user, $code);
$verified = $service->verifySmsCode($user, $code);
$verified = $service->verifyEmailCode($user, $code);
$verified = $service->verifyRecoveryCode($user, $code);

// Send codes
$service->sendSmsCode($user);
$service->sendEmailCode($user);

// Enable/Disable 2FA
$service->enable($user);
$service->disable($user);
```

## Routes

| Route | Method | Description | Access |
|-------|--------|-------------|---------|
| `/two-factor/setup` | GET | 2FA setup page | Authenticated |
| `/two-factor/verify/{userId?}` | GET | 2FA verification page | Public |

## Components

### TwoFactorSetup

**File**: `app/Livewire/TwoFactorSetup.php`
**View**: `resources/views/livewire/two-factor-setup.blade.php`

Handles the complete 2FA setup process including method selection, QR code generation, and verification.

### TwoFactorVerification

**File**: `app/Livewire/TwoFactorVerification.php`
**View**: `resources/views/livewire/two-factor-verification.blade.php`

Handles 2FA verification during login, including recovery code support.

## Middleware

### TwoFactorAuthMiddleware

**File**: `app/Http/Middleware/TwoFactorAuthMiddleware.php`

Automatically enforces 2FA verification for users who have it enabled. Redirects to verification page if 2FA is required but not verified.

## Security Considerations

### Best Practices

1. **Encryption**: All sensitive data is encrypted using Laravel's Crypt facade
2. **Session Security**: 2FA verification is tied to user sessions
3. **Rate Limiting**: Implement rate limiting on verification endpoints
4. **Recovery Codes**: Store recovery codes securely (not in plain text)
5. **Audit Logging**: Log all 2FA attempts and changes

### Production Recommendations

1. **SMS Service**: Integrate with Twilio or similar SMS service
2. **Email Service**: Use reliable email service (SendGrid, Mailgun, etc.)
3. **Redis**: Use Redis for temporary code storage instead of sessions
4. **Monitoring**: Monitor failed verification attempts
5. **Backup**: Regular backup of 2FA configurations

## Troubleshooting

### Common Issues

#### 1. "Invalid verification code" Error
**Cause**: Clock skew, expired code, or wrong code
**Solution**: 
- Check device time synchronization
- Request new code
- Verify code format

#### 2. "Recovery code not found" Error
**Cause**: Code already used or invalid
**Solution**: 
- Use a different recovery code
- Generate new recovery codes

#### 3. "SMS/Email not received" Error
**Cause**: Service configuration issues
**Solution**:
- Check SMS/email service configuration
- Verify phone number/email format
- Check service logs

#### 4. "QR code not scanning" Error
**Cause**: QR code format or size issues
**Solution**:
- Try manual secret entry
- Check QR code size and format
- Verify authenticator app compatibility

### Debug Mode

Enable detailed logging by setting in `.env`:
```env
LOG_LEVEL=debug
```

Check logs at `storage/logs/laravel.log` for 2FA-related errors.

## Integration with Microsoft OAuth

The 2FA system works seamlessly with your existing Microsoft OAuth authentication:

1. **Login Flow**: Microsoft OAuth → 2FA verification → Dashboard
2. **Session Management**: Both authentication methods are respected
3. **User Management**: 2FA settings persist across OAuth sessions

## Customization

### Adding New 2FA Methods

1. **Extend** `TwoFactorAuthService` with new methods
2. **Update** `TwoFactorSetup` component
3. **Add** validation rules
4. **Update** views with new UI elements

### Customizing UI

1. **Modify** Livewire component views
2. **Update** Tailwind CSS classes
3. **Add** custom JavaScript for enhanced UX
4. **Implement** custom validation messages

### Extending Functionality

1. **Add** backup methods (multiple 2FA methods per user)
2. **Implement** device trust (remember devices)
3. **Add** admin override capabilities
4. **Create** 2FA analytics and reporting

## Testing

### Manual Testing

1. **Setup 2FA** with each method
2. **Test** verification process
3. **Verify** recovery code functionality
4. **Test** middleware enforcement
5. **Check** session handling

### Automated Testing

```php
// Example test
public function test_user_can_enable_totp_2fa()
{
    $user = User::factory()->create();
    $service = app(TwoFactorAuthService::class);
    
    $secret = $service->generateSecret($user);
    $verified = $service->verifyTotp($user, $this->generateTOTP($secret));
    
    $this->assertTrue($verified);
}
```

## Performance Considerations

1. **QR Code Generation**: Cached for better performance
2. **Database Queries**: Optimized with proper indexing
3. **Session Storage**: Efficient session management
4. **Code Expiration**: Automatic cleanup of expired codes

## Compliance

The 2FA system supports various compliance requirements:

- **GDPR**: Secure data handling and user consent
- **SOC 2**: Security controls and audit trails
- **HIPAA**: Healthcare data protection (if applicable)
- **PCI DSS**: Payment card security (if applicable)

## Support

### For Technical Issues

1. **Check** Laravel logs: `storage/logs/laravel.log`
2. **Verify** database migrations: `php artisan migrate:status`
3. **Test** service configuration: `php artisan tinker`
4. **Review** middleware registration: `bootstrap/app.php`

### For User Issues

1. **Recovery Codes**: Guide users to use recovery codes
2. **Device Setup**: Help with authenticator app installation
3. **Phone/Email**: Verify contact information accuracy
4. **Admin Override**: Provide temporary access if needed

---

**Status**: ✅ **Fully Operational**  
**Last Updated**: Current Date  
**Version**: 1.0  
**Compatibility**: Laravel 11, Livewire 3, Microsoft OAuth

