Spaces:
Sleeping
Sleeping
v2 token key in db
Browse files- .gitignore +2 -1
- routes/v2.py +91 -1
.gitignore
CHANGED
|
@@ -1,2 +1,3 @@
|
|
| 1 |
__pycache__
|
| 2 |
-
test.db
|
|
|
|
|
|
| 1 |
__pycache__
|
| 2 |
+
test.db
|
| 3 |
+
database.db
|
routes/v2.py
CHANGED
|
@@ -1,9 +1,72 @@
|
|
| 1 |
import httpx
|
| 2 |
-
from fastapi import APIRouter, HTTPException, Request
|
| 3 |
import json
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
router = APIRouter()
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
@router.get("/")
|
| 8 |
async def v2():
|
| 9 |
return {"message": "Hello World from v2"}
|
|
@@ -26,6 +89,22 @@ async def proxy_request(protocol:str, url: str):
|
|
| 26 |
|
| 27 |
@router.post("/{protocol}/{url:path}")
|
| 28 |
async def proxy_post(protocol:str, url: str, request: Request):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
body = await request.body()
|
| 30 |
headers = dict(request.headers) # 将请求头转换为字典
|
| 31 |
|
|
@@ -39,6 +118,17 @@ async def proxy_post(protocol:str, url: str, request: Request):
|
|
| 39 |
|
| 40 |
dest_url = f"{protocol}://{url}"
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
async with httpx.AsyncClient() as client:
|
| 43 |
try:
|
| 44 |
# 向目标 URL 发送 POST 请求
|
|
|
|
| 1 |
import httpx
|
| 2 |
+
from fastapi import APIRouter, HTTPException, Request, Depends
|
| 3 |
import json
|
| 4 |
+
import random
|
| 5 |
+
import sqlite3
|
| 6 |
+
from datetime import datetime
|
| 7 |
|
| 8 |
router = APIRouter()
|
| 9 |
|
| 10 |
+
# SQLite database connection
|
| 11 |
+
def get_db_connection():
|
| 12 |
+
conn = sqlite3.connect('database.db')
|
| 13 |
+
conn.row_factory = sqlite3.Row
|
| 14 |
+
return conn
|
| 15 |
+
|
| 16 |
+
# Initialize database
|
| 17 |
+
def init_db():
|
| 18 |
+
conn = get_db_connection()
|
| 19 |
+
conn.execute('''
|
| 20 |
+
CREATE TABLE IF NOT EXISTS authorized_tokens (
|
| 21 |
+
token TEXT PRIMARY KEY,
|
| 22 |
+
expiration TEXT
|
| 23 |
+
)
|
| 24 |
+
''')
|
| 25 |
+
conn.execute('''
|
| 26 |
+
CREATE TABLE IF NOT EXISTS api_keys (
|
| 27 |
+
api_key TEXT PRIMARY KEY,
|
| 28 |
+
expiration TEXT
|
| 29 |
+
)
|
| 30 |
+
''')
|
| 31 |
+
conn.commit()
|
| 32 |
+
conn.close()
|
| 33 |
+
|
| 34 |
+
init_db()
|
| 35 |
+
|
| 36 |
+
# Import data to database
|
| 37 |
+
@router.post("/import/authorized_tokens")
|
| 38 |
+
async def import_authorized_tokens(tokens: dict):
|
| 39 |
+
conn = get_db_connection()
|
| 40 |
+
for token, expiration in tokens.items():
|
| 41 |
+
conn.execute('INSERT OR REPLACE INTO authorized_tokens (token, expiration) VALUES (?, ?)', (token, expiration))
|
| 42 |
+
conn.commit()
|
| 43 |
+
conn.close()
|
| 44 |
+
return {"message": "Authorized tokens imported successfully"}
|
| 45 |
+
|
| 46 |
+
@router.post("/import/api_keys")
|
| 47 |
+
async def import_api_keys(keys: dict):
|
| 48 |
+
conn = get_db_connection()
|
| 49 |
+
for api_key, expiration in keys.items():
|
| 50 |
+
conn.execute('INSERT OR REPLACE INTO api_keys (api_key, expiration) VALUES (?, ?)', (api_key, expiration))
|
| 51 |
+
conn.commit()
|
| 52 |
+
conn.close()
|
| 53 |
+
return {"message": "API keys imported successfully"}
|
| 54 |
+
|
| 55 |
+
# Export data from database
|
| 56 |
+
@router.get("/export/authorized_tokens")
|
| 57 |
+
async def export_authorized_tokens():
|
| 58 |
+
conn = get_db_connection()
|
| 59 |
+
tokens = conn.execute('SELECT * FROM authorized_tokens').fetchall()
|
| 60 |
+
conn.close()
|
| 61 |
+
return {token['token']: token['expiration'] for token in tokens}
|
| 62 |
+
|
| 63 |
+
@router.get("/export/api_keys")
|
| 64 |
+
async def export_api_keys():
|
| 65 |
+
conn = get_db_connection()
|
| 66 |
+
keys = conn.execute('SELECT * FROM api_keys').fetchall()
|
| 67 |
+
conn.close()
|
| 68 |
+
return {key['api_key']: key['expiration'] for key in keys}
|
| 69 |
+
|
| 70 |
@router.get("/")
|
| 71 |
async def v2():
|
| 72 |
return {"message": "Hello World from v2"}
|
|
|
|
| 89 |
|
| 90 |
@router.post("/{protocol}/{url:path}")
|
| 91 |
async def proxy_post(protocol:str, url: str, request: Request):
|
| 92 |
+
# 获取请求头中的Authorization字段
|
| 93 |
+
auth_header = request.headers.get("Authorization")
|
| 94 |
+
if not auth_header:
|
| 95 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 96 |
+
|
| 97 |
+
# 去掉Bearer前缀
|
| 98 |
+
token = auth_header.split(" ")[1] if "Bearer " in auth_header else auth_header
|
| 99 |
+
|
| 100 |
+
# 检查token是否过期
|
| 101 |
+
current_time = datetime.utcnow().isoformat()
|
| 102 |
+
conn = get_db_connection()
|
| 103 |
+
token_row = conn.execute('SELECT * FROM authorized_tokens WHERE token = ?', (token,)).fetchone()
|
| 104 |
+
conn.close()
|
| 105 |
+
if not token_row or token_row['expiration'] < current_time:
|
| 106 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 107 |
+
|
| 108 |
body = await request.body()
|
| 109 |
headers = dict(request.headers) # 将请求头转换为字典
|
| 110 |
|
|
|
|
| 118 |
|
| 119 |
dest_url = f"{protocol}://{url}"
|
| 120 |
|
| 121 |
+
# 随机选择一个有效的API Key
|
| 122 |
+
conn = get_db_connection()
|
| 123 |
+
keys = conn.execute('SELECT * FROM api_keys WHERE expiration >= ?', (current_time,)).fetchall()
|
| 124 |
+
conn.close()
|
| 125 |
+
if not keys:
|
| 126 |
+
raise HTTPException(status_code=503, detail="No valid API keys available")
|
| 127 |
+
selected_api_key = random.choice(keys)['api_key']
|
| 128 |
+
print(selected_api_key)
|
| 129 |
+
print(f"Bearer {selected_api_key}")
|
| 130 |
+
headers['Authorization'] = f"Bearer {selected_api_key}"
|
| 131 |
+
|
| 132 |
async with httpx.AsyncClient() as client:
|
| 133 |
try:
|
| 134 |
# 向目标 URL 发送 POST 请求
|