extend rate limiter

This commit is contained in:
O K
2026-04-05 21:20:54 +03:00
parent 811451bd1c
commit 961c1ed53d
5 changed files with 58 additions and 38 deletions

41
classes/RateLimiter.php Normal file
View File

@@ -0,0 +1,41 @@
<?php
class RateLimiter
{
/**
* @param string $ip The IP to check
* @param string $action A unique string for the action (e.g., '404', 'verify_attempt')
* @param int $max_requests
* @param int $window seconds
* @return bool True if allowed, false if limit exceeded
*/
public static function checkIsRateLimited($ip, $action, $max_requests, $window)
{
// 1. Check if the Cache module is available
if (!Module::isInstalled('dbmemorycache') || !Module::isEnabled('dbmemorycache')) {
return false; // Not limited if we can't track it
}
$cache = Module::getInstanceByName('dbmemorycache');
if (!$cache) {
return false;
}
// 2. Generate unique key for this IP + Action
$cacheKey = hash('sha256', 'bot_limit_' . $action . '_' . $ip);
// 3. Get current count
$currentCount = 0;
if ($cache->existsValue($cacheKey)) {
$currentCount = (int) $cache->getValue($cacheKey);
}
$currentCount++;
// 4. Save back with the window (Resets timer on every hit = Sliding Window)
$cache->setValue($cacheKey, $currentCount, $window);
// 5. Return status
return ($currentCount > $max_requests);
}
}