175 lines
5.4 KiB
Python
175 lines
5.4 KiB
Python
"""
|
|
设置路由
|
|
"""
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from pydantic import BaseModel
|
|
|
|
from database import get_db
|
|
from models import User
|
|
from schemas import CookieSetting, SystemStatus
|
|
from auth import get_current_user
|
|
from fumamx_cli import update_cookie, COOKIE_FILE, check_cookie_valid
|
|
|
|
router = APIRouter(prefix="/settings", tags=["设置"])
|
|
|
|
# Token 文件路径
|
|
TOKEN_CONFIG_FILE = "/home/ubuntu/nanocode/fumamxCLI/src/config.py"
|
|
|
|
|
|
class TokenSetting(BaseModel):
|
|
access_token: str
|
|
individual_access_token: str
|
|
|
|
|
|
def read_tokens_from_config():
|
|
"""从 config.py 读取当前 token"""
|
|
tokens = {
|
|
"access_token": "",
|
|
"individual_access_token": ""
|
|
}
|
|
try:
|
|
with open(TOKEN_CONFIG_FILE, 'r') as f:
|
|
content = f.read()
|
|
|
|
# 解析 ACCESS_TOKEN
|
|
import re
|
|
access_match = re.search(r'ACCESS_TOKEN\s*=\s*["\']([^"\']+)["\']', content)
|
|
if access_match:
|
|
tokens["access_token"] = access_match.group(1)
|
|
|
|
# 解析 INDIVIDUAL_ACCESS_TOKEN
|
|
individual_match = re.search(r'INDIVIDUAL_ACCESS_TOKEN\s*=\s*["\']([^"\']+)["\']', content)
|
|
if individual_match:
|
|
tokens["individual_access_token"] = individual_match.group(1)
|
|
|
|
except Exception as e:
|
|
print(f"读取 token 失败: {e}")
|
|
|
|
return tokens
|
|
|
|
|
|
def write_tokens_to_config(access_token: str, individual_access_token: str):
|
|
"""写入 token 到 config.py"""
|
|
try:
|
|
with open(TOKEN_CONFIG_FILE, 'r') as f:
|
|
content = f.read()
|
|
|
|
import re
|
|
# 替换 ACCESS_TOKEN
|
|
content = re.sub(
|
|
r'ACCESS_TOKEN\s*=\s*["\'][^"\']*["\']',
|
|
f'ACCESS_TOKEN = "{access_token}"',
|
|
content
|
|
)
|
|
|
|
# 替换 INDIVIDUAL_ACCESS_TOKEN
|
|
content = re.sub(
|
|
r'INDIVIDUAL_ACCESS_TOKEN\s*=\s*["\'][^"\']*["\']',
|
|
f'INDIVIDUAL_ACCESS_TOKEN = "{individual_access_token}"',
|
|
content
|
|
)
|
|
|
|
with open(TOKEN_CONFIG_FILE, 'w') as f:
|
|
f.write(content)
|
|
|
|
return True
|
|
except Exception as e:
|
|
print(f"写入 token 失败: {e}")
|
|
return False
|
|
|
|
|
|
def check_tokens_valid() -> bool:
|
|
"""检查 token 是否有效"""
|
|
tokens = read_tokens_from_config()
|
|
return bool(tokens["access_token"] and tokens["individual_access_token"])
|
|
|
|
|
|
@router.get("/status", response_model=SystemStatus)
|
|
def get_status(current_user: User = Depends(get_current_user)):
|
|
"""获取系统状态"""
|
|
cookie_valid = check_cookie_valid()
|
|
tokens_valid = check_tokens_valid()
|
|
return {
|
|
"logged_in": True,
|
|
"user": current_user.username,
|
|
"cookie_valid": cookie_valid,
|
|
"tokens_valid": tokens_valid
|
|
}
|
|
|
|
|
|
@router.post("/cookie")
|
|
def set_cookie(
|
|
data: CookieSetting,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""设置 cookie"""
|
|
try:
|
|
# 验证是否为有效的 JSON
|
|
import json
|
|
cookie_data = json.loads(data.cookie_content)
|
|
|
|
# 保存到文件
|
|
with open(COOKIE_FILE, 'w') as f:
|
|
json.dump(cookie_data, f, indent=2)
|
|
|
|
# 验证 cookie 有效性
|
|
if check_cookie_valid():
|
|
return {"message": "Cookie 设置成功并验证通过"}
|
|
else:
|
|
return {"message": "Cookie 已保存,但验证失败,请检查内容"}
|
|
|
|
except json.JSONDecodeError:
|
|
raise HTTPException(status_code=400, detail="无效的 JSON 格式")
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=f"保存失败: {str(e)}")
|
|
|
|
|
|
@router.get("/cookie")
|
|
def get_cookie(current_user: User = Depends(get_current_user)):
|
|
"""获取当前 cookie(脱敏)"""
|
|
try:
|
|
with open(COOKIE_FILE, 'r') as f:
|
|
import json
|
|
cookies = json.load(f)
|
|
|
|
# 脱敏处理
|
|
safe_cookies = []
|
|
for c in cookies:
|
|
safe_cookies.append({
|
|
"name": c.get("name"),
|
|
"domain": c.get("domain"),
|
|
"value_preview": c.get("value", "")[:10] + "..." if len(c.get("value", "")) > 10 else c.get("value")
|
|
})
|
|
|
|
return {"cookies": safe_cookies}
|
|
except Exception as e:
|
|
return {"cookies": [], "error": str(e)}
|
|
|
|
|
|
@router.get("/tokens")
|
|
def get_tokens(current_user: User = Depends(get_current_user)):
|
|
"""获取当前 Token(脱敏显示)"""
|
|
tokens = read_tokens_from_config()
|
|
# 脱敏处理
|
|
return {
|
|
"access_token": tokens["access_token"][:8] + "..." if len(tokens["access_token"]) > 8 else tokens["access_token"],
|
|
"individual_access_token": tokens["individual_access_token"][:8] + "..." if len(tokens["individual_access_token"]) > 8 else tokens["individual_access_token"],
|
|
"has_tokens": bool(tokens["access_token"] and tokens["individual_access_token"])
|
|
}
|
|
|
|
|
|
@router.post("/tokens")
|
|
def set_tokens(
|
|
data: TokenSetting,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""设置 Token"""
|
|
if not data.access_token.strip() or not data.individual_access_token.strip():
|
|
raise HTTPException(status_code=400, detail="Token 不能为空")
|
|
|
|
if write_tokens_to_config(data.access_token.strip(), data.individual_access_token.strip()):
|
|
return {"message": "Token 设置成功"}
|
|
else:
|
|
raise HTTPException(status_code=500, detail="Token 保存失败")
|