PluginProbe
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses / 1.0.94
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses v1.0.94
2.10.0 2.10.01 2.9.1 2.9.0 2.8.1 2.8.0 2.7.7 2.7.5 2.7.0 2.6.01 2.6.0 2.5.0 2.4.01 trunk 1.0.90 1.0.91 1.0.92 1.0.93 1.0.94 1.0.95 1.0.96 1.0.97 1.0.98 1.0.99 1.1.0 All 77 releases
fluent-community / vendor / wpfluent / framework / src / WPFluent / Http / Middleware / RateLimiter.php

RateLimiter.php in FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses 1.0.94, at vendor/wpfluent/framework/src/WPFluent/Http/Middleware/RateLimiter.php

90 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCommunity\Framework\Http\Middleware;
4
5 use FluentCommunity\Framework\Foundation\App;
6
7 class RateLimiter
8 {
9 protected $limit;
10 protected $interval;
11
12 public function __construct($limit, $interval)
13 {
14 $this->limit = $limit;
15 $this->interval = $interval;
16 }
17
18 public function handle($request, $next)
19 {
20 if ($this->shouldAllow($request)) {
21 return $next($request);
22 }
23
24 $settings = $this->getSettings(
25 $request, $currentTime = time()
26 );
27
28 if ($this->isIntervalExpired($settings, $currentTime)) {
29 $settings = $this->resetRateLimit($currentTime);
30 } else {
31 $settings['count']++;
32 }
33
34 $this->updateSettings($request, $settings);
35
36 if ($this->isRateLimitExceeded($settings)) {
37 return $request->abort(429, 'Too many requests.');
38 }
39
40 return $next($request);
41 }
42
43 protected function shouldAllow($request)
44 {
45 return is_user_logged_in() || $request->method() === 'HEAD';
46 }
47
48 protected function getSettings($request, $currentTime)
49 {
50 $settings = $this->getTransient($request);
51 return $settings ?: ['count' => 0, 'firstTime' => $currentTime];
52 }
53
54 protected function isIntervalExpired($settings, $currentTime)
55 {
56 return (
57 $currentTime - $settings['firstTime']
58 ) > $this->interval;
59 }
60
61 protected function resetRateLimit($currentTime)
62 {
63 return ['count' => 1, 'firstTime' => $currentTime];
64 }
65
66 protected function isRateLimitExceeded($settings)
67 {
68 return $settings['count'] > $this->limit;
69 }
70
71 protected function getTransient($request)
72 {
73 return get_transient($this->makeTransientKey($request));
74 }
75
76 protected function updateSettings($request, $settings)
77 {
78 $key = $this->makeTransientKey($request);
79
80 set_transient($key, $settings, $this->interval);
81 }
82
83 protected function makeTransientKey($request)
84 {
85 $slug = App::config()->get('app.slug');
86
87 return "{$slug}_rate_limit_" . md5($request->getIp());
88 }
89 }
90