S-Dreamer commited on
Commit
ff24c30
·
verified ·
1 Parent(s): 1c34bfc

Create utils/security.py

Browse files
Files changed (1) hide show
  1. utils/security.py +30 -0
utils/security.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import hmac
3
+ import hashlib
4
+ from fastapi import HTTPException
5
+
6
+ REQUEST_LOG = {}
7
+ WINDOW_SECONDS = 10
8
+ MAX_REQUESTS = 6
9
+
10
+
11
+ def rate_limit(ip):
12
+ t = time.time()
13
+ entries = REQUEST_LOG.get(ip, [])
14
+ entries = [x for x in entries if t - x < WINDOW_SECONDS]
15
+
16
+ if len(entries) >= MAX_REQUESTS:
17
+ raise HTTPException(
18
+ status_code=429,
19
+ detail="Too many requests."
20
+ )
21
+
22
+ REQUEST_LOG[ip] = entries + [t]
23
+
24
+
25
+ def sign_payload(payload, secret):
26
+ return hmac.new(
27
+ secret.encode(),
28
+ payload.encode(),
29
+ hashlib.sha256
30
+ ).hexdigest()