"""登录接口。本地保存工号、加密密码和加密后的登录凭证。""" 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 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, fetch_home_exams, fetch_home_summary, fetch_home_trainings, fetch_training_detail, login_and_store, revoke_credential, start_credential_refresh, submit_jigsaw, ) from euniv.session import clear_session, read_employee_id, write_session from pydantic import BaseModel as _BaseModel class MonthlyTargetBody(_BaseModel): monthly_target: int @asynccontextmanager async def lifespan(_app: FastAPI): init_db() ensure_admin_seed() load_admin_identity() stop_refresh = None study_worker = None if os.environ.get("EUNIV_DISABLE_REFRESH") != "1": stop_refresh = start_credential_refresh() from euniv.autostudy import start_autostudy study_worker = start_autostudy() yield if study_worker is not None: study_worker.stop() if stop_refresh is not None: stop_refresh.set() 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=64) 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 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, 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 {"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, 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) @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, 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 @app.get("/api/home") def home(request: Request, db: Session = Depends(get_db)) -> dict: try: return fetch_home(db, _signed_in(request, db)) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @app.get("/api/home/summary") def home_summary(request: Request, db: Session = Depends(get_db)) -> dict: try: return fetch_home_summary(db, _signed_in(request, db)) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @app.get("/api/home/exams") def home_exams(request: Request, db: Session = Depends(get_db)) -> dict: try: return fetch_home_exams(db, _signed_in(request, db)) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @app.get("/api/home/trainings") def home_trainings(request: Request, db: Session = Depends(get_db)) -> dict: try: return fetch_home_trainings(db, _signed_in(request, db)) 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, db), path) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @app.get("/api/settings/monthly-target") def get_monthly_target(request: Request, db: Session = Depends(get_db)) -> dict: employee_id = _signed_in(request, db) account = db.get(Account, employee_id) return {"monthly_target": account.monthly_target if account else 600} @app.put("/api/settings/monthly-target") def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session = Depends(get_db)) -> dict: employee_id = _signed_in(request, db) if not 0 <= body.monthly_target <= 9999: raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数") account = db.get(Account, employee_id) if account is None: raise HTTPException(status_code=401, detail="未登录") account.monthly_target = body.monthly_target db.commit() return {"monthly_target": account.monthly_target} @app.get("/api/autostudy/status") def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict: _signed_in(request, db) from euniv.autostudy import autostudy_status return autostudy_status() @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, db), 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")