| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Services; |
| 4 |
|
| 5 |
use FluentCart\App\Helpers\AddressHelper; |
| 6 |
|
| 7 |
class RateLimiter |
| 8 |
{ |
| 9 |
|
| 10 |
public static function isActive() |
| 11 |
{ |
| 12 |
return wp_using_ext_object_cache(); |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Checks if the action identified by $identifier is being spammed. This will only work if an external object cache is enabled. |
| 17 |
* Usage: FluentCart\App\Services\RateLimiter::isSpamming('checkout_attempt', 5, 60); // allows 5 attempts per 60 seconds |
| 18 |
* |
| 19 |
* @param $identifier string A unique identifier for the action being rate limited. For example: checkout_attempt |
| 20 |
* @param $limit Number of allowed attempts within the time window |
| 21 |
* @param $seconds integer Time window in seconds |
| 22 |
* @param $sendJson boolean Whether to send a JSON response when rate limit is exceeded |
| 23 |
* @return bool |
| 24 |
*/ |
| 25 |
public static function isSpamming($identifier, $limit = 10, $seconds = 30, $sendJson = false) |
| 26 |
{ |
| 27 |
if (!self::isActive()) { |
| 28 |
return false; // Currently only support rate limiting when external object cache is enabled |
| 29 |
} |
| 30 |
|
| 31 |
$prefix = AddressHelper::getIpAddress(); |
| 32 |
$userId = get_current_user_id(); |
| 33 |
if ($userId) { |
| 34 |
$prefix .= "_user_{$userId}"; |
| 35 |
} |
| 36 |
|
| 37 |
$prefix = md5($prefix); |
| 38 |
$identifier = "{$prefix}_{$identifier}"; |
| 39 |
$hits = static::getCurrentHits($identifier); |
| 40 |
|
| 41 |
if (!$hits) { |
| 42 |
$hits = [ |
| 43 |
time() |
| 44 |
]; |
| 45 |
// Save the hit for the first time |
| 46 |
self::setHits($identifier, $hits, $seconds); |
| 47 |
return false; // all good here |
| 48 |
} |
| 49 |
|
| 50 |
// Remove hits older than the time window |
| 51 |
$currentTime = time(); |
| 52 |
$hits = array_filter($hits, function ($hitTime) use ($currentTime, $seconds) { |
| 53 |
return ($currentTime - $hitTime) <= $seconds; |
| 54 |
}); |
| 55 |
|
| 56 |
// Add the current hit |
| 57 |
$hits[] = $currentTime; |
| 58 |
self::setHits($identifier, $hits, $seconds); |
| 59 |
|
| 60 |
$isSpamming = count($hits) > $limit; |
| 61 |
|
| 62 |
if ($isSpamming && $sendJson) { |
| 63 |
wp_send_json([ |
| 64 |
'message' => __('Too many requests. Please try again after some time.', 'fluent-cart') |
| 65 |
], 429); |
| 66 |
} |
| 67 |
|
| 68 |
return $isSpamming; |
| 69 |
} |
| 70 |
|
| 71 |
private static function getCurrentHits($identifier) |
| 72 |
{ |
| 73 |
$hits = Cache::get("rate_limit:{$identifier}"); |
| 74 |
return $hits ?? []; |
| 75 |
} |
| 76 |
|
| 77 |
private static function setHits($identifier, $hits, $seconds) |
| 78 |
{ |
| 79 |
return Cache::set("rate_limit:{$identifier}", $hits, $seconds); |
| 80 |
} |
| 81 |
} |
| 82 |
|