Files

704 lines
25 KiB
Python

"""登录接口。本地保存工号、加密密码和加密后的登录凭证。"""
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.exceptions import RequestValidationError
from fastapi.responses import FileResponse, JSONResponse
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, ge=0, le=9999)
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, ge=1, le=28)
hour: int = Field(strict=True, ge=0, le=23)
minute: int = Field(strict=True, ge=0, le=59)
second: int = Field(strict=True, ge=0, le=59)
enabled: bool | None = None
class CourseWorkersBody(BaseModel):
workers: int = Field(strict=True, ge=1, le=8)
class StudyBundleBody(BaseModel):
monthly_target: int = Field(strict=True, ge=0, le=9999)
day: int = Field(strict=True, ge=1, le=28)
hour: int = Field(strict=True, ge=0, le=23)
minute: int = Field(strict=True, ge=0, le=59)
second: int = Field(strict=True, ge=0, le=59)
enabled: bool = True
workers: int = Field(strict=True, ge=1, le=8)
heartbeat_mode: str | None = None
heartbeat_video_seconds: int | None = Field(default=None, strict=True, ge=0, le=300)
heartbeat_document_seconds: int | None = Field(default=None, strict=True, ge=0, le=600)
heartbeat_scorm_seconds: int | None = Field(default=None, strict=True, ge=0, le=600)
hours_source: str | None = None
class StudyControlBody(BaseModel):
action: str = Field(min_length=1, max_length=16)
settings: StudyBundleBody | None = None
@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
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
stop_refresh = start_credential_refresh()
from euniv.autostudy import start_autostudy
study_worker = start_autostudy()
start_pending_cleaner()
yield
if study_worker is not None:
study_worker.stop()
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)
_FIELD_ERRORS = {
"monthly_target": "每月学时目标须为 0 到 9999 的整数",
"day": "每月开始日须为 5 到 25 的整数",
"hour": "每月开始时须为 0 到 23 的整数",
"minute": "每月开始分须为 0 到 59 的整数",
"second": "每月开始秒须为 0 到 59 的整数",
"workers": "同时学习课程数须为 1 到 8",
"heartbeat_video_seconds": "视频心跳间隔须为 0 到 300 的整数",
"heartbeat_document_seconds": "文档心跳间隔须为 0 到 600 的整数",
"heartbeat_scorm_seconds": "Scorm 心跳间隔须为 0 到 600 的整数",
}
@app.exception_handler(RequestValidationError)
def reject_bad_body(_request: Request, exc: RequestValidationError) -> JSONResponse:
for item in exc.errors():
loc = item.get("loc") or ()
name = loc[-1] if loc else ""
if isinstance(name, str) and name in _FIELD_ERRORS:
return JSONResponse(status_code=400, content={"detail": _FIELD_ERRORS[name]})
return JSONResponse(status_code=422, content={"detail": "请求格式不正确"})
@app.exception_handler(Exception)
def reject_unexpected(_request: Request, exc: Exception) -> JSONResponse:
if isinstance(exc, HTTPException):
detail = exc.detail if isinstance(exc.detail, str) else "请求没有完成"
return JSONResponse(status_code=exc.status_code, content={"detail": detail})
logging.getLogger("euniv.api").exception("请求没有完成")
return JSONResponse(status_code=500, content={"detail": "服务暂时不可用"})
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/announcements")
def announcements(request: Request, db: Session = Depends(get_db)) -> list[dict]:
from admin.notices import list_notices
_signed_in(request, db)
return list_notices(db)
@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_user, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
try:
apply_user(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.get("/api/settings/heartbeat")
def get_heartbeat(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.heartbeat 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)
def _apply_study_bundle(account: Account, body: StudyBundleBody) -> None:
"""把首页这一组学习配置写到账号上。不符合要求时抛 400,由调用方回滚。"""
from euniv.course_workers import CourseWorkersError, apply as apply_workers
from euniv.heartbeat import HeartbeatError, apply as apply_heartbeat
from euniv.study_window import StudyWindowError, apply_user as apply_start
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)
if (
body.heartbeat_mode is not None
or body.heartbeat_video_seconds is not None
or body.heartbeat_document_seconds is not None
or body.heartbeat_scorm_seconds is not None
):
apply_heartbeat(
account,
body.heartbeat_mode,
body.heartbeat_video_seconds,
body.heartbeat_document_seconds,
body.heartbeat_scorm_seconds,
)
if body.hours_source is not None:
chosen = str(body.hours_source).strip().lower()
if chosen not in {"api", "history"}:
raise HTTPException(status_code=400, detail="学时判断须为官方统计或历史统计")
account.hours_source = chosen
except (StudyWindowError, CourseWorkersError, HeartbeatError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.put("/api/settings/study")
def put_study_bundle(body: StudyBundleBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.heartbeat import view_of as heartbeat_view
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="未登录")
workers_before = account.course_workers
try:
_apply_study_bundle(account, body)
except HTTPException:
db.rollback()
raise
db.commit()
from euniv.autostudy import restart_work, sync_work
if account.course_workers != workers_before:
restart_work(account.employee_id)
sync_work(account.employee_id)
payload = view_of(account)
payload["monthly_target"] = account.monthly_target
payload["workers"] = account.course_workers
payload.update(heartbeat_view(account))
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.study_control import payload_for
return payload_for(_signed_in(request, db))
@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 body.settings is not None:
try:
_apply_study_bundle(account, body.settings)
except HTTPException:
db.rollback()
raise
if int(account.monthly_target or 0) <= 0:
db.rollback()
raise HTTPException(status_code=400, detail="每月目标为 0,不会学习")
if hours_met(account):
from euniv.autostudy import halt_work
db.commit()
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_push import pump, 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
link = register(employee_id, websocket)
sender = asyncio.create_task(pump(employee_id, link))
last_message = 0.0
try:
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
link.wake.set()
except WebSocketDisconnect:
pass
finally:
unregister(employee_id, link)
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
@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"
@app.get("/tool-upgrade", include_in_schema=False)
@app.get("/tool-upgrade/", include_in_schema=False)
def tool_upgrade_page() -> FileResponse:
page = _dist / "tool-upgrade" / "index.html"
if not page.is_file():
raise HTTPException(status_code=404, detail="页面不存在")
return FileResponse(page, headers={"Cache-Control": "no-cache"})
if _dist.is_dir():
app.mount("/", _WebFiles(directory=_dist, html=True), name="web")