Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/security/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/security/two-factor-auth.php

<?php
/**
 * Two-Factor Authentication Setup Page
 * For admin users
 */

require_once '../../config/config.php';
require_once '../../classes/TwoFactorAuth.php';

if (!isLoggedIn()) {
    header('Location: ../../login.php');
    exit;
}

$userId = $_SESSION['user_id'];
$twoFA = new TwoFactorAuth('admin');

$success = '';
$error = '';
$backupCodes = [];
$qrCodeUrl = '';
$secret = '';

// Handle 2FA enable/disable for individual methods
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['enable_totp'])) {
        // Generate secret and QR code for TOTP
        $secret = $twoFA->generateSecret();
        $_SESSION['temp_2fa_secret'] = $secret;
        $_SESSION['temp_2fa_method'] = 'totp';
        
        $username = $_SESSION['username'] ?? $_SESSION['email'] ?? 'User';
        $qrCodeUrl = $twoFA->getQRCodeImageUrl($secret, $username);
        
    } elseif (isset($_POST['verify_totp'])) {
        $code = $_POST['code'] ?? '';
        $secret = $_SESSION['temp_2fa_secret'] ?? '';
        
        if ($twoFA->verifyTOTP($secret, $code)) {
            $backupCodes = $twoFA->enableMethod($userId, 'totp', $secret);
            unset($_SESSION['temp_2fa_secret']);
            unset($_SESSION['temp_2fa_method']);
            $success = "TOTP Authenticator method enabled successfully!";
        } else {
            $error = "Invalid verification code. Please try again.";
            $qrCodeUrl = $twoFA->getQRCodeImageUrl($secret, $_SESSION['username'] ?? 'User');
        }
        
    } elseif (isset($_POST['enable_email'])) {
        $email = $_POST['email'] ?? $_SESSION['email'];
        $backupCodes = $twoFA->enableMethod($userId, 'email', null, null, $email);
        $success = "Email OTP method enabled successfully!";
        
    } elseif (isset($_POST['enable_sms'])) {
        $phone = $_POST['phone'] ?? '';
        if (empty($phone)) {
            $error = "Please provide a phone number for SMS verification.";
        } else {
            $backupCodes = $twoFA->enableMethod($userId, 'sms', null, $phone, null);
            $success = "SMS OTP method enabled successfully!";
        }
        
    } elseif (isset($_POST['disable_method'])) {
        $method = $_POST['method'] ?? '';
        if ($twoFA->disableMethod($userId, $method)) {
            $success = ucfirst($method) . " method has been disabled.";
        } else {
            $error = "Failed to disable " . ucfirst($method) . " method.";
        }
        
    } elseif (isset($_POST['disable_all_2fa'])) {
        if ($twoFA->disable2FA($userId)) {
            $success = "All Two-Factor Authentication methods have been disabled.";
        } else {
            $error = "Failed to disable Two-Factor Authentication.";
        }
        
    } elseif (isset($_POST['regenerate_backup'])) {
        $settings = $twoFA->get2FASettings($userId);
        if ($settings && $settings['is_enabled']) {
            $backupCodes = $twoFA->generateBackupCodes();
            $hashedCodes = $twoFA->hashBackupCodes($backupCodes);
            
            $table = 'user_2fa_settings';
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("UPDATE {$table} SET backup_codes = ? WHERE user_id = ?");
            $stmt->execute([json_encode($hashedCodes), $userId]);
            
            $success = "New backup codes generated!";
        }
    }
}

$settings = $twoFA->get2FASettings($userId);

include '../../includes/header.php';
include '../../includes/sidebar.php';
?>

<main class="main-content md:ml-64 pt-16">
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-800">
                <i class="fas fa-shield-alt mr-3"></i>Two-Factor Authentication
            </h1>
            <p class="text-gray-600 mt-2">Add an extra layer of security to your account</p>
        </div>

        <?php if ($success): ?>
            <div class="bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded-lg mb-6">
                <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg mb-6">
                <i class="fas fa-exclamation-circle mr-2"></i><?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <!-- Overall Status -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">
                <i class="fas fa-info-circle mr-2"></i>Overall Status
            </h2>
            
            <?php if ($settings && $settings['is_enabled']): ?>
                <?php
                $enabledMethods = $twoFA->getEnabledMethods($userId);
                $methodCount = count($enabledMethods);
                ?>
                <div class="flex items-center justify-between p-4 bg-green-50 border border-green-200 rounded-lg">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle text-green-600 text-2xl mr-3"></i>
                        <div>
                            <p class="font-semibold text-green-800">2FA is Active</p>
                            <p class="text-sm text-green-600"><?php echo $methodCount; ?> method<?php echo $methodCount > 1 ? 's' : ''; ?> enabled</p>
                        </div>
                    </div>
                    <form method="POST" class="inline" onsubmit="return confirm('Disable ALL 2FA methods?');">
                        <button type="submit" name="disable_all_2fa" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                            <i class="fas fa-times-circle mr-2"></i>Disable All
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <div class="flex items-center p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <i class="fas fa-exclamation-triangle text-yellow-600 text-2xl mr-3"></i>
                    <div>
                        <p class="font-semibold text-yellow-800">No 2FA Methods Enabled</p>
                        <p class="text-sm text-yellow-600">Enable at least one method below to secure your account</p>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Method Management Cards -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">
                <i class="fas fa-shield-alt mr-2"></i>Authentication Methods
            </h2>
            <p class="text-sm text-gray-600 mb-6">Enable multiple methods for maximum security and flexibility</p>
            
            <div class="grid md:grid-cols-3 gap-6">
                <!-- TOTP Method Card -->
                <div class="border-2 <?php echo !empty($settings['totp_enabled']) ? 'border-green-400 bg-green-50' : 'border-gray-200'; ?> rounded-lg p-5">
                    <div class="text-center mb-4">
                        <i class="fas fa-mobile-alt text-4xl text-blue-600 mb-2"></i>
                        <h3 class="font-bold text-gray-800">Authenticator App</h3>
                        <p class="text-xs text-gray-500 mt-1">Google Authenticator, Authy</p>
                    </div>
                    
                    <?php if (!empty($settings['totp_enabled'])): ?>
                        <div class="bg-green-100 text-green-800 px-3 py-2 rounded-lg text-center text-sm font-semibold mb-3">
                            ✓ Enabled
                        </div>
                        <form method="POST" onsubmit="return confirm('Disable TOTP method?');">
                            <input type="hidden" name="method" value="totp">
                            <button type="submit" name="disable_method" class="w-full px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 text-sm">
                                <i class="fas fa-times mr-1"></i>Disable
                            </button>
                        </form>
                    <?php else: ?>
                        <div class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-center text-sm mb-3">
                            Not Enabled
                        </div>
                        <form method="POST">
                            <button type="submit" name="enable_totp" class="w-full px-4 py-2 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:shadow-lg text-sm">
                                <i class="fas fa-plus mr-1"></i>Enable
                            </button>
                        </form>
                    <?php endif; ?>
                </div>

                <!-- Email OTP Method Card -->
                <div class="border-2 <?php echo !empty($settings['email_enabled']) ? 'border-green-400 bg-green-50' : 'border-gray-200'; ?> rounded-lg p-5">
                    <div class="text-center mb-4">
                        <i class="fas fa-envelope text-4xl text-purple-600 mb-2"></i>
                        <h3 class="font-bold text-gray-800">Email OTP</h3>
                        <p class="text-xs text-gray-500 mt-1">Codes sent to your email</p>
                    </div>
                    
                    <?php if (!empty($settings['email_enabled'])): ?>
                        <div class="bg-green-100 text-green-800 px-3 py-2 rounded-lg text-center text-sm font-semibold mb-3">
                            ✓ Enabled
                        </div>
                        <form method="POST" onsubmit="return confirm('Disable Email OTP method?');">
                            <input type="hidden" name="method" value="email">
                            <button type="submit" name="disable_method" class="w-full px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 text-sm">
                                <i class="fas fa-times mr-1"></i>Disable
                            </button>
                        </form>
                    <?php else: ?>
                        <div class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-center text-sm mb-3">
                            Not Enabled
                        </div>
                        <form method="POST" id="emailSetupForm">
                            <input type="email" name="email" value="<?php echo htmlspecialchars($_SESSION['email'] ?? ''); ?>" 
                                   class="w-full px-3 py-2 border rounded-lg text-sm mb-2" placeholder="Email" required>
                            <button type="submit" name="enable_email" class="w-full px-4 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg hover:shadow-lg text-sm">
                                <i class="fas fa-plus mr-1"></i>Enable
                            </button>
                        </form>
                    <?php endif; ?>
                </div>

                <!-- SMS OTP Method Card -->
                <div class="border-2 <?php echo !empty($settings['sms_enabled']) ? 'border-green-400 bg-green-50' : 'border-gray-200'; ?> rounded-lg p-5">
                    <div class="text-center mb-4">
                        <i class="fas fa-sms text-4xl text-green-600 mb-2"></i>
                        <h3 class="font-bold text-gray-800">SMS OTP</h3>
                        <p class="text-xs text-gray-500 mt-1">Codes sent via text</p>
                    </div>
                    
                    <?php if (!empty($settings['sms_enabled'])): ?>
                        <div class="bg-green-100 text-green-800 px-3 py-2 rounded-lg text-center text-sm font-semibold mb-3">
                            ✓ Enabled
                        </div>
                        <form method="POST" onsubmit="return confirm('Disable SMS OTP method?');">
                            <input type="hidden" name="method" value="sms">
                            <button type="submit" name="disable_method" class="w-full px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 text-sm">
                                <i class="fas fa-times mr-1"></i>Disable
                            </button>
                        </form>
                    <?php else: ?>
                        <div class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-center text-sm mb-3">
                            Not Enabled
                        </div>
                        <form method="POST" id="smsSetupForm">
                            <input type="tel" name="phone" class="w-full px-3 py-2 border rounded-lg text-sm mb-2" 
                                   placeholder="+1234567890" required>
                            <button type="submit" name="enable_sms" class="w-full px-4 py-2 bg-gradient-to-r from-green-600 to-teal-600 text-white rounded-lg hover:shadow-lg text-sm">
                                <i class="fas fa-plus mr-1"></i>Enable
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- TOTP QR Code Modal (shown when enabling TOTP) -->
        <?php if ($qrCodeUrl && isset($_SESSION['temp_2fa_method']) && $_SESSION['temp_2fa_method'] === 'totp'): ?>
        <div class="bg-white rounded-xl shadow-lg p-8 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4 text-center">
                <i class="fas fa-qrcode mr-2"></i>Scan QR Code
            </h2>
            <div class="text-center p-6 bg-gray-50 rounded-lg">
                <img src="<?php echo htmlspecialchars($qrCodeUrl); ?>" alt="QR Code" class="mx-auto mb-4" />
                <p class="text-sm text-gray-600 mb-2">Scan this with your authenticator app</p>
                <p class="text-xs text-gray-500 mb-4">Or enter this code manually:</p>
                <code class="bg-white px-4 py-2 rounded border text-base font-mono"><?php echo htmlspecialchars($secret); ?></code>
                
                <form method="POST" class="mt-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Enter 6-digit code from your app:</label>
                    <input type="text" name="code" maxlength="6" pattern="[0-9]{6}" required
                           class="w-64 mx-auto px-4 py-2 border border-gray-300 rounded-lg text-center text-2xl tracking-widest"
                           placeholder="000000" autofocus>
                    <div class="mt-4">
                        <button type="submit" name="verify_totp" class="px-8 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:shadow-lg">
                            <i class="fas fa-check mr-2"></i>Verify & Enable
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($backupCodes)): ?>
            <!-- Backup Codes Display -->
            <div class="bg-yellow-50 border-2 border-yellow-400 rounded-xl shadow-lg p-6 mb-6">
                <h2 class="text-xl font-bold text-yellow-800 mb-4">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Save Your Backup Codes!
                </h2>
                <p class="text-yellow-700 mb-4">These codes can be used to access your account if you lose your device. Each code can only be used once.</p>
                
                <div class="grid md:grid-cols-2 gap-2 bg-white p-4 rounded-lg mb-4">
                    <?php foreach ($backupCodes as $code): ?>
                        <code class="block p-2 bg-gray-100 rounded text-center font-mono font-bold"><?php echo $code; ?></code>
                    <?php endforeach; ?>
                </div>
                
                <button onclick="printBackupCodes()" class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 mr-2">
                    <i class="fas fa-print mr-2"></i>Print Codes
                </button>
                <button onclick="copyBackupCodes()" class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">
                    <i class="fas fa-copy mr-2"></i>Copy to Clipboard
                </button>
            </div>
        <?php endif; ?>

        <?php if ($settings && $settings['is_enabled']): ?>
            <!-- Manage 2FA -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-cog mr-2"></i>Manage 2FA
                </h2>
                
                <form method="POST" class="inline-block">
                    <button type="submit" name="regenerate_backup" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        <i class="fas fa-sync-alt mr-2"></i>Regenerate Backup Codes
                    </button>
                </form>
            </div>
        <?php endif; ?>
    </div>
</main>

<script>
function selectMethod(method) {
    // Hide all setup forms
    document.getElementById('totp_setup').classList.add('hidden');
    document.getElementById('email_setup').classList.add('hidden');
    document.getElementById('sms_setup').classList.add('hidden');
    
    // Remove all border highlights
    document.querySelectorAll('[onclick^="selectMethod"]').forEach(el => {
        el.classList.remove('border-blue-500');
        el.classList.add('border-gray-200');
    });
    
    // Show selected form and highlight
    document.getElementById(method + '_setup').classList.remove('hidden');
    event.currentTarget.classList.remove('border-gray-200');
    event.currentTarget.classList.add('border-blue-500');
    
    // Check radio button
    document.getElementById('method_' + method).checked = true;
}

function printBackupCodes() {
    window.print();
}

function copyBackupCodes() {
    const codes = <?php echo json_encode($backupCodes ?? []); ?>;
    const text = codes.join('\n');
    navigator.clipboard.writeText(text).then(() => {
        alert('Backup codes copied to clipboard!');
    });
}
</script>

<?php include '../../includes/footer.php'; ?>

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