This commit is contained in:
1 parent
8f3fd04618
commit
2d3ff21222
17 files changed
+1566
-136
No files matched your search
+223
-16
@@ -4,20 +4,38 @@ from urllib.parse import urlparse
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
|
||||
from pydantic import BaseModel
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .ai_config import get_ai_status, get_config_value, load_local_whisper_config, load_text_ai_config
|
||||
from .auth import (
|
||||
create_auth_token,
|
||||
generate_activation_code,
|
||||
hash_password,
|
||||
normalize_username,
|
||||
verify_auth_token,
|
||||
verify_password,
|
||||
)
|
||||
from .db import (
|
||||
DATABASE_PATH,
|
||||
create_activation_codes,
|
||||
create_video,
|
||||
delete_video,
|
||||
delete_unused_activation_code,
|
||||
get_user_auth_record,
|
||||
get_user_by_id,
|
||||
initialize_database,
|
||||
list_activation_codes,
|
||||
list_users,
|
||||
list_videos,
|
||||
mark_user_login,
|
||||
parse_tags,
|
||||
register_user_with_activation,
|
||||
table_names,
|
||||
get_video,
|
||||
update_user_active,
|
||||
update_video,
|
||||
upsert_video_subtitle,
|
||||
)
|
||||
@@ -134,6 +152,26 @@ ensure_upload_directories()
|
||||
|
||||
app = FastAPI(title="Speaking Lab API")
|
||||
admin_security = HTTPBasic(auto_error=False)
|
||||
bearer_security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
activationCode: str
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class GenerateActivationCodesRequest(BaseModel):
|
||||
quantity: int = 1
|
||||
|
||||
|
||||
class UpdateUserStatusRequest(BaseModel):
|
||||
isActive: bool
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
@@ -167,7 +205,126 @@ def api_get_video(video_id: int) -> dict[str, object]:
|
||||
return video
|
||||
|
||||
|
||||
def require_admin(credentials: HTTPBasicCredentials | None = Depends(admin_security)) -> dict[str, str]:
|
||||
def get_token_secret() -> str:
|
||||
configured = get_config_value("AUTH_SECRET")
|
||||
if configured:
|
||||
return configured
|
||||
admin_password = get_config_value("ADMIN_PASSWORD")
|
||||
return admin_password or "speaking-lab-development-secret"
|
||||
|
||||
|
||||
def build_user_response(username: str, role: str, user_id: int | None = None) -> dict[str, object]:
|
||||
return {
|
||||
"id": user_id,
|
||||
"username": username,
|
||||
"role": role,
|
||||
}
|
||||
|
||||
|
||||
def create_session_payload(username: str, role: str, user_id: int | None = None) -> dict[str, object]:
|
||||
token = create_auth_token(
|
||||
{
|
||||
"username": username,
|
||||
"role": role,
|
||||
"userId": user_id,
|
||||
},
|
||||
get_token_secret(),
|
||||
)
|
||||
return {
|
||||
"token": token,
|
||||
"user": build_user_response(username, role, user_id),
|
||||
}
|
||||
|
||||
|
||||
def validate_bearer_session(token: str) -> dict[str, object] | None:
|
||||
payload = verify_auth_token(token, get_token_secret())
|
||||
if not payload:
|
||||
return None
|
||||
|
||||
role = str(payload.get("role") or "")
|
||||
username = str(payload.get("username") or "")
|
||||
if role == "admin" and username:
|
||||
return build_user_response(username, "admin", None)
|
||||
|
||||
user_id = int(payload.get("userId") or 0)
|
||||
user = get_user_by_id(user_id) if user_id else None
|
||||
if not user or not user["isActive"]:
|
||||
return None
|
||||
if user["username"] != username:
|
||||
return None
|
||||
return build_user_response(str(user["username"]), str(user["role"]), int(user["id"]))
|
||||
|
||||
|
||||
def require_session(credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security)) -> dict[str, object]:
|
||||
if credentials is None:
|
||||
raise HTTPException(status_code=401, detail="请先登录。")
|
||||
|
||||
session = validate_bearer_session(credentials.credentials)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=401, detail="登录已失效,请重新登录。")
|
||||
return session
|
||||
|
||||
|
||||
@app.post("/api/auth/login")
|
||||
def api_auth_login(request: LoginRequest) -> dict[str, object]:
|
||||
username = normalize_username(request.username)
|
||||
password = request.password
|
||||
if not username or not password:
|
||||
raise HTTPException(status_code=400, detail="请输入账号和密码。")
|
||||
|
||||
admin_username = normalize_username(get_config_value("ADMIN_USERNAME"))
|
||||
admin_password = get_config_value("ADMIN_PASSWORD")
|
||||
if admin_username and admin_password and username == admin_username:
|
||||
if not secrets.compare_digest(password, admin_password):
|
||||
raise HTTPException(status_code=401, detail="账号或密码错误。")
|
||||
return create_session_payload(admin_username, "admin")
|
||||
|
||||
user = get_user_auth_record(username)
|
||||
if user is None or not verify_password(password, user["password_hash"]):
|
||||
raise HTTPException(status_code=401, detail="账号或密码错误。")
|
||||
if not bool(user["is_active"]):
|
||||
raise HTTPException(status_code=403, detail="账号已停用,请联系管理员。")
|
||||
|
||||
mark_user_login(int(user["id"]))
|
||||
return create_session_payload(str(user["email"]), str(user["role"]), int(user["id"]))
|
||||
|
||||
|
||||
@app.post("/api/auth/register")
|
||||
def api_auth_register(request: RegisterRequest) -> dict[str, object]:
|
||||
username = normalize_username(request.username)
|
||||
password = request.password
|
||||
activation_code = request.activationCode.strip().upper()
|
||||
if not activation_code:
|
||||
raise HTTPException(status_code=400, detail="请输入激活卡密。")
|
||||
if not username or not password:
|
||||
raise HTTPException(status_code=400, detail="请输入账号和密码。")
|
||||
if len(password) < 6:
|
||||
raise HTTPException(status_code=400, detail="密码至少需要 6 位。")
|
||||
|
||||
try:
|
||||
user = register_user_with_activation(
|
||||
username=username,
|
||||
password_hash=hash_password(password),
|
||||
activation_code=activation_code,
|
||||
)
|
||||
except ValueError as error:
|
||||
if str(error) == "username_exists":
|
||||
raise HTTPException(status_code=409, detail="账号已存在。") from error
|
||||
raise HTTPException(status_code=400, detail="激活卡密无效或已被使用。") from error
|
||||
|
||||
mark_user_login(int(user["id"]))
|
||||
return create_session_payload(str(user["username"]), str(user["role"]), int(user["id"]))
|
||||
|
||||
|
||||
@app.get("/api/auth/session")
|
||||
def api_auth_session(session: dict[str, object] = Depends(require_session)) -> dict[str, object]:
|
||||
return {"ok": True, "user": session}
|
||||
|
||||
|
||||
def require_admin(
|
||||
credentials: HTTPBasicCredentials | None = Depends(admin_security),
|
||||
bearer: HTTPAuthorizationCredentials | None = Depends(bearer_security),
|
||||
) -> dict[str, str]:
|
||||
admin_username = get_config_value("ADMIN_USERNAME")
|
||||
admin_password = get_config_value("ADMIN_PASSWORD")
|
||||
|
||||
@@ -177,26 +334,76 @@ def require_admin(credentials: HTTPBasicCredentials | None = Depends(admin_secur
|
||||
detail="未配置 ADMIN_USERNAME / ADMIN_PASSWORD,请先在 .env 中填写管理员账号密码。",
|
||||
)
|
||||
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="需要管理员账号密码。",
|
||||
)
|
||||
if credentials is not None:
|
||||
username_ok = secrets.compare_digest(credentials.username, admin_username)
|
||||
password_ok = secrets.compare_digest(credentials.password, admin_password)
|
||||
if username_ok and password_ok:
|
||||
return {"username": admin_username, "role": "admin"}
|
||||
|
||||
username_ok = secrets.compare_digest(credentials.username, admin_username)
|
||||
password_ok = secrets.compare_digest(credentials.password, admin_password)
|
||||
if not username_ok or not password_ok:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="管理员账号或密码错误。",
|
||||
)
|
||||
if bearer is not None and hasattr(bearer, "credentials"):
|
||||
session = validate_bearer_session(bearer.credentials)
|
||||
if session and session["role"] == "admin":
|
||||
return {"username": str(session["username"]), "role": "admin"}
|
||||
|
||||
return {"username": admin_username}
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="需要管理员账号。",
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/admin/session")
|
||||
def api_admin_session(admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]:
|
||||
return {"ok": True, "username": admin["username"]}
|
||||
return {"ok": True, "username": admin["username"], "role": "admin"}
|
||||
|
||||
|
||||
@app.get("/api/admin/users")
|
||||
def api_admin_users(admin: dict[str, str] = Depends(require_admin)) -> list[dict[str, object]]:
|
||||
return list_users()
|
||||
|
||||
|
||||
@app.patch("/api/admin/users/{user_id}")
|
||||
def api_admin_update_user(
|
||||
user_id: int,
|
||||
request: UpdateUserStatusRequest,
|
||||
admin: dict[str, str] = Depends(require_admin),
|
||||
) -> dict[str, object]:
|
||||
user = update_user_active(user_id, request.isActive)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail="用户不存在,或不能修改管理员账号。")
|
||||
return {"ok": True, "user": user}
|
||||
|
||||
|
||||
@app.get("/api/admin/activation-codes")
|
||||
def api_admin_activation_codes(admin: dict[str, str] = Depends(require_admin)) -> list[dict[str, object]]:
|
||||
return list_activation_codes()
|
||||
|
||||
|
||||
@app.post("/api/admin/activation-codes")
|
||||
def api_admin_create_activation_codes(
|
||||
request: GenerateActivationCodesRequest,
|
||||
admin: dict[str, str] = Depends(require_admin),
|
||||
) -> dict[str, object]:
|
||||
if request.quantity < 1 or request.quantity > 100:
|
||||
raise HTTPException(status_code=400, detail="一次只能生成 1 到 100 个卡密。")
|
||||
|
||||
codes: list[str] = []
|
||||
while len(codes) < request.quantity:
|
||||
code = generate_activation_code()
|
||||
if code not in codes:
|
||||
codes.append(code)
|
||||
|
||||
created = create_activation_codes(codes, admin["username"])
|
||||
return {"ok": True, "codes": created}
|
||||
|
||||
|
||||
@app.delete("/api/admin/activation-codes/{code_id}")
|
||||
def api_admin_delete_activation_code(
|
||||
code_id: int,
|
||||
admin: dict[str, str] = Depends(require_admin),
|
||||
) -> dict[str, object]:
|
||||
if not delete_unused_activation_code(code_id):
|
||||
raise HTTPException(status_code=400, detail="已使用的卡密不能删除。")
|
||||
return {"ok": True, "deletedCodeId": code_id}
|
||||
|
||||
|
||||
@app.post("/api/videos")
|
||||
|
||||
Reference in new issue
Block a user