-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
95 lines (75 loc) · 2.52 KB
/
auth.py
File metadata and controls
95 lines (75 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
API Key Authentication & Credit Management
==========================================
Simple in-memory implementation for demo purposes.
Replace with database in production.
"""
from fastapi import HTTPException, Header
from typing import Optional
# ============================================
# In-memory storage (replace with database)
# ============================================
# Demo API keys with starting credits
users_db = {
"demo_api_key_12345": {
"credits": 10,
"email": "demo@example.com"
}
}
# ============================================
# Authentication
# ============================================
async def verify_api_key(x_api_key: Optional[str] = Header(None)) -> str:
"""
Verify API key from X-API-Key header.
In production, validate against database.
"""
if not x_api_key:
raise HTTPException(
status_code=401,
detail={
"error": "missing_api_key",
"message": "X-API-Key header is required"
}
)
# For demo: accept any key and create user if not exists
if x_api_key not in users_db:
# Auto-create user with 5 free credits
users_db[x_api_key] = {
"credits": 5,
"email": None
}
print(f"🆕 New user created: {x_api_key[:8]}... (5 free credits)")
return x_api_key
# ============================================
# Credit Management
# ============================================
def get_user_credits(api_key: str) -> int:
"""Get current credit balance for user"""
if api_key not in users_db:
return 0
return users_db[api_key]["credits"]
def deduct_credits(api_key: str, amount: int) -> int:
"""
Deduct credits from user account.
Returns remaining credits.
"""
if api_key not in users_db:
raise HTTPException(status_code=401, detail="Invalid API key")
current = users_db[api_key]["credits"]
if current < amount:
raise HTTPException(
status_code=402,
detail=f"Insufficient credits. Have: {current}, Need: {amount}"
)
users_db[api_key]["credits"] = current - amount
return users_db[api_key]["credits"]
def add_credits(api_key: str, amount: int) -> int:
"""
Add credits to user account (after payment).
Returns new balance.
"""
if api_key not in users_db:
users_db[api_key] = {"credits": 0, "email": None}
users_db[api_key]["credits"] += amount
return users_db[api_key]["credits"]