Fixes whitelisting in db

main
Yasen Pramatarov 2024-12-12 16:16:48 +02:00
parent a0747cfbc8
commit bc1089be21
1 changed files with 34 additions and 29 deletions

View File

@ -57,19 +57,23 @@ class RateLimiter {
// Check if IP is whitelisted // Check if IP is whitelisted
private function isIpWhitelisted($ip) { private function isIpWhitelisted($ip) {
// Check exact IP match // Check exact IP match and CIDR ranges
if (in_array($ip, $this->whitelistedIps)) { $stmt = $this->db->prepare("SELECT ip_address, is_network FROM {$this->whitelistTable}");
return true; $stmt->execute();
}
// Check CIDR ranges while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
foreach ($this->whitelistedNetworks as $network) { if ($row['is_network']) {
if ($this->ipInRange($ip, $network)) { if ($this->ipInRange($ip, $row['ip_address'])) {
return true; return true;
} }
} } else {
if ($ip === $row['ip_address']) {
return true;
}
}
}
return false; return false;
} }
private function ipInRange($ip, $cidr) { private function ipInRange($ip, $cidr) {
@ -84,29 +88,30 @@ class RateLimiter {
} }
// Add to whitelist // Add to whitelist
public function addToWhitelist($ip, $isNetwork = false) { public function addToWhitelist($ip, $isNetwork = false, $description = '', $createdBy = 'system') {
if ($isNetwork) { $stmt = $this->db->prepare("INSERT INTO {$this->whitelistTable}
if (!in_array($ip, $this->whitelistedNetworks)) { (ip_address, is_network, description, created_by)
$this->whitelistedNetworks[] = $ip; VALUES (?, ?, ?, ?)
} ON DUPLICATE KEY UPDATE
} else { is_network = VALUES(is_network),
if (!in_array($ip, $this->whitelistedIps)) { description = VALUES(description),
$this->whitelistedIps[] = $ip; created_by = VALUES(created_by)");
}
} return $stmt->execute([$ip, $isNetwork, $description, $createdBy]);
} }
// Remove from whitelist // Remove from whitelist
public function removeFromWhitelist($ip) { public function removeFromWhitelist($ip) {
$indexIp = array_search($ip, $this->whitelistedIps); $stmt = $this->db->prepare("DELETE FROM {$this->whitelistTable} WHERE ip_address = ?");
if ($indexIp !== false) {
unset($this->whitelistedIps[$indexIp]);
}
$indexNetwork = array_search($ip, $this->whitelistedNetworks); return $stmt->execute([$ip]);
if ($indexNetwork !== false) { }
unset($this->whitelistedNetworks[$indexNetwork]);
} public function getWhitelistedIps() {
$stmt = $this->db->prepare("SELECT * FROM {$this->whitelistTable} ORDER BY created_at DESC");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} }
public function attempt($username, $ipAddress) { public function attempt($username, $ipAddress) {