Ajouter lib/RateLimit.php

This commit is contained in:
yasss2627 2026-01-16 22:08:51 +00:00
parent b7dc6eec61
commit 2760c87bf2

63
lib/RateLimit.php Normal file
View File

@ -0,0 +1,63 @@
<?php
class RateLimit {
private $pdo;
public function __construct($pdo) {
$this->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]);
}
}