Bader Alabddan commited on
Commit
2cc9918
·
1 Parent(s): beefe31

Initial commit: Billing Auth Gateway

Browse files
Files changed (8) hide show
  1. Dockerfile +12 -0
  2. app.py +142 -0
  3. auth.py +74 -0
  4. data/api_keys.json +12 -0
  5. deploy_to_hf.py +47 -0
  6. key_generator.py +64 -0
  7. requirements.txt +4 -0
  8. utils/encryption.py +20 -0
Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ EXPOSE 7860
11
+
12
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Request
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import json
5
+ import os
6
+ from datetime import datetime
7
+ from auth import validate_api_key, get_key_info
8
+ from key_generator import generate_api_key
9
+
10
+ app = FastAPI(title="Billing & Auth Gateway", version="1.0.0")
11
+
12
+ # Enable CORS
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ # Request models
22
+ class GenerateKeyRequest(BaseModel):
23
+ plan_tier: str
24
+ user_email: str = "demo@example.com"
25
+
26
+ class ValidateKeyRequest(BaseModel):
27
+ api_key: str
28
+
29
+ class RevokeKeyRequest(BaseModel):
30
+ api_key: str
31
+
32
+ @app.get("/")
33
+ async def root():
34
+ return {
35
+ "service": "Billing & Auth Gateway",
36
+ "version": "1.0.0",
37
+ "status": "operational",
38
+ "endpoints": [
39
+ "/api/generate_key",
40
+ "/api/validate_key",
41
+ "/api/revoke_key",
42
+ "/api/key_info/{api_key}",
43
+ "/health"
44
+ ]
45
+ }
46
+
47
+ @app.post("/api/generate_key")
48
+ async def generate_key(request: GenerateKeyRequest):
49
+ """Generate a new API key"""
50
+ try:
51
+ result = generate_api_key(request.plan_tier, request.user_email)
52
+ return {
53
+ "api_key": result["api_key"],
54
+ "plan_tier": result["plan_tier"],
55
+ "calls_limit": result["calls_limit"],
56
+ "created_date": result["created_date"],
57
+ "status": "success"
58
+ }
59
+ except Exception as e:
60
+ raise HTTPException(status_code=500, detail=str(e))
61
+
62
+ @app.post("/api/validate_key")
63
+ async def validate_key(request: ValidateKeyRequest):
64
+ """Validate an API key"""
65
+ result = validate_api_key(request.api_key)
66
+
67
+ if not result["valid"]:
68
+ return {
69
+ "valid": False,
70
+ "error": "Invalid API key",
71
+ "status": "error"
72
+ }
73
+
74
+ return {
75
+ "valid": True,
76
+ "plan_tier": result["plan_tier"],
77
+ "calls_limit": result["calls_limit"],
78
+ "calls_used": result["calls_used"],
79
+ "active": result["active"],
80
+ "status": "success"
81
+ }
82
+
83
+ @app.post("/api/revoke_key")
84
+ async def revoke_key(request: RevokeKeyRequest):
85
+ """Revoke an API key"""
86
+ try:
87
+ # Load existing keys
88
+ keys_file = "data/api_keys.json"
89
+ if os.path.exists(keys_file):
90
+ with open(keys_file, 'r') as f:
91
+ keys = json.load(f)
92
+ else:
93
+ return {"revoked": False, "error": "Key not found", "status": "error"}
94
+
95
+ # Find and revoke key
96
+ key_found = False
97
+ for key in keys:
98
+ if key["api_key"] == request.api_key:
99
+ key["active"] = False
100
+ key_found = True
101
+ break
102
+
103
+ if not key_found:
104
+ return {"revoked": False, "error": "Key not found", "status": "error"}
105
+
106
+ # Save updated keys
107
+ with open(keys_file, 'w') as f:
108
+ json.dump(keys, f, indent=2)
109
+
110
+ return {"revoked": True, "status": "success"}
111
+ except Exception as e:
112
+ raise HTTPException(status_code=500, detail=str(e))
113
+
114
+ @app.get("/api/key_info/{api_key}")
115
+ async def key_info(api_key: str):
116
+ """Get information about an API key"""
117
+ info = get_key_info(api_key)
118
+
119
+ if not info:
120
+ raise HTTPException(status_code=404, detail="Key not found")
121
+
122
+ return {
123
+ "plan_tier": info["plan_tier"],
124
+ "calls_limit": info["calls_limit"],
125
+ "calls_used": info["calls_used"],
126
+ "created_date": info["created_date"],
127
+ "active": info["active"],
128
+ "status": "success"
129
+ }
130
+
131
+ @app.get("/health")
132
+ async def health():
133
+ return {
134
+ "status": "healthy",
135
+ "service": "billing-auth-gateway",
136
+ "version": "1.0.0",
137
+ "timestamp": datetime.now().isoformat()
138
+ }
139
+
140
+ if __name__ == "__main__":
141
+ import uvicorn
142
+ uvicorn.run(app, host="0.0.0.0", port=7860)
auth.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ def validate_api_key(api_key):
5
+ """
6
+ Validate an API key
7
+
8
+ Args:
9
+ api_key: API key to validate
10
+
11
+ Returns:
12
+ dict with validation result and key information
13
+ """
14
+ keys_file = "data/api_keys.json"
15
+
16
+ # Check if keys file exists
17
+ if not os.path.exists(keys_file):
18
+ return {"valid": False}
19
+
20
+ # Load keys
21
+ try:
22
+ with open(keys_file, 'r') as f:
23
+ keys = json.load(f)
24
+ except Exception as e:
25
+ return {"valid": False}
26
+
27
+ # Find key
28
+ for key in keys:
29
+ if key["api_key"] == api_key:
30
+ if not key.get("active", True):
31
+ return {"valid": False}
32
+
33
+ return {
34
+ "valid": True,
35
+ "plan_tier": key["plan_tier"],
36
+ "calls_limit": key["calls_limit"],
37
+ "calls_used": key.get("calls_used", 0),
38
+ "active": key.get("active", True)
39
+ }
40
+
41
+ return {"valid": False}
42
+
43
+ def get_key_info(api_key):
44
+ """
45
+ Get information about an API key
46
+
47
+ Args:
48
+ api_key: API key to look up
49
+
50
+ Returns:
51
+ dict with key information or None if not found
52
+ """
53
+ keys_file = "data/api_keys.json"
54
+
55
+ if not os.path.exists(keys_file):
56
+ return None
57
+
58
+ try:
59
+ with open(keys_file, 'r') as f:
60
+ keys = json.load(f)
61
+ except Exception as e:
62
+ return None
63
+
64
+ for key in keys:
65
+ if key["api_key"] == api_key:
66
+ return {
67
+ "plan_tier": key["plan_tier"],
68
+ "calls_limit": key["calls_limit"],
69
+ "calls_used": key.get("calls_used", 0),
70
+ "created_date": key["created_date"],
71
+ "active": key.get("active", True)
72
+ }
73
+
74
+ return None
data/api_keys.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "key_id": "key_demo_001",
4
+ "api_key": "bdr_test_demo_key_12345",
5
+ "plan_tier": "Pro",
6
+ "user_email": "demo@bdr-ai.com",
7
+ "created_date": "2026-01-08",
8
+ "calls_limit": 10000,
9
+ "calls_used": 0,
10
+ "active": true
11
+ }
12
+ ]
deploy_to_hf.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import sys
4
+ from huggingface_hub import HfApi, create_repo
5
+
6
+ def deploy_to_huggingface():
7
+ repo_name = "billing-auth-gateway"
8
+ username = "BDR-AI"
9
+ repo_id = f"{username}/{repo_name}"
10
+
11
+ hf_token = os.environ.get("HF_TOKEN")
12
+ if not hf_token:
13
+ print("Error: HF_TOKEN environment variable not set")
14
+ sys.exit(1)
15
+
16
+ print(f"Deploying {repo_name} to Hugging Face Spaces...")
17
+
18
+ try:
19
+ api = HfApi(token=hf_token)
20
+ create_repo(repo_id=repo_id, repo_type="space", space_sdk="docker", token=hf_token, exist_ok=True)
21
+ print(f"✓ Repository {repo_id} created/verified")
22
+
23
+ files_to_upload = [
24
+ "app.py",
25
+ "auth.py",
26
+ "key_generator.py",
27
+ "requirements.txt",
28
+ "README.md",
29
+ "data/api_keys.json",
30
+ "utils/encryption.py"
31
+ ]
32
+
33
+ for file_path in files_to_upload:
34
+ try:
35
+ api.upload_file(path_or_fileobj=file_path, path_in_repo=file_path, repo_id=repo_id, repo_type="space", token=hf_token)
36
+ print(f"✓ Uploaded {file_path}")
37
+ except Exception as e:
38
+ print(f"✗ Failed to upload {file_path}: {e}")
39
+
40
+ print(f"\n✓ Deployment complete!")
41
+ print(f"View your space at: https://huggingface.co/spaces/{repo_id}")
42
+ except Exception as e:
43
+ print(f"✗ Deployment failed: {e}")
44
+ sys.exit(1)
45
+
46
+ if __name__ == "__main__":
47
+ deploy_to_huggingface()
key_generator.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import secrets
4
+ from datetime import datetime
5
+
6
+ def generate_api_key(plan_tier, user_email):
7
+ """
8
+ Generate a new API key
9
+
10
+ Args:
11
+ plan_tier: Plan tier (Free, Starter, Pro)
12
+ user_email: User email address
13
+
14
+ Returns:
15
+ dict with api_key and key information
16
+ """
17
+ # Validate plan tier
18
+ valid_tiers = ["Free", "Starter", "Pro"]
19
+ if plan_tier not in valid_tiers:
20
+ raise ValueError(f"Invalid plan tier. Must be one of: {', '.join(valid_tiers)}")
21
+
22
+ # Set calls limit based on plan
23
+ calls_limits = {
24
+ "Free": 100,
25
+ "Starter": 1000,
26
+ "Pro": 10000
27
+ }
28
+ calls_limit = calls_limits[plan_tier]
29
+
30
+ # Generate unique API key
31
+ key_prefix = "bdr_test_" if plan_tier == "Free" else "bdr_prod_"
32
+ random_part = secrets.token_urlsafe(16)
33
+ api_key = f"{key_prefix}{random_part}"
34
+
35
+ # Create key data
36
+ key_data = {
37
+ "key_id": f"key_{secrets.token_hex(4)}",
38
+ "api_key": api_key,
39
+ "plan_tier": plan_tier,
40
+ "user_email": user_email,
41
+ "created_date": datetime.now().strftime("%Y-%m-%d"),
42
+ "calls_limit": calls_limit,
43
+ "calls_used": 0,
44
+ "active": True
45
+ }
46
+
47
+ # Load existing keys
48
+ keys_file = "data/api_keys.json"
49
+ os.makedirs("data", exist_ok=True)
50
+
51
+ if os.path.exists(keys_file):
52
+ with open(keys_file, 'r') as f:
53
+ keys = json.load(f)
54
+ else:
55
+ keys = []
56
+
57
+ # Add new key
58
+ keys.append(key_data)
59
+
60
+ # Save keys
61
+ with open(keys_file, 'w') as f:
62
+ json.dump(keys, f, indent=2)
63
+
64
+ return key_data
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi==0.109.0
2
+ uvicorn==0.27.0
3
+ pydantic==2.5.3
4
+ python-multipart==0.0.6
utils/encryption.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import secrets
3
+
4
+ def hash_api_key(api_key):
5
+ """Hash an API key for secure storage"""
6
+ return hashlib.sha256(api_key.encode()).hexdigest()
7
+
8
+ def generate_secure_token(length=32):
9
+ """Generate a secure random token"""
10
+ return secrets.token_urlsafe(length)
11
+
12
+ def verify_key_format(api_key):
13
+ """Verify API key format"""
14
+ if not api_key:
15
+ return False
16
+ if not api_key.startswith(("bdr_test_", "bdr_prod_")):
17
+ return False
18
+ if len(api_key) < 20:
19
+ return False
20
+ return True