-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.lua
More file actions
53 lines (46 loc) · 1.65 KB
/
handler.lua
File metadata and controls
53 lines (46 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
-- flood-control plugin configuration code
local kong = kong
local ngx = ngx
local ngx_shared = ngx.shared
local FloodControlHandler = {}
FloodControlHandler.VERSION = "1.0.0"
FloodControlHandler.PRIORITY = 1200
-- Access phase logic
function FloodControlHandler:access(conf)
-- Determine identifier based on configuration
local identifier
if conf.identifier_type == "ip" then
identifier = kong.client.get_forwarded_ip()
elseif conf.identifier_type == "consumer" then
identifier = (kong.client.get_consumer() or kong.client.get_credential()).id
else
identifier = kong.client.get_forwarded_ip()
end
-- Calculate interval per request
local rate = conf.rate
local unit = conf.unit
local interval
if unit == "second" then
interval = 1 / rate -- Convert to seconds
elseif unit == "minute" then
interval = 60 / rate -- Convert to seconds
else
return kong.response.exit(400, {message = "Invalid Rate Unit. Use 'second', or 'minute'."})
end
-- Use shared memory to track request timestamps
local last_time = ngx_shared.flood_control:get(identifier) -- Get last request time for this identifier
local now = ngx.now() -- Get current time in seconds with millisecond precision
if last_time then
local elapsed = now - last_time
if elapsed < interval then
return kong.response.exit(
429,
{
message = "Flood Control: Too many requests within the allowed rate."
}
)
end
end
ngx_shared.flood_control:set(identifier, now)
end
return FloodControlHandler