"""登录接口。本地保存工号、加密密码和加密后的登录凭证。""" from __future__ import annotations import os from contextlib import asynccontextmanager from pathlib import Path from fastapi import Depends, FastAPI, HTTPException, Request, Response from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field from sqlalchemy.orm import Session from euniv.db import get_db, init_db from euniv.service import ( fetch_exam_detail, fetch_home, fetch_training_detail, login_and_store, revoke_credential, start_credential_refresh, submit_jigsaw, ) from euniv.session import clear_session, read_employee_id, write_session @asynccontextmanager async def lifespan(_app: FastAPI): init_db() stop = None if os.environ.get("EUNIV_DISABLE_REFRESH") != "1": stop = start_credential_refresh() yield if stop is not None: stop.set() app = FastAPI(title="EunivTools", lifespan=lifespan) class LoginBody(BaseModel): employee_id: str = Field(min_length=1, max_length=32) password: str = Field(min_length=1, max_length=128) manual_jigsaw: bool = False class JigsawBody(BaseModel): attempt_id: str = Field(min_length=8, max_length=64) offset: int = Field(ge=0, le=2000) @app.get("/api/health") def health() -> dict: return {"ok": True} def _open_session(response: Response, payload: dict) -> dict: employee_id = payload.get("employee_id") if employee_id: write_session(response, employee_id) return payload @app.get("/api/session") def session(request: Request) -> dict: employee_id = read_employee_id(request.cookies) if not employee_id: raise HTTPException(status_code=401, detail="未登录") return {"employee_id": employee_id} @app.post("/api/login") def login(body: LoginBody, response: Response, db: Session = Depends(get_db)) -> dict: try: payload = login_and_store(db, body.employee_id.strip(), body.password, manual=body.manual_jigsaw) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc return _open_session(response, payload) @app.post("/api/login/jigsaw") def login_jigsaw(body: JigsawBody, response: Response, db: Session = Depends(get_db)) -> dict: try: payload = submit_jigsaw(db, body.attempt_id, body.offset) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc return _open_session(response, payload) @app.post("/api/logout") def logout(response: Response) -> dict: clear_session(response) return {"ok": True} @app.post("/api/revoke") def revoke(request: Request, response: Response, db: Session = Depends(get_db)) -> dict: employee_id = read_employee_id(request.cookies) if not employee_id: raise HTTPException(status_code=401, detail="未登录") revoke_credential(db, employee_id) clear_session(response) return {"ok": True} def _signed_in(request: Request) -> str: employee_id = read_employee_id(request.cookies) if not employee_id: raise HTTPException(status_code=401, detail="未登录") return employee_id @app.get("/api/home") def home(request: Request, db: Session = Depends(get_db)) -> dict: try: return fetch_home(db, _signed_in(request)) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @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) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @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) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc _dist = Path(__file__).resolve().parents[2] / "web" / "dist" if _dist.is_dir(): app.mount("/", StaticFiles(directory=_dist, html=True), name="web")