Files
EnuivTools/backend/euniv/api.py
T

408 lines
13 KiB
Python

"""登录接口。本地保存工号、加密密码和加密后的登录凭证。"""
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_study_history,
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
class ProxyBody(_BaseModel):
scheme: str
host: str = ""
port: int | None = None
username: str = ""
password: str | None = None
class StudyStartBody(_BaseModel):
day: int
hour: int
minute: int
second: int
class CourseWorkersBody(_BaseModel):
workers: int
class StudyControlBody(_BaseModel):
action: str
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
ensure_admin_seed()
load_admin_identity()
stop_refresh = None
study_worker = None
stop_pool = None
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop_refresh = start_credential_refresh()
from euniv.autostudy import start_autostudy
from euniv.proxy_pool import start_proxy_pool
study_worker = start_autostudy()
stop_pool = start_proxy_pool()
yield
if study_worker is not None:
study_worker.stop()
if stop_pool is not None:
stop_pool.set()
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/settings/study-start")
def get_study_start(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.study_window import view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
return view_of(account)
@app.put("/api/settings/study-start")
def put_study_start(body: StudyStartBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.study_window import StudyWindowError, apply, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
try:
apply(account, body.day, body.hour, body.minute, body.second)
except StudyWindowError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return view_of(account)
@app.get("/api/settings/course-workers")
def get_course_workers(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.course_workers import view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
return view_of(account)
@app.put("/api/settings/course-workers")
def put_course_workers(body: CourseWorkersBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.course_workers import CourseWorkersError, apply, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
try:
apply(account, body.workers)
except CourseWorkersError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return view_of(account)
@app.get("/api/settings/proxy")
def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
return view_of(account)
@app.put("/api/settings/proxy")
def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import ProxyError, apply, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
try:
apply(account, body.scheme, body.host, body.port, body.username, body.password)
except ProxyError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return view_of(account)
@app.delete("/api/settings/proxy")
def delete_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import clear, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
clear(account)
db.commit()
return view_of(account)
@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/settings/study-control")
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.autostudy import autostudy_status
from euniv.study_control import view_of
employee_id = _signed_in(request, db)
account = db.get(Account, employee_id)
if account is None:
raise HTTPException(status_code=401, detail="未登录")
payload = view_of(account)
live = (autostudy_status().get("users") or {}).get(employee_id) or {}
payload["state"] = str(live.get("state") or "")
payload["course"] = str(live.get("course") or "")
payload["message"] = str(live.get("message") or "")
workers = live.get("workers") or []
payload["workers"] = workers if isinstance(workers, list) else []
payload["active"] = bool(live) and payload["state"] not in {"已达标", "已停止", "会话失效", "会话过期"}
if payload["active"]:
payload["started"] = True
return payload
@app.post("/api/settings/study-control")
def post_study_control(body: StudyControlBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.autostudy import request_stop, request_wake
from euniv.study_control import start_now, stop_now
employee_id = _signed_in(request, db)
account = db.get(Account, employee_id)
if account is None:
raise HTTPException(status_code=401, detail="未登录")
action = (body.action or "").strip().lower()
if action == "start":
start_now(account)
db.commit()
request_wake()
elif action == "stop":
stop_now(account)
db.commit()
request_stop(employee_id)
else:
raise HTTPException(status_code=400, detail="请选择开始或停止")
return get_study_control(request, db)
@app.get("/api/home/history")
def home_history(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_study_history(db, _signed_in(request, db))
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, 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")