eishit32 commited on
Commit
dc9c85b
·
verified ·
1 Parent(s): 43a618c

Update auth.py

Browse files
Files changed (1) hide show
  1. auth.py +18 -25
auth.py CHANGED
@@ -1,44 +1,37 @@
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
 
 
 
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