PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.6.4
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.6.4
1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 1.3.19 trunk 1.2.0 All 47 releases
fluent-cart / app / Services / RateLimiter.php

RateLimiter.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.6.4, at app/Services/RateLimiter.php

82 lines 2.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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