diff --git a/auth.php b/auth.php new file mode 100644 index 0000000..72517ac --- /dev/null +++ b/auth.php @@ -0,0 +1,169 @@ +prepare("SELECT id FROM users WHERE username = ? OR email = ?"); + $stmt->execute([$username, $email]); + if ($stmt->fetch()) { + $error = 'Ce nom d\'utilisateur ou cet email est déjà utilisé.'; + } else { + $hashed_password = password_hash($password, PASSWORD_DEFAULT); + $stmt = $db->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)"); + try { + $stmt->execute([$username, $email, $hashed_password]); + $success = 'Compte créé avec succès ! Vous pouvez maintenant vous connecter.'; + } catch (Exception $e) { + $error = 'Erreur lors de la création du compte.'; + } + } + } + } elseif ($action === 'login') { + $username = trim($_POST['username'] ?? ''); + $password = $_POST['password'] ?? ''; + + if (empty($username) || empty($password)) { + $error = 'Tous les champs sont obligatoires.'; + } else { + $db = db(); + $stmt = $db->prepare("SELECT * FROM users WHERE username = ?"); + $stmt->execute([$username]); + $user = $stmt->fetch(); + + if ($user && password_verify($password, $user['password'])) { + $_SESSION['user_id'] = $user['id']; + $_SESSION['username'] = $user['username']; + $_SESSION['role'] = $user['role']; + + $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?")->execute([$user['id']]); + + header('Location: index.php'); + exit; + } else { + $error = 'Identifiants incorrects.'; + } + } + } +} + +if (isset($_GET['logout'])) { + session_destroy(); + header('Location: index.php'); + exit; +} + +$page = $_GET['page'] ?? 'login'; +?> + + +
+ + +