it-architecture/backend/app/deps.py

42 lines
1.6 KiB
Python

"""Shared request helpers."""
from __future__ import annotations
import sqlite3
from typing import Annotated
from urllib.parse import unquote
from fastapi import Depends, HTTPException, Request
from .db import get_db, setting
def ensure_editable(db: sqlite3.Connection, action: str = "修改") -> None:
"""Abort a content write while the platform is switched to read-only.
423 Locked says "this exists but cannot be edited right now", which is exactly what
the switch means, and the frontend turns it into a toast naming that switch. The
``/api/settings`` endpoints deliberately stay open: locking the platform must never
lock the page that unlocks it again.
"""
if setting(db, "editing_enabled", True) is False:
raise HTTPException(423, f"平台已锁定为只读,无法{action}。请在「系统配置 · 平台配置」打开「允许编辑」后重试。")
def require_editable(db: Annotated[sqlite3.Connection, Depends(get_db)]) -> None:
"""Route dependency form of :func:`ensure_editable` for plain content writes."""
ensure_editable(db)
def actor_from(request: Request) -> str:
"""Editing identity travels on a header so every write method can stay uniform.
Header values cannot carry Chinese text, so the client percent-encodes it and we
decode here. Anything that is not valid escape coding is kept as-is.
"""
raw = request.headers.get("X-Editor") or request.headers.get("X-Actor") or ""
try:
decoded = unquote(raw, errors="strict") # strict so malformed input falls back below
except (UnicodeDecodeError, ValueError):
decoded = raw
return decoded.strip()[:40] or "匿名"