extend rate limiter
This commit is contained in:
41
classes/RateLimiter.php
Normal file
41
classes/RateLimiter.php
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user