2021-05-16 15:50:22 +00:00
|
|
|
import atexit
|
|
|
|
|
|
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
|
|
|
|
|
|
banned = {}
|
|
|
|
active = False
|
|
|
|
threshold = -1
|
|
|
|
|
2021-05-18 03:41:02 +00:00
|
|
|
|
2021-11-24 17:41:12 +00:00
|
|
|
def forgive_banned():
|
2021-05-16 15:50:22 +00:00
|
|
|
global banned
|
2021-11-24 17:49:07 +00:00
|
|
|
global threshold
|
2021-05-16 15:50:22 +00:00
|
|
|
|
2021-11-24 17:41:12 +00:00
|
|
|
clear_list = []
|
|
|
|
|
|
|
|
for ip in banned:
|
|
|
|
if banned[ip] <= 0:
|
|
|
|
clear_list.append(ip)
|
|
|
|
else:
|
2021-11-24 17:49:07 +00:00
|
|
|
banned[ip] = min(threshold, banned[ip]) - 1
|
2021-11-24 17:41:12 +00:00
|
|
|
|
|
|
|
for ip in clear_list:
|
|
|
|
del banned[ip]
|
2021-05-18 03:41:02 +00:00
|
|
|
|
2022-02-20 08:09:02 +00:00
|
|
|
|
2021-05-18 03:41:02 +00:00
|
|
|
def setup(violations_threshold=100):
|
2021-05-16 15:50:22 +00:00
|
|
|
global active
|
|
|
|
global threshold
|
|
|
|
|
|
|
|
active = True
|
|
|
|
threshold = violations_threshold
|
|
|
|
|
|
|
|
scheduler = BackgroundScheduler()
|
2022-07-15 17:03:13 +00:00
|
|
|
scheduler.add_job(func=forgive_banned, trigger="interval", minutes=30)
|
2021-05-16 15:50:22 +00:00
|
|
|
scheduler.start()
|
|
|
|
|
|
|
|
# Shut down the scheduler when exiting the app
|
|
|
|
atexit.register(lambda: scheduler.shutdown())
|
|
|
|
|
|
|
|
|
|
|
|
def report(request_ip):
|
2021-05-16 15:52:39 +00:00
|
|
|
if active:
|
|
|
|
banned[request_ip] = banned.get(request_ip, 0)
|
|
|
|
banned[request_ip] += 1
|
2021-11-05 13:55:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
def decrease(request_ip):
|
|
|
|
if banned[request_ip] > 0:
|
|
|
|
banned[request_ip] -= 1
|
|
|
|
|
|
|
|
|
|
|
|
def has_violation(request_ip):
|
|
|
|
return request_ip in banned and banned[request_ip] > 0
|
2021-05-16 15:50:22 +00:00
|
|
|
|
2021-05-18 03:41:02 +00:00
|
|
|
|
2021-05-16 15:50:22 +00:00
|
|
|
def is_banned(request_ip):
|
|
|
|
# More than X offences?
|
2021-05-16 15:59:39 +00:00
|
|
|
return active and banned.get(request_ip, 0) >= threshold
|