"""登录接口。本地保存工号、加密密码和加密后的登录凭证。""" from __future__ import annotations import asyncio import logging import os from contextlib import asynccontextmanager from pathlib import Path logging.basicConfig( level=os.getenv("EUNIV_LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(name)s %(message)s", ) logging.getLogger("httpx").setLevel(logging.WARNING) logging.getLogger("httpcore").setLevel(logging.WARNING) from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field from sqlalchemy.orm import Session from admin.identity import identity from admin.login_limit import record_failure, record_success, too_many 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, load_config from euniv.db import get_db, init_db from euniv.models import Account from euniv.login_limit import allow as login_allowed from euniv.service import ( fetch_exam_detail, fetch_home_exams, fetch_home_summary, fetch_home_trainings, fetch_study_history, fetch_training_detail, login_and_store, poll_qr_login, revoke_credential, start_credential_refresh, start_qr_login, start_pending_cleaner, submit_jigsaw, ) from euniv.session import clear_session, write_session class MonthlyTargetBody(BaseModel): monthly_target: int = Field(strict=True) class ProxyBody(BaseModel): scheme: str = Field(min_length=1, max_length=16) host: str = Field(default="", max_length=255) port: int | None = Field(default=None, ge=1, le=65535) username: str = Field(default="", max_length=128) password: str | None = Field(default=None, max_length=128) class StudyStartBody(BaseModel): day: int = Field(strict=True) hour: int = Field(strict=True) minute: int = Field(strict=True) second: int = Field(strict=True) enabled: bool | None = None class CourseWorkersBody(BaseModel): workers: int = Field(strict=True) class StudyBundleBody(BaseModel): monthly_target: int = Field(strict=True) day: int = Field(strict=True) hour: int = Field(strict=True) minute: int = Field(strict=True) second: int = Field(strict=True) enabled: bool = True workers: int = Field(strict=True) class StudyControlBody(BaseModel): action: str = Field(min_length=1, max_length=16) @asynccontextmanager async def lifespan(_app: FastAPI): from euniv.instance_lock import acquire_instance_lock acquire_instance_lock() if os.environ.get("EUNIV_DISABLE_REFRESH") == "1": logging.getLogger("euniv.api").warning("EUNIV_DISABLE_REFRESH=1,后台刷新、自动学习和代理池都不会启动") init_db() ensure_admin_seed() from admin.settings import ensure_key_check ensure_key_check() load_admin_identity() from euniv.study_push import attach_loop attach_loop(asyncio.get_running_loop()) 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() start_pending_cleaner() 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() _openapi = os.environ.get("EUNIV_OPENAPI") == "1" app = FastAPI( title="EunivTools", lifespan=lifespan, docs_url="/docs" if _openapi else None, redoc_url="/redoc" if _openapi else None, openapi_url="/openapi.json" if _openapi else None, ) 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) class QrPollBody(BaseModel): attempt_id: str = Field(min_length=8, max_length=64) @app.get("/api/health") def health() -> dict: from sqlalchemy import text from euniv.db import SessionLocal with SessionLocal() as db: db.execute(text("SELECT 1")) study_alive = False try: from euniv import autostudy worker = autostudy._worker thread = getattr(worker, "_thread", None) if worker is not None else None study_alive = bool(thread is not None and thread.is_alive()) except Exception: study_alive = False return {"ok": True, "database": True, "study": study_alive} 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: from euniv.session import COOKIE_NAME, open_seal, still_valid raw = request.cookies.get(COOKIE_NAME) if not raw: return None opened = open_seal(raw, "user") if opened is None: return None employee_id, issued = opened account = db.get(Account, employee_id) if account is None or not still_valid(issued, account.sessions_valid_after): 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, load_config(db).admin_sessions_valid_after): 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} def _client_host(request: Request) -> str: if request.client is None or not request.client.host: return "unknown" return request.client.host @app.post("/api/login") def login(body: LoginBody, request: Request, response: Response, db: Session = Depends(get_db)) -> dict: account = body.employee_id.strip() if not account: raise HTTPException(status_code=400, detail="请填写工号") if not login_allowed(_client_host(request)): raise HTTPException(status_code=429, detail="登录过于频繁,请稍后再试") if identity.matches(account): source = _client_host(request) if too_many(source): raise HTTPException(status_code=429, detail="登录失败次数过多,请稍后再试") if not identity.password_ok(body.password): record_failure(source) if too_many(source): raise HTTPException(status_code=429, detail="登录失败次数过多,请稍后再试") raise HTTPException(status_code=400, detail="登录失败") record_success(source) 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/login/qr") def login_qr(request: Request) -> dict: if not login_allowed(_client_host(request)): raise HTTPException(status_code=429, detail="登录过于频繁,请稍后再试") try: return start_qr_login() except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @app.post("/api/login/qr/poll") def login_qr_poll(body: QrPollBody, response: Response, db: Session = Depends(get_db)) -> dict: try: payload = poll_qr_login(db, body.attempt_id) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc if payload.get("employee_id"): return _open_session(response, payload) return 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 = _active_employee(request, db) 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, load_config(db).admin_sessions_valid_after): 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/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() from euniv.autostudy import sync_work sync_work(employee_id) 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 if body.enabled is not None: account.study_schedule_enabled = bool(body.enabled) db.commit() from euniv.autostudy import sync_work sync_work(account.employee_id) return view_of(account) @app.put("/api/settings/study") def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depends(get_db)) -> dict: from euniv.course_workers import CourseWorkersError, apply as apply_workers from euniv.study_window import StudyWindowError, apply as apply_start, view_of if not 0 <= body.monthly_target <= 9999: raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数") account = db.get(Account, _signed_in(request, db)) if account is None: raise HTTPException(status_code=401, detail="未登录") try: account.monthly_target = body.monthly_target apply_start(account, body.day, body.hour, body.minute, body.second) account.study_schedule_enabled = bool(body.enabled) apply_workers(account, body.workers) except (StudyWindowError, CourseWorkersError) as exc: db.rollback() raise HTTPException(status_code=400, detail=str(exc)) from exc db.commit() from euniv.autostudy import sync_work sync_work(account.employee_id) payload = view_of(account) payload["monthly_target"] = account.monthly_target payload["workers"] = account.course_workers return payload @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() from euniv.autostudy import restart_work restart_work(account.employee_id) return view_of(account) @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 assemble, settle, stamp_frame employee_id = _signed_in(request, db) account = db.get(Account, employee_id) if account is None: raise HTTPException(status_code=401, detail="未登录") status = autostudy_status() live = dict((status.get("users") or {}).get(employee_id) or {}) if settle(account, live): db.commit() return stamp_frame(employee_id, assemble(account, live)) @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, sync_work from euniv.study_control import hours_met, start_now, stop_now from euniv.study_push import notify 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": if int(account.monthly_target or 0) <= 0: raise HTTPException(status_code=400, detail="每月目标为 0,不会学习") if hours_met(account): from euniv.autostudy import halt_work halt_work(employee_id) else: from euniv.autostudy import clear_study_hold clear_study_hold(employee_id) start_now(account) db.commit() sync_work(employee_id) elif action == "stop": stop_now(account) db.commit() request_stop(employee_id) else: raise HTTPException(status_code=400, detail="请选择开始或停止") notify(employee_id, urgent=True) return get_study_control(request, db) def _same_origin(websocket: WebSocket) -> bool: origin = websocket.headers.get("origin", "") if not origin: return True from urllib.parse import urlparse origin_host = (urlparse(origin).hostname or "").lower() request_host = websocket.headers.get("host", "").split(":")[0].strip("[]").lower() return bool(origin_host) and origin_host == request_host def _ws_gate(cookies: dict) -> tuple[int, str]: from euniv.db import SessionLocal from euniv.session import COOKIE_NAME, open_seal, still_valid with SessionLocal() as db: if admin_session_active(cookies, load_config(db).admin_sessions_valid_after): return 4403, "" opened = open_seal(cookies.get(COOKIE_NAME, ""), "user") if opened is None: return 4401, "" employee_id, issued = opened account = db.get(Account, employee_id) if account is None or not still_valid(issued, account.sessions_valid_after): return 4401, "" return 0, employee_id @app.websocket("/api/settings/study-control/ws") async def study_control_ws(websocket: WebSocket): from euniv.study_control import payload_for from euniv.study_push import register, unregister if not _same_origin(websocket): await websocket.close(code=4403) return await websocket.accept() code, employee_id = await asyncio.to_thread(_ws_gate, dict(websocket.cookies)) if code: await websocket.close(code=code) return register(employee_id, websocket) last_message = 0.0 try: await websocket.send_json(await asyncio.to_thread(payload_for, employee_id)) while True: message = await websocket.receive() if message.get("type") == "websocket.disconnect": break if "text" not in message: continue now = asyncio.get_running_loop().time() if now - last_message < 1: continue last_message = now await websocket.send_json(await asyncio.to_thread(payload_for, employee_id)) except WebSocketDisconnect: pass finally: unregister(employee_id, websocket) @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 @app.api_route("/api", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]) @app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]) def api_fallback(rest: str = "") -> None: raise HTTPException(status_code=405, detail="不支持该请求") class _WebFiles(StaticFiles): async def get_response(self, path: str, scope): response = await super().get_response(path, scope) if path in {"", "index.html"}: response.headers["Cache-Control"] = "no-cache" return response _dist = Path(__file__).resolve().parents[2] / "web" / "dist" if _dist.is_dir(): app.mount("/", _WebFiles(directory=_dist, html=True), name="web")