eishit32 commited on
Commit
4d59f18
·
verified ·
1 Parent(s): 80d4072

Create auth.py

Browse files
Files changed (1) hide show
  1. auth.py +34 -0
auth.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Header, HTTPException
2
+ import time
3
+
4
+ # ⚡ Demo in-memory keys (replace with DB later)
5
+ API_KEYS = {
6
+ "free_key_123": {"plan": "free", "limit": 100},
7
+ "pro_key_456": {"plan": "pro", "limit": 10000},
8
+ }
9
+
10
+ request_log = {}
11
+
12
+
13
+ def verify_api_key(x_api_key: str = Header(...)):
14
+ if x_api_key not in API_KEYS:
15
+ raise HTTPException(status_code=401, detail="Invalid API Key")
16
+
17
+ plan = API_KEYS[x_api_key]["plan"]
18
+ limit = API_KEYS[x_api_key]["limit"]
19
+
20
+ now = int(time.time())
21
+ window = 60 # 1 minute window
22
+
23
+ logs = request_log.get(x_api_key, [])
24
+ logs = [t for t in logs if now - t < window]
25
+
26
+ if len(logs) >= limit:
27
+ raise HTTPException(
28
+ status_code=429,
29
+ detail=f"Rate limit exceeded for {plan} plan"
30
+ )
31
+
32
+ logs.append(now)
33
+ request_log[x_api_key] = logs
34
+ return True