Spaces:
Sleeping
Sleeping
Update auth.py
Browse files
auth.py
CHANGED
|
@@ -1,44 +1,37 @@
|
|
| 1 |
from fastapi import Header, HTTPException
|
| 2 |
-
from firebase_admin import firestore
|
| 3 |
import time
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
REQUEST_LOG = {}
|
| 9 |
|
| 10 |
|
| 11 |
def verify_api_key(x_api_key: str = Header(...)):
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
data = doc.to_dict()
|
| 19 |
-
|
| 20 |
-
# 2. Check active
|
| 21 |
-
if not data.get("active", False):
|
| 22 |
-
raise HTTPException(status_code=403, detail="API key disabled")
|
| 23 |
|
| 24 |
-
|
| 25 |
-
limit = data.get("limit", 50000)
|
| 26 |
|
| 27 |
-
# 3. Rate limit
|
| 28 |
now = int(time.time())
|
| 29 |
-
window = 60 # 1
|
| 30 |
|
| 31 |
-
logs =
|
| 32 |
logs = [t for t in logs if now - t < window]
|
| 33 |
|
| 34 |
-
if len(logs) >= limit:
|
| 35 |
raise HTTPException(
|
| 36 |
status_code=429,
|
| 37 |
-
detail=f"Rate limit exceeded
|
| 38 |
)
|
| 39 |
|
| 40 |
logs.append(now)
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
return data
|
| 44 |
|
|
|
|
|
|
| 1 |
from fastapi import Header, HTTPException
|
|
|
|
| 2 |
import time
|
| 3 |
|
| 4 |
+
# Demo API keys (later move to DB)
|
| 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(
|
| 16 |
+
status_code=401,
|
| 17 |
+
detail="Invalid API Key"
|
| 18 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
key_data = API_KEYS[x_api_key]
|
|
|
|
| 21 |
|
|
|
|
| 22 |
now = int(time.time())
|
| 23 |
+
window = 60 # 1 minute window
|
| 24 |
|
| 25 |
+
logs = request_log.get(x_api_key, [])
|
| 26 |
logs = [t for t in logs if now - t < window]
|
| 27 |
|
| 28 |
+
if len(logs) >= key_data["limit"]:
|
| 29 |
raise HTTPException(
|
| 30 |
status_code=429,
|
| 31 |
+
detail=f"Rate limit exceeded for {key_data['plan']} plan"
|
| 32 |
)
|
| 33 |
|
| 34 |
logs.append(now)
|
| 35 |
+
request_log[x_api_key] = logs
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
return key_data
|