feat: add activation-code auth
Deploy Speaking Practice / deploy (push) Successful in 24s

This commit is contained in:
TTlaji committed 2026-06-05 16:56:30 +08:00
1 parent 8f3fd04618
commit 2d3ff21222
17 files changed
+1566 -136

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
import base64
import hashlib
import hmac
import json
import secrets
import time
PASSWORD_ALGORITHM = "pbkdf2_sha256"
PASSWORD_ITERATIONS = 120_000
TOKEN_TTL_SECONDS = 60 * 60 * 24 * 7
def _b64url_encode(value: bytes) -> str:
return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")
def _b64url_decode(value: str) -> bytes:
padding = "=" * (-len(value) % 4)
return base64.urlsafe_b64decode(value + padding)
def hash_password(password: str) -> str:
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
salt.encode("ascii"),
PASSWORD_ITERATIONS,
).hex()
return f"{PASSWORD_ALGORITHM}${PASSWORD_ITERATIONS}${salt}${digest}"
def verify_password(password: str, stored_hash: str) -> bool:
try:
algorithm, iterations_raw, salt, expected = stored_hash.split("$", 3)
iterations = int(iterations_raw)
except (ValueError, AttributeError):
return False
if algorithm != PASSWORD_ALGORITHM:
return False
actual = hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
salt.encode("ascii"),
iterations,
).hex()
return hmac.compare_digest(actual, expected)
def create_auth_token(payload: dict[str, object], secret: str, ttl_seconds: int = TOKEN_TTL_SECONDS) -> str:
token_payload = {
**payload,
"exp": int(time.time()) + ttl_seconds,
}
payload_json = json.dumps(token_payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
payload_part = _b64url_encode(payload_json)
signature = hmac.new(secret.encode("utf-8"), payload_part.encode("ascii"), hashlib.sha256).digest()
return f"{payload_part}.{_b64url_encode(signature)}"
def verify_auth_token(token: str, secret: str) -> dict[str, object] | None:
try:
payload_part, signature_part = token.split(".", 1)
except ValueError:
return None
expected_signature = hmac.new(
secret.encode("utf-8"),
payload_part.encode("ascii"),
hashlib.sha256,
).digest()
try:
actual_signature = _b64url_decode(signature_part)
except (ValueError, base64.binascii.Error):
return None
if not hmac.compare_digest(actual_signature, expected_signature):
return None
try:
payload = json.loads(_b64url_decode(payload_part).decode("utf-8"))
except (ValueError, UnicodeDecodeError):
return None
if int(payload.get("exp") or 0) < int(time.time()):
return None
return payload if isinstance(payload, dict) else None
def normalize_username(username: str) -> str:
return username.strip().lower()
def generate_activation_code() -> str:
groups = [secrets.token_urlsafe(4).replace("-", "X").replace("_", "Y").upper()[:6] for _ in range(3)]
return "SL-" + "-".join(groups)
+232
View File
@@ -83,6 +83,31 @@ def initialize_database() -> None:
}
if "cover_url" not in video_columns:
connection.execute("ALTER TABLE videos ADD COLUMN cover_url TEXT")
user_columns = {
row["name"]
for row in connection.execute("PRAGMA table_info(users)").fetchall()
}
if "is_active" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1")
if "last_login_at" not in user_columns:
connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT")
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS activation_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL UNIQUE,
created_by TEXT NOT NULL,
used_by_user_id INTEGER,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
used_at TEXT,
status TEXT NOT NULL DEFAULT 'unused',
FOREIGN KEY (used_by_user_id) REFERENCES users (id) ON DELETE SET NULL
);
CREATE INDEX IF NOT EXISTS idx_activation_codes_status
ON activation_codes (status);
"""
)
connection.execute(
"""
DELETE FROM subtitles
@@ -101,6 +126,213 @@ def initialize_database() -> None:
)
def row_to_user(row: sqlite3.Row) -> dict[str, object]:
return {
"id": row["id"],
"username": repair_mojibake_text(row["email"]),
"displayName": repair_mojibake_text(row["display_name"] or row["email"]),
"role": row["role"],
"isActive": bool(row["is_active"]),
"createdAt": row["created_at"],
"updatedAt": row["updated_at"],
"lastLoginAt": row["last_login_at"] or "",
}
def row_to_activation_code(row: sqlite3.Row) -> dict[str, object]:
return {
"id": row["id"],
"code": row["code"],
"createdBy": row["created_by"],
"status": row["status"],
"createdAt": row["created_at"],
"usedAt": row["used_at"] or "",
"usedByUserId": row["used_by_user_id"],
"usedByUsername": repair_mojibake_text(row["used_by_username"] or ""),
}
def get_user_by_username(username: str) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM users
WHERE email = ?
""",
(repair_mojibake_text(username),),
).fetchone()
return row_to_user(row) if row else None
def get_user_auth_record(username: str) -> sqlite3.Row | None:
with get_connection() as connection:
return connection.execute(
"""
SELECT *
FROM users
WHERE email = ?
""",
(repair_mojibake_text(username),),
).fetchone()
def get_user_by_id(user_id: int) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM users
WHERE id = ?
""",
(user_id,),
).fetchone()
return row_to_user(row) if row else None
def list_users() -> list[dict[str, object]]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT *
FROM users
ORDER BY created_at DESC, id DESC
"""
).fetchall()
return [row_to_user(row) for row in rows]
def update_user_active(user_id: int, is_active: bool) -> dict[str, object] | None:
with get_connection() as connection:
cursor = connection.execute(
"""
UPDATE users
SET is_active = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
AND role != 'admin'
""",
(1 if is_active else 0, user_id),
)
if cursor.rowcount == 0:
return None
return get_user_by_id(user_id)
def mark_user_login(user_id: int) -> None:
with get_connection() as connection:
connection.execute(
"""
UPDATE users
SET last_login_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(user_id,),
)
def register_user_with_activation(*, username: str, password_hash: str, activation_code: str) -> dict[str, object]:
clean_username = repair_mojibake_text(username)
clean_code = activation_code.strip().upper()
with get_connection() as connection:
code_row = connection.execute(
"""
SELECT *
FROM activation_codes
WHERE code = ?
AND status = 'unused'
""",
(clean_code,),
).fetchone()
if code_row is None:
raise ValueError("activation_code_unavailable")
try:
cursor = connection.execute(
"""
INSERT INTO users (
email, password_hash, display_name, role, is_active
)
VALUES (?, ?, ?, 'user', 1)
""",
(clean_username, password_hash, clean_username),
)
except sqlite3.IntegrityError as exc:
raise ValueError("username_exists") from exc
user_id = int(cursor.lastrowid)
connection.execute(
"""
UPDATE activation_codes
SET status = 'used',
used_by_user_id = ?,
used_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(user_id, code_row["id"]),
)
user = get_user_by_id(user_id)
if user is None:
raise RuntimeError("Registered user could not be loaded")
return user
def create_activation_codes(codes: list[str], created_by: str) -> list[dict[str, object]]:
created_ids: list[int] = []
with get_connection() as connection:
for code in codes:
cursor = connection.execute(
"""
INSERT INTO activation_codes (code, created_by)
VALUES (?, ?)
""",
(code, created_by),
)
created_ids.append(int(cursor.lastrowid))
with get_connection() as connection:
placeholders = ",".join("?" for _ in created_ids)
rows = connection.execute(
f"""
SELECT activation_codes.*, users.email AS used_by_username
FROM activation_codes
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
WHERE activation_codes.id IN ({placeholders})
ORDER BY activation_codes.id DESC
""",
created_ids,
).fetchall()
return [row_to_activation_code(row) for row in rows]
def list_activation_codes() -> list[dict[str, object]]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT activation_codes.*, users.email AS used_by_username
FROM activation_codes
LEFT JOIN users ON users.id = activation_codes.used_by_user_id
ORDER BY activation_codes.created_at DESC, activation_codes.id DESC
"""
).fetchall()
return [row_to_activation_code(row) for row in rows]
def delete_unused_activation_code(code_id: int) -> bool:
with get_connection() as connection:
cursor = connection.execute(
"""
DELETE FROM activation_codes
WHERE id = ?
AND status = 'unused'
""",
(code_id,),
)
return cursor.rowcount > 0
def repair_mojibake_text(value: str | None) -> str:
if not value:
return ""
+223 -16
View File
@@ -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")