diff --git a/backend/admin/identity.py b/backend/admin/identity.py index 6240b24..aed9b14 100644 --- a/backend/admin/identity.py +++ b/backend/admin/identity.py @@ -8,6 +8,7 @@ from __future__ import annotations import hmac import threading +from contextlib import contextmanager from admin.passwords import is_hashed, verify_password from euniv.crypto import decrypt_secret @@ -17,7 +18,12 @@ class AdminIdentity: def __init__(self) -> None: self._username = "" self._password_cipher = "" - self._lock = threading.Lock() + self._lock = threading.RLock() + + @contextmanager + def exclusive(self): + with self._lock: + yield def replace(self, username: str, password_cipher: str) -> None: with self._lock: diff --git a/backend/admin/settings.py b/backend/admin/settings.py index d03b318..c75059e 100644 --- a/backend/admin/settings.py +++ b/backend/admin/settings.py @@ -260,8 +260,9 @@ def save_settings(db: Session, payload: dict) -> SystemConfig: row.admin_password_cipher = hash_password(password_text) if previous_username != username or password_text: row.admin_sessions_valid_after = datetime.now(timezone.utc) - db.commit() - identity.replace(row.admin_username, row.admin_password_cipher) + with identity.exclusive(): + db.commit() + identity.replace(row.admin_username, row.admin_password_cipher) if interval != previous_interval: from euniv.service import notify_refresh_interval_changed diff --git a/backend/admin/users.py b/backend/admin/users.py index f62e5a6..d72c4f6 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -316,8 +316,10 @@ def delete_user(db: Session, employee_id: str) -> dict: db.delete(account) db.commit() from euniv.autostudy import stop_account + from euniv.study_push import close_account stop_account(employee_id) + close_account(employee_id) from euniv.service import release_credential_lock release_credential_lock(employee_id) diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 5e84531..752cd01 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -16,6 +16,8 @@ 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 JSONResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field from sqlalchemy.orm import Session @@ -47,7 +49,7 @@ from euniv.session import clear_session, write_session class MonthlyTargetBody(BaseModel): - monthly_target: int = Field(strict=True) + monthly_target: int = Field(strict=True, ge=0, le=9999) class ProxyBody(BaseModel): @@ -59,25 +61,25 @@ class ProxyBody(BaseModel): class StudyStartBody(BaseModel): - day: int = Field(strict=True) - hour: int = Field(strict=True) - minute: int = Field(strict=True) - second: int = Field(strict=True) + day: int = Field(strict=True, ge=5, le=25) + 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) + workers: int = Field(strict=True, ge=1, le=8) 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) + monthly_target: int = Field(strict=True, ge=0, le=9999) + day: int = Field(strict=True, ge=5, le=25) + 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) + workers: int = Field(strict=True, ge=1, le=8) class StudyControlBody(BaseModel): @@ -131,6 +133,25 @@ app = FastAPI( 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", +} + + +@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": "请求格式不正确"}) + class LoginBody(BaseModel): employee_id: str = Field(min_length=1, max_length=64) diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 02f5fca..04fb3a8 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -519,8 +519,10 @@ def revoke_credential(db: Session, employee_id: str) -> None: account.sessions_valid_after = datetime.now(timezone.utc) db.commit() from euniv.autostudy import stop_account + from euniv.study_push import close_account stop_account(employee_id) + close_account(employee_id) release_credential_lock(employee_id) diff --git a/backend/euniv/study_push.py b/backend/euniv/study_push.py index 52f9088..76048e7 100644 --- a/backend/euniv/study_push.py +++ b/backend/euniv/study_push.py @@ -49,6 +49,34 @@ def unregister(employee_id: str, ws: WebSocket) -> None: _last_flush.pop(key, None) +def close_account(employee_id: str) -> None: + """注销或删除后关掉这个账号已经打开的学习状态连接。""" + key = (employee_id or "").strip() + if not key: + return + loop = _loop + if loop is None or not loop.is_running(): + _drop_account(key) + return + loop.call_soon_threadsafe(_drop_account, key) + + +def _drop_account(key: str) -> None: + handle = _pending.pop(key, None) + if handle is not None: + handle.cancel() + _dirty.discard(key) + _urgent.discard(key) + _inflight.discard(key) + _last_flush.pop(key, None) + sockets = list(_clients.pop(key, ())) + for ws in sockets: + try: + asyncio.get_running_loop().create_task(ws.close(code=4401)) + except RuntimeError: + pass + + def notify(employee_id: str | None = None, urgent: bool = False) -> None: loop = _loop if loop is None or not loop.is_running(): diff --git a/backend/tests/test_study_push.py b/backend/tests/test_study_push.py index c1a4d07..7f68660 100644 --- a/backend/tests/test_study_push.py +++ b/backend/tests/test_study_push.py @@ -53,3 +53,23 @@ def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None: study_push.unregister("u1", socket) asyncio.run(main()) + + +def test_close_account_drops_open_socket() -> None: + closed: list[int] = [] + + class Socket(_Socket): + async def close(self, code: int = 1000) -> None: + closed.append(code) + + socket = Socket() + + async def main() -> None: + study_push._clients.clear() + study_push.attach_loop(asyncio.get_running_loop()) + study_push.register("gone", socket) + study_push.close_account("gone") + await _until(lambda: closed == [4401]) + assert "gone" not in study_push._clients + + asyncio.run(main()) diff --git a/web/src/features/home/HomeView.vue b/web/src/features/home/HomeView.vue index 4e85118..65d225a 100644 --- a/web/src/features/home/HomeView.vue +++ b/web/src/features/home/HomeView.vue @@ -887,7 +887,8 @@ onUnmounted(() => {
本月进度 - {{ monthProgress.current }} / {{ monthProgress.target }} 分钟 + {{ monthProgress.current }} / {{ monthProgress.target }} 分钟 + {{ monthProgress.current }} 分钟