eishit32 commited on
Commit
e18662a
·
verified ·
1 Parent(s): 0fc3983

Update auth.py

Browse files
Files changed (1) hide show
  1. auth.py +25 -15
auth.py CHANGED
@@ -1,34 +1,44 @@
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
 
 
 
1
  from fastapi import Header, HTTPException
2
+ from firebase_admin import firestore
3
  import time
4
 
5
+ db = firestore.client()
 
 
 
 
6
 
7
+ # in-memory rate tracking (later move to Redis)
8
+ REQUEST_LOG = {}
9
 
10
 
11
  def verify_api_key(x_api_key: str = Header(...)):
12
+ # 1. Check key exists
13
+ doc = db.collection("api_keys").document(x_api_key).get()
14
 
15
+ if not doc.exists:
16
+ raise HTTPException(status_code=401, detail="Invalid API key")
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
+ plan = data.get("plan", "pro")
25
+ limit = data.get("limit", 50000)
26
+
27
+ # 3. Rate limit
28
  now = int(time.time())
29
+ window = 60 # 1 min
30
 
31
+ logs = REQUEST_LOG.get(x_api_key, [])
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 ({plan} plan)"
38
  )
39
 
40
  logs.append(now)
41
+ REQUEST_LOG[x_api_key] = logs
42
+
43
+ return data
44
+