Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/2FA_INTEGRATION_GUIDE.md

# Two-Factor Authentication Integration Guide

## 📋 Installation Complete!

Your 2FA system has been installed with the following components:

### Files Created:
- ✅ `sql/two_factor_auth.sql` - Database schema
- ✅ `classes/TwoFactorAuth.php` - 2FA service class
- ✅ `modules/security/two-factor-auth.php` - Admin setup page
- ✅ `verify-2fa.php` - Verification page during login
- ✅ `install_2fa.php` - Installation script

---

## 🔗 Integration with Login Pages

### STEP 1: Modify Admin Login (`login.php`)

Add this code **AFTER** successful password verification:

```php
// After line where password is verified successfully
if (password_verify($password, $user['password'])) {
    
    // CHECK FOR 2FA
    require_once 'classes/TwoFactorAuth.php';
    $twoFA = new TwoFactorAuth('admin');
    $twoFASettings = $twoFA->is2FAEnabled($user['id']);
    
    if ($twoFASettings && $twoFASettings['is_enabled']) {
        // Store user ID in session for 2FA verification
        $_SESSION['2fa_user_id'] = $user['id'];
        $_SESSION['2fa_user_type'] = 'admin';
        
        // Redirect to 2FA verification
        header('Location: verify-2fa.php');
        exit;
    }
    
    // NO 2FA - Continue normal login
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    // ... rest of login code
}
```

### STEP 2: Modify Member Login (`members/login.php`)

Add this code **AFTER** successful password verification:

```php
// After password verification
if (password_verify($password, $member['password_hash'])) {
    
    // CHECK FOR 2FA
    require_once '../classes/TwoFactorAuth.php';
    $twoFA = new TwoFactorAuth('member');
    $twoFASettings = $twoFA->is2FAEnabled($member['id']);
    
    if ($twoFASettings && $twoFASettings['is_enabled']) {
        // Store member ID in session for 2FA verification
        $_SESSION['2fa_user_id'] = $member['id'];
        $_SESSION['2fa_user_type'] = 'member';
        
        // Redirect to 2FA verification
        header('Location: ../verify-2fa.php');
        exit;
    }
    
    // NO 2FA - Continue normal login
    $_SESSION['member_id'] = $member['id'];
    $_SESSION['username'] = $member['username'];
    // ... rest of login code
}
```

---

## 🎯 How It Works

### Login Flow:
```
User enters credentials
        ↓
Password verified ✓
        ↓
Check if 2FA enabled?
        ↓
    YES → Redirect to verify-2fa.php
        ↓
    Enter 6-digit code
        ↓
    Code verified ✓
        ↓
    Login complete
```

### 2FA Methods:

1. **TOTP (Authenticator App)** - Primary Method
   - Google Authenticator
   - Microsoft Authenticator
   - Authy
   - 1Password
   - LastPass Authenticator

2. **Email OTP** - Backup Method
   - 6-digit code sent to email
   - Expires in 10 minutes

3. **SMS OTP** - Backup Method  
   - 6-digit code sent to phone
   - Expires in 10 minutes
   - Requires SMS provider integration

4. **Backup Codes** - Recovery Method
   - 10 one-time use codes
   - 8 characters each
   - Save securely offline

---

## 🔐 Setting Up 2FA

### For Admins:
1. Run installation: `http://localhost/copmadinaarea/install_2fa.php`
2. Go to **Dashboard → Security Settings**
3. Choose method (TOTP recommended)
4. Scan QR code with authenticator app
5. Enter 6-digit code to verify
6. **Save backup codes!**

### For Members:
1. Create member 2FA setup page at `members/security.php` (copy from admin version)
2. Members access via Account Settings
3. Same setup process as admins

---

## 📱 User Instructions

### Setting Up Authenticator App:

1. **Download App:**
   - iPhone: App Store → "Google Authenticator"
   - Android: Play Store → "Google Authenticator"

2. **Add Account:**
   - Open app
   - Tap "+" or "Add account"
   - Scan QR code displayed on setup page
   - Or enter code manually

3. **Verify:**
   - Enter 6-digit code from app
   - Save backup codes shown

4. **Login:**
   - Enter username & password
   - Enter current 6-digit code from app
   - Access granted!

---

## 🛠️ Advanced Configuration

### Enforce 2FA for All Users:

In `system_settings` table, update:
```sql
UPDATE system_settings 
SET setting_value = '1' 
WHERE setting_key = '2fa_enforced_admin';

UPDATE system_settings 
SET setting_value = '1' 
WHERE setting_key = '2fa_enforced_member';
```

### SMS Integration (Twilio Example):

Edit `classes/TwoFactorAuth.php` → `sendSMSOTP()` method:

```php
private function sendSMSOTP($userId, $code, $expiryMinutes) {
    // ... get phone number ...
    
    if ($phone) {
        // Twilio Integration
        require_once __DIR__ . '/../vendor/autoload.php';
        
        $twilio = new \Twilio\Rest\Client(
            'YOUR_ACCOUNT_SID',
            'YOUR_AUTH_TOKEN'
        );
        
        $message = $twilio->messages->create(
            $phone, // To
            [
                'from' => 'YOUR_TWILIO_NUMBER',
                'body' => "Your verification code is: {$code}\nExpires in {$expiryMinutes} minutes."
            ]
        );
    }
}
```

### Custom OTP Length:

```sql
UPDATE system_settings 
SET setting_value = '8' 
WHERE setting_key = 'otp_length';
```

### Custom Expiry Time:

```sql
UPDATE system_settings 
SET setting_value = '15' 
WHERE setting_key = 'otp_expiry_minutes';
```

---

## 🔍 Troubleshooting

### "Invalid verification code"

**TOTP Issues:**
- Ensure device time is synced (Settings → Date & Time → Auto)
- Time sync is critical for TOTP
- Try code discrepancy setting (default allows ±30 seconds)

**OTP Issues:**
- Check spam folder for email
- Verify phone number format (+1234567890)
- Check OTP hasn't expired (default 10 min)

### "Lost my device"

**Solutions:**
1. Use backup code (8-character code from setup)
2. Request email OTP on verification page
3. Contact admin to disable 2FA

### Can't receive SMS

**Check:**
1. Phone number format correct (+country code)
2. SMS provider configured in code
3. Check SMS provider logs
4. Use email OTP as alternative

---

## 📊 Security Monitoring

### View 2FA Attempt Logs:

```sql
SELECT 
    user_type,
    user_id,
    method_used,
    success,
    ip_address,
    created_at
FROM two_factor_attempts
WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
ORDER BY created_at DESC;
```

### Check Users Without 2FA:

```sql
-- Admins without 2FA
SELECT u.id, u.username, u.email, u.access_level
FROM users u
LEFT JOIN user_2fa_settings s ON u.id = s.user_id
WHERE (s.is_enabled = 0 OR s.is_enabled IS NULL)
AND u.access_level IN ('superuser', 'admin');

-- Members without 2FA
SELECT m.id, m.username, m.email
FROM member_accounts m
LEFT JOIN member_2fa_settings s ON m.id = s.member_id
WHERE (s.is_enabled = 0 OR s.is_enabled IS NULL);
```

---

## ⚠️ Important Security Notes

1. **Backup Codes:**
   - Generated once during setup
   - Each code can only be used once
   - Store offline (print or write down)
   - Don't share or screenshot

2. **QR Codes:**
   - Never share QR code screenshots
   - QR code is your secret key
   - Compromised QR = compromised 2FA

3. **Time Sync:**
   - TOTP requires accurate device time
   - Enable automatic time sync
   - Critical for authenticator apps

4. **Recovery:**
   - Always save backup codes
   - Provide alternative email
   - Admin can disable 2FA for recovery

5. **SMS Security:**
   - SMS less secure than TOTP
   - Vulnerable to SIM swapping
   - Use as backup only

---

## 🎓 User Education

### Email Template for Users:

**Subject: Important: Enable Two-Factor Authentication**

Dear [Name],

We're enhancing security by implementing Two-Factor Authentication (2FA). This adds an extra layer of protection to your account.

**What is 2FA?**
2FA requires two things to log in:
1. Your password (something you know)
2. A code from your phone (something you have)

**How to Set Up:**
1. Log in to your account
2. Go to Security Settings
3. Click "Enable 2FA"
4. Follow the setup wizard
5. **Important: Save your backup codes!**

**Recommended App:**
Google Authenticator (free on App Store / Play Store)

**Questions?**
Contact IT support at [email/phone]

Thank you for helping keep our systems secure!

---

## 📚 Additional Resources

### Documentation:
- TOTP Specification: RFC 6238
- HOTP Specification: RFC 4226
- Google Authenticator: https://github.com/google/google-authenticator

### Testing:
- Use `http://2fa.live` to test TOTP codes
- Verify time sync: `https://time.is`

### Libraries Used:
- Pure PHP implementation (no external dependencies)
- Compatible with all TOTP apps
- Standard Base32 encoding
- SHA1 HMAC algorithm

---

## ✅ Post-Installation Checklist

- [ ] Run `install_2fa.php`
- [ ] Verify database tables created
- [ ] Set up your own 2FA as test
- [ ] Test login with 2FA
- [ ] Test backup code
- [ ] Test email OTP
- [ ] Integrate with `login.php`
- [ ] Integrate with `members/login.php`
- [ ] Create member 2FA setup page
- [ ] Test member 2FA flow
- [ ] Configure SMS provider (optional)
- [ ] Document for your users
- [ ] Train support staff
- [ ] Monitor 2FA adoption rate

---

## 🚀 Future Enhancements

Potential additions:
- WebAuthn/FIDO2 support (hardware keys)
- Biometric authentication
- Remember device for 30 days
- 2FA enrollment reminders
- Admin dashboard for 2FA stats
- Bulk 2FA enforcement tools
- SMS provider failover
- Multi-device TOTP sync

---

## 📞 Support

For questions or issues:
1. Check troubleshooting section above
2. Review 2FA attempt logs in database
3. Test with backup codes
4. Contact system administrator

---

**Installation Date:** <?php echo date('Y-m-d H:i:s'); ?>  
**Version:** 1.0  
**Status:** ✅ Ready to Use

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists