Add backward compatibility when getting ban reasons in Lua and bwcli

This commit is contained in:
Théophile Diot 2024-01-30 09:51:46 +01:00
parent 0cd68eac6a
commit d27ee82a66
No known key found for this signature in database
GPG key ID: 248FEA4BAE400D06
3 changed files with 35 additions and 11 deletions

View file

@ -258,10 +258,15 @@ api.global.GET["^/bans$"] = function(self)
"can't access ttl " .. k .. " from datastore : " .. ttl
)
end
local ban_data = decode(result)
local ban =
local ban_data
ok, ban_data = pcall(decode, result)
if not ok then
ban_data = { reason = result, date = -1 }
end
table.insert(
data,
{ ip = k:sub(9, #k), reason = ban_data["reason"], date = ban_data["date"], exp = math.floor(ttl) }
table.insert(data, ban)
)
end
end
return self:response(HTTP_OK, "success", data)

View file

@ -317,7 +317,11 @@ utils.get_reason = function(ctx)
end
local banned, _ = datastore:get("bans_ip_" .. ip)
if banned then
return decode(banned)["reason"], {}
local ok, ban_data = pcall(decode, banned)
if ok then
banned = ban_data["reason"]
end
return banned, {}
end
-- unknown
if ngx.status == utils.get_deny_status() then
@ -642,12 +646,16 @@ utils.is_banned = function(ip)
if not result and err ~= "not found" then
return nil, "datastore:get() error : " .. result
elseif result and err ~= "not found" then
local ok, ttl = datastore:ttl("bans_ip_" .. ip)
local ban_data = decode(result)
if not ok then
return true, ban_data["reason"], -1
local ok, ban_data = pcall(decode, result)
if ok then
result = ban_data["reason"]
end
return true, ban_data["reason"], ttl
local ttl
ok, ttl = datastore:ttl("bans_ip_" .. ip)
if not ok then
return true, result, -1
end
return true, result, ttl
end
-- Redis case
local use_redis, err = utils.get_variable("USE_REDIS", false)
@ -694,7 +702,12 @@ utils.is_banned = function(ip)
if not ok then
return nil, "datastore:set() error : " .. err
end
return true, decode(data[1])["reason"], data[2]
local ban_data
ok, ban_data = pcall(decode, data[1])
if ok then
data[1] = ban_data["reason"]
end
return true, data[1], data[2]
end
clusterstore:close()
return false, "not banned"

View file

@ -258,7 +258,13 @@ class CLI(ApiCaller):
cli_str += "No ban found\n"
for ban in bans:
cli_str += f"- {ban['ip']} ; banned the {datetime.fromtimestamp(ban['date']).strftime('%d-%m-%Y at %H:%M:%S')} for {format_remaining_time(ban['exp'])} remaining with reason \"{ban.get('reason', 'no reason given')}\"\n"
banned_date = ""
remaining = "for eternity"
if ban["date"] != -1:
banned_date = f"the {datetime.fromtimestamp(ban['date']).strftime('%d-%m-%Y at %H:%M:%S')} "
if ban["exp"] != -1:
remaining = f"for {format_remaining_time(ban['exp'])} remaining"
cli_str += f"- {ban['ip']} ; banned {banned_date}{remaining} with reason \"{ban.get('reason', 'no reason given')}\"\n"
cli_str += "\n"
return True, cli_str