UPNISO_API / auth.py
eishit32's picture
Update auth.py
dc9c85b verified
Raw
History Blame Contribute Delete
864 Bytes
from fastapi import Header, HTTPException
import time
# Demo API keys (later move to DB)
API_KEYS = {
"free_key_123": {"plan": "free", "limit": 100},
"pro_key_456": {"plan": "pro", "limit": 10000},
}
request_log = {}
def verify_api_key(x_api_key: str = Header(...)):
if x_api_key not in API_KEYS:
raise HTTPException(
status_code=401,
detail="Invalid API Key"
)
key_data = API_KEYS[x_api_key]
now = int(time.time())
window = 60 # 1 minute window
logs = request_log.get(x_api_key, [])
logs = [t for t in logs if now - t < window]
if len(logs) >= key_data["limit"]:
raise HTTPException(
status_code=429,
detail=f"Rate limit exceeded for {key_data['plan']} plan"
)
logs.append(now)
request_log[x_api_key] = logs
return key_data