Ajouter lib/RateLimit.php
This commit is contained in:
parent
b7dc6eec61
commit
2760c87bf2
63
lib/RateLimit.php
Normal file
63
lib/RateLimit.php
Normal 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]);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user