true]); if (!empty($_SESSION['admin_id'])) { header('Location: dashboard.php'); exit; } // Déconnexion (redirige vers le handler dédié) if (isset($_GET['logout'])) { header('Location: /admin/login.php'); exit; } $error = ''; $username = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { Security::enforceSameOrigin(); Security::verifyCsrf($_POST['csrf_token'] ?? ''); require_once __DIR__ . '/../config/database.php'; $db = getDatabase(); $ip = Security::clientIp(); $username = trim($_POST['username'] ?? ''); $password = $_POST['password'] ?? ''; // Vérifier les tentatives récentes $attempts = $db->prepare( 'SELECT COUNT(*) FROM login_attempts WHERE ip = :ip AND created_at > NOW() - INTERVAL 15 MINUTE' ); $attempts->execute(['ip' => $ip]); $attemptCount = (int) $attempts->fetchColumn(); if ($attemptCount >= 5) { $error = 'Trop de tentatives. Réessayez dans 15 minutes.'; } elseif (empty($username) || empty($password)) { $error = 'Veuillez remplir tous les champs.'; } else { try { $stmt = $db->prepare( 'SELECT id, username, password_hash FROM admins WHERE username = :username LIMIT 1' ); $stmt->execute(['username' => $username]); $admin = $stmt->fetch(); if ($admin && password_verify($password, $admin['password_hash'])) { // Connexion réussie session_regenerate_id(true); $_SESSION['admin_id'] = $admin['id']; $_SESSION['admin_username'] = $admin['username']; // Log succès $db->prepare( 'INSERT INTO admin_logs (admin_id, username, action, ip, success) VALUES (:id, :u, :a, :ip, 1)' )->execute([ 'id' => $admin['id'], 'u' => $admin['username'], 'a' => 'login', 'ip' => $ip, ]); // Purger les tentatives de cette IP $db->prepare('DELETE FROM login_attempts WHERE ip = :ip')->execute(['ip' => $ip]); header('Location: dashboard.php'); exit; } else { // Échec — enregistrer la tentative $db->prepare( 'INSERT INTO login_attempts (ip, username) VALUES (:ip, :u)' )->execute(['ip' => $ip, 'u' => $username]); // Log échec $db->prepare( 'INSERT INTO admin_logs (username, action, ip, success) VALUES (:u, :a, :ip, 0)' )->execute(['u' => $username, 'a' => 'login_failed', 'ip' => $ip]); $remaining = 5 - ($attemptCount + 1); $error = 'Identifiants incorrects.' . ($remaining > 0 ? " ({$remaining} tentative(s) restante(s))" : ''); } } catch (PDOException $e) { error_log('Erreur login admin : ' . $e->getMessage()); $error = 'Une erreur est survenue. Veuillez réessayer.'; } } } ?>