feat: 增加管理后台的会话、配置和用户管理

This commit is contained in:
Nixevol
2026-10-28 03:53:52 +08:00
parent d42691aebb
commit ad52207a93
17 changed files with 1382 additions and 70 deletions
+46 -13
View File
@@ -11,7 +11,12 @@ from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from admin.identity import identity
from admin.routes import admin_router, public_router
from admin.session import admin_session_active, clear_admin_session, write_admin_session
from admin.settings import ensure_admin_seed, jigsaw_plan, load_admin_identity
from euniv.db import get_db, init_db
from euniv.models import Account
from euniv.service import (
fetch_exam_detail,
fetch_home,
@@ -27,6 +32,8 @@ from euniv.session import clear_session, read_employee_id, write_session
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
ensure_admin_seed()
load_admin_identity()
stop = None
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop = start_credential_refresh()
@@ -36,10 +43,12 @@ async def lifespan(_app: FastAPI):
app = FastAPI(title="EunivTools", lifespan=lifespan)
app.include_router(public_router)
app.include_router(admin_router)
class LoginBody(BaseModel):
employee_id: str = Field(min_length=1, max_length=32)
employee_id: str = Field(min_length=1, max_length=64)
password: str = Field(min_length=1, max_length=128)
manual_jigsaw: bool = False
@@ -56,23 +65,45 @@ def health() -> dict:
def _open_session(response: Response, payload: dict) -> dict:
employee_id = payload.get("employee_id")
if employee_id:
write_session(response, employee_id)
return payload
if not employee_id:
return payload
write_session(response, str(employee_id))
clear_admin_session(response)
opened = dict(payload)
opened["role"] = "user"
opened["employee_id"] = str(employee_id)
return opened
def _active_employee(request: Request, db: Session) -> str | None:
employee_id = read_employee_id(request.cookies)
if not employee_id or db.get(Account, employee_id) is None:
return None
return employee_id
@app.get("/api/session")
def session(request: Request) -> dict:
employee_id = read_employee_id(request.cookies)
def session(request: Request, db: Session = Depends(get_db)) -> dict:
if admin_session_active(request.cookies):
return {"role": "admin", "username": identity.username()}
employee_id = _active_employee(request, db)
if not employee_id:
raise HTTPException(status_code=401, detail="未登录")
return {"employee_id": employee_id}
return {"role": "user", "employee_id": employee_id}
@app.post("/api/login")
def login(body: LoginBody, response: Response, db: Session = Depends(get_db)) -> dict:
account = body.employee_id.strip()
if identity.matches(account):
if not identity.password_ok(body.password):
raise HTTPException(status_code=400, detail="登录失败")
write_admin_session(response)
clear_session(response)
return {"role": "admin", "username": identity.username()}
manual, attempts = jigsaw_plan(db, body.manual_jigsaw)
try:
payload = login_and_store(db, body.employee_id.strip(), body.password, manual=body.manual_jigsaw)
payload = login_and_store(db, account, body.password, manual=manual, auto_attempts=attempts)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return _open_session(response, payload)
@@ -103,8 +134,10 @@ def revoke(request: Request, response: Response, db: Session = Depends(get_db))
return {"ok": True}
def _signed_in(request: Request) -> str:
employee_id = read_employee_id(request.cookies)
def _signed_in(request: Request, db: Session) -> str:
if admin_session_active(request.cookies):
raise HTTPException(status_code=403, detail="管理员不能访问该接口")
employee_id = _active_employee(request, db)
if not employee_id:
raise HTTPException(status_code=401, detail="未登录")
return employee_id
@@ -113,7 +146,7 @@ def _signed_in(request: Request) -> str:
@app.get("/api/home")
def home(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home(db, _signed_in(request))
return fetch_home(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -121,7 +154,7 @@ def home(request: Request, db: Session = Depends(get_db)) -> dict:
@app.get("/api/exam")
def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_exam_detail(db, _signed_in(request), path)
return fetch_exam_detail(db, _signed_in(request, db), path)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -129,7 +162,7 @@ def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> d
@app.get("/api/training")
def training_detail(path: str, request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_training_detail(db, _signed_in(request), path)
return fetch_training_detail(db, _signed_in(request, db), path)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+6 -2
View File
@@ -324,7 +324,7 @@ class EunivClient:
block = payload.get("code") or {}
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
def login(self, manual: bool = False) -> dict:
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
self.client.get(EUNIV + "/")
self.client.post(
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
@@ -358,10 +358,14 @@ class EunivClient:
raise RuntimeError(f"安全码检查失败:{check_message}")
self._cipher = encrypt_password(public_key, self.password)
return self._login_with_jigsaw(manual, auto_attempts)
def _login_with_jigsaw(self, manual: bool, auto_attempts: int) -> dict:
"""次数由调用方传入。只把拼图被拒绝计入自动次数,密码错误或网络失败不重试。"""
if manual:
self._load_jigsaw()
raise ManualJigsaw(self.current_puzzle())
for _ in range(3):
for _ in range(auto_attempts):
big, small, top = self._load_jigsaw()
try:
return self.submit_jigsaw(jigsaw_offset(big, small, top))
+6 -1
View File
@@ -2,7 +2,9 @@
from __future__ import annotations
from sqlalchemy import String, Text
from datetime import datetime
from sqlalchemy import Boolean, DateTime, String, Text, false as sql_false
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -16,3 +18,6 @@ class Account(Base):
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
password_cipher: Mapped[str] = mapped_column(Text)
credential_cipher: Mapped[str] = mapped_column(Text, default="")
refresh_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false())
last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
+120 -28
View File
@@ -63,6 +63,7 @@ def login_and_store(
password: str,
client_factory=EunivClient,
manual: bool = False,
auto_attempts: int = 3,
) -> dict:
_purge_pending()
account = db.get(Account, employee_id)
@@ -74,7 +75,7 @@ def login_and_store(
held = False
try:
try:
profile = client.login(manual=manual)
profile = client.login(manual=manual, auto_attempts=auto_attempts)
except ManualJigsaw as exc:
attempt_id = secrets.token_urlsafe(18)
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
@@ -133,25 +134,32 @@ def fetch_training_detail(db: Session, employee_id: str, path: str, client_facto
return _live(db, employee_id, client_factory, lambda client: client.training_detail(path))
def _auto_attempts(db: Session) -> int:
from admin.settings import auto_attempt_count
return auto_attempt_count(db)
def _live(db: Session, employee_id: str, client_factory, read):
account = db.get(Account, employee_id)
if account is None:
raise RuntimeError("请先登录")
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
attempts = _auto_attempts(db)
client = client_factory(employee_id, decrypt_secret(account.password_cipher))
try:
if credential.get("yxt_token"):
client.restore(credential)
else:
try:
client.authorize(client.login())
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
try:
data = read(client)
except SessionExpired:
try:
client.authorize(client.login())
client.authorize(client.login(manual=False, auto_attempts=attempts))
except ManualJigsaw:
raise RuntimeError("登录需要重新验证,请重新登录") from None
data = read(client)
@@ -173,40 +181,124 @@ def revoke_credential(db: Session, employee_id: str) -> None:
def refresh_stored_credentials(client_factory=EunivClient) -> None:
"""逐个刷新。先只取出工号,再每人单独打开会话,避免把全部凭证同时放进内存。"""
from admin.settings import auto_attempt_count
from euniv.db import SessionLocal
with SessionLocal() as db:
accounts = list(db.scalars(select(Account)))
for account in accounts:
if not account.credential_cipher:
continue
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
try:
previous = json.loads(decrypt_secret(account.credential_cipher))
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
db.commit()
continue
profile = client.login()
_persist(db, account.employee_id, decrypt_secret(account.password_cipher), client, profile)
except Exception:
continue
finally:
client.close()
attempts = auto_attempt_count(db)
employee_ids = list(db.scalars(select(Account.employee_id).order_by(Account.employee_id)))
for employee_id in employee_ids:
_refresh_one(employee_id, attempts, client_factory)
def start_credential_refresh(interval_seconds: int = 1800) -> threading.Event:
stop = threading.Event()
def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
from admin.users import record_outcome
from euniv.db import SessionLocal
with SessionLocal() as db:
account = db.get(Account, employee_id)
if account is None or account.refresh_paused or not account.credential_cipher:
return
client = None
valid = False
try:
password = decrypt_secret(account.password_cipher)
previous = json.loads(decrypt_secret(account.credential_cipher))
client = client_factory(employee_id, password)
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
if _dump(updated) != _dump(previous):
account.credential_cipher = encrypt_secret(_dump(updated))
valid = True
else:
profile = client.login(manual=False, auto_attempts=attempts)
_persist(db, employee_id, password, client, profile)
valid = True
except Exception:
db.rollback()
valid = False
account = db.get(Account, employee_id)
if account is None:
return
finally:
if client is not None:
try:
client.close()
except Exception:
pass
record_outcome(account, valid)
db.commit()
class _RefreshGate:
"""停止或变更间隔时立刻结束当前等待。"""
def __init__(self) -> None:
self._event = threading.Event()
self._lock = threading.Lock()
self._reason = ""
def set(self) -> None:
with self._lock:
self._reason = "stop"
self._event.set()
def wake(self) -> None:
with self._lock:
if self._reason != "stop":
self._reason = "wake"
self._event.set()
def wait(self, seconds: float) -> str:
self._event.wait(timeout=max(0.0, seconds))
with self._lock:
reason = self._reason
if reason == "stop":
return "stop"
if reason == "wake":
self._reason = ""
self._event.clear()
return "wake"
return "timeout"
_gate: _RefreshGate | None = None
def _refresh_interval_seconds() -> int:
from admin.settings import refresh_interval_seconds
return refresh_interval_seconds()
def notify_refresh_interval_changed() -> None:
"""保存新间隔后打断等待。这次唤醒只重新计时,不立刻刷新。"""
if _gate is not None:
_gate.wake()
def start_credential_refresh() -> _RefreshGate:
global _gate
gate = _RefreshGate()
_gate = gate
def loop() -> None:
while not stop.wait(interval_seconds):
refresh_stored_credentials()
while True:
seconds = _refresh_interval_seconds()
reason = gate.wait(seconds)
if reason == "stop":
return
if reason == "wake":
continue
try:
refresh_stored_credentials()
except Exception:
continue
threading.Thread(target=loop, name="euniv-credential-refresh", daemon=True).start()
return stop
return gate
def stored_password(account: Account) -> str: