From 2760c87bf2c91d07e8b23942ee653575dbe390a4 Mon Sep 17 00:00:00 2001 From: yasss2627 Date: Fri, 16 Jan 2026 22:08:51 +0000 Subject: [PATCH] Ajouter lib/RateLimit.php --- lib/RateLimit.php | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 lib/RateLimit.php diff --git a/lib/RateLimit.php b/lib/RateLimit.php new file mode 100644 index 0000000..207128d --- /dev/null +++ b/lib/RateLimit.php @@ -0,0 +1,63 @@ +pdo = $pdo; + $this->createTable(); + } + + /** + * Crée la table rate_limit_logs si elle n'existe pas + */ + private function createTable() { + $this->pdo->exec(" + CREATE TABLE IF NOT EXISTS `rate_limit_logs` ( + `id` INT AUTO_INCREMENT PRIMARY KEY, + `identifier` VARCHAR(255) NOT NULL, + `action` VARCHAR(50) NOT NULL, + `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + INDEX (`identifier`, `action`, `timestamp`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 + "); + } + + /** + * Enregistre une tentative + */ + public function recordAttempt($identifier, $action) { + $stmt = $this->pdo->prepare( + "INSERT INTO `rate_limit_logs` (identifier, action, timestamp) VALUES (?, ?, NOW())" + ); + $stmt->execute([(string)$identifier, (string)$action]); + } + + /** + * Vérifie si un utilisateur est bloqué + * @param $identifier ID utilisateur ou IP + * @param $action Action à limiter (login, post, etc) + * @param $limit Nombre d'actions autorisées + * @param $window Fenêtre de temps en secondes + */ + public function isBlocked($identifier, $action, $limit, $window) { + $since = date('Y-m-d H:i:s', time() - $window); + + $stmt = $this->pdo->prepare( + "SELECT COUNT(*) as count FROM `rate_limit_logs` + WHERE identifier = ? AND action = ? AND timestamp > ?" + ); + $stmt->execute([(string)$identifier, (string)$action, $since]); + $result = $stmt->fetch(PDO::FETCH_ASSOC); + + return $result['count'] >= $limit; + } + + /** + * Nettoie les anciens logs (optionnel) + */ + public function cleanup($daysOld = 7) { + $since = date('Y-m-d H:i:s', time() - ($daysOld * 86400)); + $stmt = $this->pdo->prepare("DELETE FROM `rate_limit_logs` WHERE timestamp < ?"); + $stmt->execute([$since]); + } +} \ No newline at end of file