From ad52207a93a827d443fd15066f3885bf1bda3cdc Mon Sep 17 00:00:00 2001 From: Nixevol Date: Wed, 28 Oct 2026 03:53:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=90=8E=E5=8F=B0=E7=9A=84=E4=BC=9A=E8=AF=9D=E3=80=81=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=92=8C=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 1 - backend/admin/__init__.py | 1 + backend/admin/identity.py | 49 ++ backend/admin/models.py | 20 + backend/admin/routes.py | 95 +++ backend/admin/session.py | 36 + backend/admin/settings.py | 136 ++++ backend/admin/users.py | 169 +++++ backend/alembic/env.py | 1 + .../alembic/versions/0004_admin_settings.py | 34 + backend/euniv/api.py | 59 +- backend/euniv/client.py | 8 +- backend/euniv/models.py | 7 +- backend/euniv/service.py | 148 ++++- backend/tests/conftest.py | 19 + backend/tests/test_admin.py | 621 ++++++++++++++++++ backend/tests/test_api.py | 48 +- 17 files changed, 1382 insertions(+), 70 deletions(-) create mode 100644 backend/admin/__init__.py create mode 100644 backend/admin/identity.py create mode 100644 backend/admin/models.py create mode 100644 backend/admin/routes.py create mode 100644 backend/admin/session.py create mode 100644 backend/admin/settings.py create mode 100644 backend/admin/users.py create mode 100644 backend/alembic/versions/0004_admin_settings.py create mode 100644 backend/tests/test_admin.py diff --git a/.env.example b/.env.example index f6ed45a..03642cc 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,2 @@ EUNIV_SECRET_KEY=请换成一串只放在服务器上的密钥 EUNIV_DB_PATH=data/euniv.db -EUNIV_WORKER_INTERVAL=20 diff --git a/backend/admin/__init__.py b/backend/admin/__init__.py new file mode 100644 index 0000000..43ca535 --- /dev/null +++ b/backend/admin/__init__.py @@ -0,0 +1 @@ +"""管理后台:会话、系统配置和用户管理。""" diff --git a/backend/admin/identity.py b/backend/admin/identity.py new file mode 100644 index 0000000..85a8761 --- /dev/null +++ b/backend/admin/identity.py @@ -0,0 +1,49 @@ +"""进程内只保留当前管理员的用户名和密码密文。 + +不缓存明文密码,也不缓存 e 学用户、登录凭证或检查结果。 +启动时从设置表加载,修改用户名或密码后同步。重启会重新加载。 +""" + +from __future__ import annotations + +import threading + +from euniv.crypto import decrypt_secret + + +class AdminIdentity: + def __init__(self) -> None: + self._username = "" + self._password_cipher = "" + self._lock = threading.Lock() + + def replace(self, username: str, password_cipher: str) -> None: + with self._lock: + self._username = username + self._password_cipher = password_cipher + + def matches(self, account: str) -> bool: + with self._lock: + username = self._username + return bool(username) and account == username + + def password_ok(self, password: str) -> bool: + with self._lock: + cipher = self._password_cipher + if not cipher: + return False + try: + return decrypt_secret(cipher) == password + except Exception: + return False + + def username(self) -> str: + with self._lock: + return self._username + + def password_cipher(self) -> str: + with self._lock: + return self._password_cipher + + +identity = AdminIdentity() diff --git a/backend/admin/models.py b/backend/admin/models.py new file mode 100644 index 0000000..f135a6b --- /dev/null +++ b/backend/admin/models.py @@ -0,0 +1,20 @@ +"""系统配置。刷新间隔、验证码选项和管理员口令都在这张表,不使用环境变量。""" + +from __future__ import annotations + +from sqlalchemy import Boolean, Integer, String, Text, false as sql_false, true as sql_true +from sqlalchemy.orm import Mapped, mapped_column + +from euniv.models import Base + + +class SystemConfig(Base): + __tablename__ = "system_config" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + refresh_interval_minutes: Mapped[int] = mapped_column(Integer, nullable=False, default=30, server_default="30") + show_manual_jigsaw: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=sql_true()) + manual_preference: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) + auto_jigsaw_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=3, server_default="3") + admin_username: Mapped[str] = mapped_column(String(64), nullable=False) + admin_password_cipher: Mapped[str] = mapped_column(Text, nullable=False) diff --git a/backend/admin/routes.py b/backend/admin/routes.py new file mode 100644 index 0000000..e219784 --- /dev/null +++ b/backend/admin/routes.py @@ -0,0 +1,95 @@ +"""管理后台和登录页公开配置的接口。""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, Request, Response +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from admin.identity import identity +from admin.session import admin_session_active, clear_admin_session +from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view +from admin.users import check_all, check_employee, delete_user, list_users, read_credentials, set_paused +from euniv.db import get_db + +public_router = APIRouter() +admin_router = APIRouter(prefix="/api/admin") + + +class SettingsBody(BaseModel): + refresh_interval_minutes: int + show_manual_jigsaw: bool + manual_preference: bool + auto_jigsaw_attempts: int + admin_username: str + admin_password: str | None = None + + +class PauseBody(BaseModel): + paused: bool + + +def require_admin(request: Request) -> str: + if not admin_session_active(request.cookies): + raise HTTPException(status_code=401, detail="未登录") + return identity.username() + + +@public_router.get("/api/login-config") +def login_config(db: Session = Depends(get_db)) -> dict: + return login_config_view(load_config(db)) + + +@admin_router.get("/settings") +def get_settings(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + return settings_view(load_config(db)) + + +@admin_router.put("/settings") +def put_settings(body: SettingsBody, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + try: + row = save_settings(db, body.model_dump()) + except SettingsError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return settings_view(row) + + +@admin_router.post("/logout") +def admin_logout(response: Response) -> dict: + clear_admin_session(response) + return {"ok": True} + + +@admin_router.get("/users") +def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]: + return list_users(db) + + +@admin_router.post("/users/check-all") +def post_check_all(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]: + return check_all(db) + + +@admin_router.post("/users/{employee_id}/check") +def post_check(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + return check_employee(db, employee_id) + + +@admin_router.post("/users/{employee_id}/refresh") +def post_refresh( + employee_id: str, + body: PauseBody, + db: Session = Depends(get_db), + _: str = Depends(require_admin), +) -> dict: + return set_paused(db, employee_id, body.paused) + + +@admin_router.get("/users/{employee_id}/credentials") +def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + return read_credentials(db, employee_id) + + +@admin_router.delete("/users/{employee_id}") +def remove_user(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: + return delete_user(db, employee_id) diff --git a/backend/admin/session.py b/backend/admin/session.py new file mode 100644 index 0000000..a6aaa7b --- /dev/null +++ b/backend/admin/session.py @@ -0,0 +1,36 @@ +"""管理员浏览器会话。只表示当前是管理员,不写入普通用户会话。""" + +from __future__ import annotations + +from fastapi import Response + +from euniv.crypto import decrypt_secret, encrypt_secret +from euniv.session import MAX_AGE + +COOKIE_NAME = "euniv_admin_session" +_MARK = "euniv-admin" + + +def admin_session_active(cookies) -> bool: + raw = cookies.get(COOKIE_NAME) + if not raw: + return False + try: + return decrypt_secret(raw) == _MARK + except Exception: + return False + + +def write_admin_session(response: Response) -> None: + response.set_cookie( + COOKIE_NAME, + encrypt_secret(_MARK), + max_age=MAX_AGE, + httponly=True, + samesite="lax", + path="/", + ) + + +def clear_admin_session(response: Response) -> None: + response.delete_cookie(COOKIE_NAME, path="/") diff --git a/backend/admin/settings.py b/backend/admin/settings.py new file mode 100644 index 0000000..7c8240f --- /dev/null +++ b/backend/admin/settings.py @@ -0,0 +1,136 @@ +"""系统配置的读取、保存和启动种子。间隔与验证码选项按次读数据库。""" + +from __future__ import annotations + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from admin.identity import identity +from admin.models import SystemConfig +from euniv.crypto import encrypt_secret + +_INITIAL_USERNAME = "admin" +_INITIAL_PASSWORD = "242520" + + +class SettingsError(ValueError): + """配置不符合要求。""" + + +def load_config(db: Session) -> SystemConfig: + row = db.get(SystemConfig, 1) + if row is None: + row = db.scalars(select(SystemConfig).limit(1)).first() + if row is None: + raise RuntimeError("系统配置不存在") + return row + + +def ensure_admin_seed() -> None: + """仅在还没有配置行时写入初始管理员。已有配置则保持不变。""" + from euniv.db import SessionLocal + + with SessionLocal() as db: + if db.scalars(select(SystemConfig).limit(1)).first() is not None: + return + db.add( + SystemConfig( + id=1, + refresh_interval_minutes=30, + show_manual_jigsaw=True, + manual_preference=False, + auto_jigsaw_attempts=3, + admin_username=_INITIAL_USERNAME, + admin_password_cipher=encrypt_secret(_INITIAL_PASSWORD), + ) + ) + db.commit() + + +def load_admin_identity() -> None: + """从设置表重新加载管理员用户名和密码密文。""" + from euniv.db import SessionLocal + + with SessionLocal() as db: + row = load_config(db) + identity.replace(row.admin_username, row.admin_password_cipher) + + +def refresh_interval_seconds(db: Session | None = None) -> int: + if db is None: + from euniv.db import SessionLocal + + with SessionLocal() as owned: + return int(load_config(owned).refresh_interval_minutes) * 60 + return int(load_config(db).refresh_interval_minutes) * 60 + + +def auto_attempt_count(db: Session) -> int: + return int(load_config(db).auto_jigsaw_attempts) + + +def settings_view(row: SystemConfig) -> dict: + return { + "refresh_interval_minutes": int(row.refresh_interval_minutes), + "show_manual_jigsaw": bool(row.show_manual_jigsaw), + "manual_preference": bool(row.manual_preference), + "auto_jigsaw_attempts": int(row.auto_jigsaw_attempts), + "admin_username": row.admin_username, + } + + +def login_config_view(row: SystemConfig) -> dict: + show = bool(row.show_manual_jigsaw) + checked = bool(row.manual_preference) if show else False + return {"show_manual_checkbox": show, "manual_checkbox_checked": checked} + + +def jigsaw_plan(db: Session, requested_manual: bool) -> tuple[bool, int]: + """返回(是否直接手动,自动尝试次数)。""" + row = load_config(db) + attempts = int(row.auto_jigsaw_attempts) + if bool(row.show_manual_jigsaw): + return bool(requested_manual), attempts + if bool(row.manual_preference): + return False, attempts + return True, attempts + + +def _as_int(value: object) -> int | None: + if isinstance(value, bool) or not isinstance(value, int): + return None + return value + + +def save_settings(db: Session, payload: dict) -> SystemConfig: + username = str(payload.get("admin_username") or "").strip() + if not username: + raise SettingsError("请填写管理员用户名") + if len(username) > 64: + raise SettingsError("管理员用户名不能超过 64 个字符") + interval = _as_int(payload.get("refresh_interval_minutes")) + attempts = _as_int(payload.get("auto_jigsaw_attempts")) + if interval is None or not 1 <= interval <= 1440: + raise SettingsError("定时刷新间隔须为 1 到 1440 的整数") + if attempts is None or not 1 <= attempts <= 10: + raise SettingsError("自动滑动次数须为 1 到 10 的整数") + password = payload.get("admin_password") + if password is not None and password != "" and len(str(password)) > 128: + raise SettingsError("管理员密码过长") + + row = load_config(db) + previous_interval = int(row.refresh_interval_minutes) + row.refresh_interval_minutes = interval + row.show_manual_jigsaw = bool(payload.get("show_manual_jigsaw")) + row.manual_preference = bool(payload.get("manual_preference")) + row.auto_jigsaw_attempts = attempts + row.admin_username = username + if password is not None and password != "": + row.admin_password_cipher = encrypt_secret(str(password)) + db.commit() + identity.replace(row.admin_username, row.admin_password_cipher) + if interval != previous_interval: + from euniv.service import notify_refresh_interval_changed + + notify_refresh_interval_changed() + return row diff --git a/backend/admin/users.py b/backend/admin/users.py new file mode 100644 index 0000000..e5ec54d --- /dev/null +++ b/backend/admin/users.py @@ -0,0 +1,169 @@ +"""本地用户的列表、检查、暂停和删除。按请求读数据库,不缓存用户或凭证。""" + +from __future__ import annotations + +import json +from datetime import datetime, timezone + +from fastapi import HTTPException +from sqlalchemy import select +from sqlalchemy.orm import Session + +from euniv.crypto import decrypt_secret +from euniv.models import Account + +_TOKEN_KEYS = ( + "ucs_token", + "ucs_account_id", + "ucs_user_id", + "ucs_ssoinfo", + "ucs_union_id", + "yxt_token", +) + + +def build_client(login_name: str, password: str): + from euniv.client import EunivClient + + return EunivClient(login_name, password) + + +def record_outcome(account: Account, valid: bool | None) -> None: + account.last_refresh_at = datetime.now(timezone.utc) + account.credential_valid = valid + + +def _optional_bool(value: object) -> bool | None: + if value is None: + return None + return bool(value) + + +def _iso_time(value: datetime | None) -> str | None: + if value is None: + return None + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.isoformat() + + +def list_users(db: Session) -> list[dict]: + has_credential = (Account.credential_cipher != "").label("has_credential") + rows = db.execute( + select( + Account.employee_id, + has_credential, + Account.refresh_paused, + Account.last_refresh_at, + Account.credential_valid, + ).order_by(Account.employee_id) + ).all() + return [ + { + "employee_id": row.employee_id, + "has_credential": bool(row.has_credential), + "refresh_paused": bool(row.refresh_paused), + "last_refresh_at": _iso_time(row.last_refresh_at), + "credential_valid": _optional_bool(row.credential_valid), + } + for row in rows + ] + + +def _require(db: Session, employee_id: str) -> Account: + account = db.get(Account, employee_id) + if account is None: + raise HTTPException(status_code=404, detail="用户不存在") + return account + + +def check_employee(db: Session, employee_id: str) -> dict: + account = _require(db, employee_id) + if not account.credential_cipher: + return {"employee_id": employee_id, "result": "未保存"} + before_password = account.password_cipher + before_credential = account.credential_cipher + client = None + result = "检查失败" + valid: bool | None = None + try: + client = build_client(employee_id, decrypt_secret(account.password_cipher)) + client.restore(json.loads(decrypt_secret(account.credential_cipher))) + alive = bool(client.credential_alive()) + result = "有效" if alive else "已失效" + valid = alive + except Exception: + db.rollback() + account = db.get(Account, employee_id) + result = "检查失败" + valid = None + finally: + if client is not None: + try: + client.close() + except Exception: + pass + if account is None: + raise HTTPException(status_code=404, detail="用户不存在") + if result != "检查失败": + account.password_cipher = before_password + account.credential_cipher = before_credential + record_outcome(account, valid) + db.commit() + payload = {"employee_id": employee_id, "result": result} + if result == "检查失败": + payload["detail"] = "检查失败" + return payload + + +def check_all(db: Session) -> list[dict]: + employee_ids = list( + db.scalars( + select(Account.employee_id) + .where(Account.credential_cipher != "") + .order_by(Account.employee_id) + ) + ) + results = [] + for employee_id in employee_ids: + try: + results.append(check_employee(db, employee_id)) + except HTTPException: + raise + except Exception: + results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"}) + return results + + +def set_paused(db: Session, employee_id: str, paused: bool) -> dict: + account = _require(db, employee_id) + account.refresh_paused = paused + db.commit() + return {"ok": True} + + +def read_credentials(db: Session, employee_id: str) -> dict: + account = _require(db, employee_id) + payload = { + "password": decrypt_secret(account.password_cipher) if account.password_cipher else "", + "ucs_token": "", + "ucs_account_id": "", + "ucs_user_id": "", + "ucs_ssoinfo": "", + "ucs_union_id": "", + "yxt_token": "", + } + if not account.credential_cipher: + payload["detail"] = "尚未完成登录或已注销" + return payload + stored = json.loads(decrypt_secret(account.credential_cipher)) + for key in _TOKEN_KEYS: + payload[key] = str(stored.get(key) or "") + return payload + + +def delete_user(db: Session, employee_id: str) -> dict: + account = _require(db, employee_id) + db.delete(account) + db.commit() + return {"ok": True} diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 1bfd478..a6796db 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -3,6 +3,7 @@ from sqlalchemy import engine_from_config, pool from euniv.db import database_url from euniv.models import Base +import admin.models # 注册系统配置表 config = context.config config.set_main_option("sqlalchemy.url", database_url()) diff --git a/backend/alembic/versions/0004_admin_settings.py b/backend/alembic/versions/0004_admin_settings.py new file mode 100644 index 0000000..3dc950d --- /dev/null +++ b/backend/alembic/versions/0004_admin_settings.py @@ -0,0 +1,34 @@ +"""系统配置、刷新暂停和刷新结论。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0004_admin_settings" +down_revision = "0003_credentials" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("accounts") as batch: + batch.add_column(sa.Column("refresh_paused", sa.Boolean(), nullable=False, server_default=sa.false())) + batch.add_column(sa.Column("last_refresh_at", sa.DateTime(timezone=True), nullable=True)) + batch.add_column(sa.Column("credential_valid", sa.Boolean(), nullable=True)) + op.create_table( + "system_config", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("refresh_interval_minutes", sa.Integer(), nullable=False, server_default="30"), + sa.Column("show_manual_jigsaw", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("manual_preference", sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column("auto_jigsaw_attempts", sa.Integer(), nullable=False, server_default="3"), + sa.Column("admin_username", sa.String(length=64), nullable=False), + sa.Column("admin_password_cipher", sa.Text(), nullable=False), + ) + + +def downgrade() -> None: + op.drop_table("system_config") + with op.batch_alter_table("accounts") as batch: + batch.drop_column("credential_valid") + batch.drop_column("last_refresh_at") + batch.drop_column("refresh_paused") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 8a0b6d9..3eea54e 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -11,7 +11,12 @@ 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, @@ -27,6 +32,8 @@ from euniv.session import clear_session, read_employee_id, write_session @asynccontextmanager async def lifespan(_app: FastAPI): init_db() + ensure_admin_seed() + load_admin_identity() stop = None if os.environ.get("EUNIV_DISABLE_REFRESH") != "1": stop = start_credential_refresh() @@ -36,10 +43,12 @@ async def lifespan(_app: FastAPI): 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=32) + employee_id: str = Field(min_length=1, max_length=64) password: str = Field(min_length=1, max_length=128) manual_jigsaw: bool = False @@ -56,23 +65,45 @@ def health() -> dict: def _open_session(response: Response, payload: dict) -> dict: employee_id = payload.get("employee_id") - if employee_id: - write_session(response, employee_id) - return payload + 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) -> dict: - employee_id = read_employee_id(request.cookies) +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 {"employee_id": employee_id} + 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, body.employee_id.strip(), body.password, manual=body.manual_jigsaw) + 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) @@ -103,8 +134,10 @@ def revoke(request: Request, response: Response, db: Session = Depends(get_db)) return {"ok": True} -def _signed_in(request: Request) -> str: - employee_id = read_employee_id(request.cookies) +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 @@ -113,7 +146,7 @@ def _signed_in(request: Request) -> str: @app.get("/api/home") def home(request: Request, db: Session = Depends(get_db)) -> dict: try: - return fetch_home(db, _signed_in(request)) + return fetch_home(db, _signed_in(request, db)) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @@ -121,7 +154,7 @@ def home(request: Request, db: Session = Depends(get_db)) -> dict: @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), path) + return fetch_exam_detail(db, _signed_in(request, db), path) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc @@ -129,7 +162,7 @@ def exam_detail(path: str, request: Request, db: Session = Depends(get_db)) -> d @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), path) + return fetch_training_detail(db, _signed_in(request, db), path) except RuntimeError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc diff --git a/backend/euniv/client.py b/backend/euniv/client.py index c8b892c..e939db3 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -324,7 +324,7 @@ class EunivClient: block = payload.get("code") or {} return block.get("code") or "", block.get("msg") or "", payload.get("bo") - def login(self, manual: bool = False) -> dict: + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: self.client.get(EUNIV + "/") self.client.post( f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate", @@ -358,10 +358,14 @@ class EunivClient: raise RuntimeError(f"安全码检查失败:{check_message}") self._cipher = encrypt_password(public_key, self.password) + return self._login_with_jigsaw(manual, auto_attempts) + + def _login_with_jigsaw(self, manual: bool, auto_attempts: int) -> dict: + """次数由调用方传入。只把拼图被拒绝计入自动次数,密码错误或网络失败不重试。""" if manual: self._load_jigsaw() raise ManualJigsaw(self.current_puzzle()) - for _ in range(3): + for _ in range(auto_attempts): big, small, top = self._load_jigsaw() try: return self.submit_jigsaw(jigsaw_offset(big, small, top)) diff --git a/backend/euniv/models.py b/backend/euniv/models.py index fc28e43..63e1e84 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -2,7 +2,9 @@ from __future__ import annotations -from sqlalchemy import String, Text +from datetime import datetime + +from sqlalchemy import Boolean, DateTime, String, Text, false as sql_false from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -16,3 +18,6 @@ class Account(Base): employee_id: Mapped[str] = mapped_column(String(32), primary_key=True) password_cipher: Mapped[str] = mapped_column(Text) credential_cipher: Mapped[str] = mapped_column(Text, default="") + refresh_paused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=sql_false()) + last_refresh_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True) diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 83343f2..e998f83 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -63,6 +63,7 @@ def login_and_store( password: str, client_factory=EunivClient, manual: bool = False, + auto_attempts: int = 3, ) -> dict: _purge_pending() account = db.get(Account, employee_id) @@ -74,7 +75,7 @@ def login_and_store( held = False try: try: - profile = client.login(manual=manual) + profile = client.login(manual=manual, auto_attempts=auto_attempts) except ManualJigsaw as exc: attempt_id = secrets.token_urlsafe(18) _pending[attempt_id] = PendingLogin(client, employee_id, password, time.time()) @@ -133,25 +134,32 @@ def fetch_training_detail(db: Session, employee_id: str, path: str, client_facto return _live(db, employee_id, client_factory, lambda client: client.training_detail(path)) +def _auto_attempts(db: Session) -> int: + from admin.settings import auto_attempt_count + + return auto_attempt_count(db) + + def _live(db: Session, employee_id: str, client_factory, read): account = db.get(Account, employee_id) if account is None: raise RuntimeError("请先登录") credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {} + attempts = _auto_attempts(db) client = client_factory(employee_id, decrypt_secret(account.password_cipher)) try: if credential.get("yxt_token"): client.restore(credential) else: try: - client.authorize(client.login()) + client.authorize(client.login(manual=False, auto_attempts=attempts)) except ManualJigsaw: raise RuntimeError("登录需要重新验证,请重新登录") from None try: data = read(client) except SessionExpired: try: - client.authorize(client.login()) + client.authorize(client.login(manual=False, auto_attempts=attempts)) except ManualJigsaw: raise RuntimeError("登录需要重新验证,请重新登录") from None data = read(client) @@ -173,40 +181,124 @@ def revoke_credential(db: Session, employee_id: str) -> None: def refresh_stored_credentials(client_factory=EunivClient) -> None: + """逐个刷新。先只取出工号,再每人单独打开会话,避免把全部凭证同时放进内存。""" + from admin.settings import auto_attempt_count from euniv.db import SessionLocal with SessionLocal() as db: - accounts = list(db.scalars(select(Account))) - for account in accounts: - if not account.credential_cipher: - continue - client = client_factory(account.employee_id, decrypt_secret(account.password_cipher)) - try: - previous = json.loads(decrypt_secret(account.credential_cipher)) - client.restore(previous) - if client.credential_alive(): - updated = client.export_credential() - if _dump(updated) != _dump(previous): - account.credential_cipher = encrypt_secret(_dump(updated)) - db.commit() - continue - profile = client.login() - _persist(db, account.employee_id, decrypt_secret(account.password_cipher), client, profile) - except Exception: - continue - finally: - client.close() + attempts = auto_attempt_count(db) + employee_ids = list(db.scalars(select(Account.employee_id).order_by(Account.employee_id))) + for employee_id in employee_ids: + _refresh_one(employee_id, attempts, client_factory) -def start_credential_refresh(interval_seconds: int = 1800) -> threading.Event: - stop = threading.Event() +def _refresh_one(employee_id: str, attempts: int, client_factory) -> None: + from admin.users import record_outcome + from euniv.db import SessionLocal + + with SessionLocal() as db: + account = db.get(Account, employee_id) + if account is None or account.refresh_paused or not account.credential_cipher: + return + client = None + valid = False + try: + password = decrypt_secret(account.password_cipher) + previous = json.loads(decrypt_secret(account.credential_cipher)) + client = client_factory(employee_id, password) + client.restore(previous) + if client.credential_alive(): + updated = client.export_credential() + if _dump(updated) != _dump(previous): + account.credential_cipher = encrypt_secret(_dump(updated)) + valid = True + else: + profile = client.login(manual=False, auto_attempts=attempts) + _persist(db, employee_id, password, client, profile) + valid = True + except Exception: + db.rollback() + valid = False + account = db.get(Account, employee_id) + if account is None: + return + finally: + if client is not None: + try: + client.close() + except Exception: + pass + record_outcome(account, valid) + db.commit() + + +class _RefreshGate: + """停止或变更间隔时立刻结束当前等待。""" + + def __init__(self) -> None: + self._event = threading.Event() + self._lock = threading.Lock() + self._reason = "" + + def set(self) -> None: + with self._lock: + self._reason = "stop" + self._event.set() + + def wake(self) -> None: + with self._lock: + if self._reason != "stop": + self._reason = "wake" + self._event.set() + + def wait(self, seconds: float) -> str: + self._event.wait(timeout=max(0.0, seconds)) + with self._lock: + reason = self._reason + if reason == "stop": + return "stop" + if reason == "wake": + self._reason = "" + self._event.clear() + return "wake" + return "timeout" + + +_gate: _RefreshGate | None = None + + +def _refresh_interval_seconds() -> int: + from admin.settings import refresh_interval_seconds + + return refresh_interval_seconds() + + +def notify_refresh_interval_changed() -> None: + """保存新间隔后打断等待。这次唤醒只重新计时,不立刻刷新。""" + if _gate is not None: + _gate.wake() + + +def start_credential_refresh() -> _RefreshGate: + global _gate + gate = _RefreshGate() + _gate = gate def loop() -> None: - while not stop.wait(interval_seconds): - refresh_stored_credentials() + while True: + seconds = _refresh_interval_seconds() + reason = gate.wait(seconds) + if reason == "stop": + return + if reason == "wake": + continue + try: + refresh_stored_credentials() + except Exception: + continue threading.Thread(target=loop, name="euniv-credential-refresh", daemon=True).start() - return stop + return gate def stored_password(account: Account) -> str: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 15baa8d..12eea88 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -2,6 +2,8 @@ import os import sys from pathlib import Path +import pytest + _backend = Path(__file__).resolve().parents[1] sys.path.insert(0, str(_backend)) _root = _backend.parent / "Temp" / "pytest" @@ -9,3 +11,20 @@ _root.mkdir(parents=True, exist_ok=True) os.environ["EUNIV_SECRET_KEY"] = "test-secret-key" os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db") os.environ["EUNIV_DISABLE_REFRESH"] = "1" + + +@pytest.fixture(autouse=True) +def fresh_database(): + from sqlalchemy import text + + from admin.settings import ensure_admin_seed, load_admin_identity + from euniv.db import engine, init_db + + with engine.begin() as connection: + connection.execute(text("DROP TABLE IF EXISTS accounts")) + connection.execute(text("DROP TABLE IF EXISTS schedules")) + connection.execute(text("DROP TABLE IF EXISTS system_config")) + connection.execute(text("DROP TABLE IF EXISTS alembic_version")) + init_db() + ensure_admin_seed() + load_admin_identity() diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py new file mode 100644 index 0000000..c0f2eb2 --- /dev/null +++ b/backend/tests/test_admin.py @@ -0,0 +1,621 @@ +import json +import threading +from datetime import datetime, timezone +from pathlib import Path + +from fastapi.testclient import TestClient +from sqlalchemy import event + +from admin.identity import identity +from admin.models import SystemConfig +from admin.settings import ensure_admin_seed, load_admin_identity, refresh_interval_seconds +from euniv.client import EunivClient, JigsawRejected, ManualJigsaw +from euniv.crypto import decrypt_secret, encrypt_secret +from euniv.db import SessionLocal, engine +from euniv.models import Account +from euniv.session import COOKIE_NAME + +INITIAL_PASSWORD = "242520" +CREDENTIAL = { + "ucs_token": "ucs-1", + "ucs_account_id": "acct", + "ucs_user_id": "user", + "ucs_ssoinfo": "sso", + "ucs_union_id": "union", + "yxt_token": "yxt-1", +} + + +def _app(): + import euniv.api as api_module + + return api_module + + +def _add_account( + employee_id: str, + password: str = "secret-pass", + credential: dict | None = CREDENTIAL, + paused: bool = False, + refreshed_at: datetime | None = None, + valid: bool | None = None, +) -> None: + with SessionLocal() as db: + db.add( + Account( + employee_id=employee_id, + password_cipher=encrypt_secret(password), + credential_cipher=encrypt_secret(json.dumps(credential)) if credential is not None else "", + refresh_paused=paused, + last_refresh_at=refreshed_at, + credential_valid=valid, + ) + ) + db.commit() + + +def _settings_body(**overrides) -> dict: + body = { + "refresh_interval_minutes": 30, + "show_manual_jigsaw": True, + "manual_preference": False, + "auto_jigsaw_attempts": 3, + "admin_username": "admin", + } + body.update(overrides) + return body + + +def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None: + api = _app() + calls = [] + + def spy(*_args, **_kwargs): + calls.append("euniv") + raise AssertionError("不应走 e 学登录") + + api.login_and_store = spy + statements = [] + + def hear(_connection, _cursor, statement, _parameters, _context, _executemany): + statements.append(statement) + + event.listen(engine, "before_cursor_execute", hear) + try: + client = TestClient(api.app) + wrong = client.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"}) + assert wrong.status_code == 400 + assert wrong.json()["detail"] == "登录失败" + assert calls == [] + assert not any("system_config" in statement.lower() for statement in statements) + + ok = client.post("/api/login", json={"employee_id": " admin ", "password": INITIAL_PASSWORD}) + assert ok.status_code == 200 + assert ok.json() == {"role": "admin", "username": "admin"} + assert "euniv_admin_session" in client.cookies + assert COOKIE_NAME not in client.cookies + assert client.get("/api/session").json() == {"role": "admin", "username": "admin"} + assert client.get("/api/home").status_code == 403 + assert client.get("/api/exam", params={"path": "/exam/x"}).status_code == 403 + assert client.get("/api/training", params={"path": "/plan/x"}).status_code == 403 + assert calls == [] + finally: + event.remove(engine, "before_cursor_execute", hear) + + +def test_admin_identity_uses_memory_until_reload() -> None: + api = _app() + calls = [] + api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: calls.append(employee_id) or { + "employee_id": employee_id + } + with SessionLocal() as db: + row = db.get(SystemConfig, 1) + assert row is not None + row.admin_username = "6650000146" + row.admin_password_cipher = encrypt_secret("other-secret") + db.commit() + + client = TestClient(api.app) + user = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) + assert user.status_code == 200 + assert user.json()["role"] == "user" + assert calls == ["6650000146"] + + calls.clear() + admin = client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}) + assert admin.status_code == 200 + assert admin.json() == {"role": "admin", "username": "admin"} + assert calls == [] + + load_admin_identity() + rejected = client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}) + assert rejected.status_code == 200 + assert rejected.json()["role"] == "user" + accepted = client.post("/api/login", json={"employee_id": "6650000146", "password": "other-secret"}) + assert accepted.json() == {"role": "admin", "username": "6650000146"} + + +def test_seed_does_not_reset_saved_admin() -> None: + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + saved = client.put( + "/api/admin/settings", + json=_settings_body(admin_username="ops", admin_password="next-secret", refresh_interval_minutes=15), + ) + assert saved.status_code == 200 + assert saved.json()["admin_username"] == "ops" + assert "admin_password" not in saved.json() + ensure_admin_seed() + load_admin_identity() + assert client.get("/api/admin/settings").json()["admin_username"] == "ops" + assert client.get("/api/session").json() == {"role": "admin", "username": "ops"} + old = client.post("/api/login", json={"employee_id": "ops", "password": INITIAL_PASSWORD}) + assert old.status_code == 400 + assert old.json()["detail"] == "登录失败" + again = client.post("/api/login", json={"employee_id": "ops", "password": "next-secret"}) + assert again.json() == {"role": "admin", "username": "ops"} + with SessionLocal() as db: + row = db.get(SystemConfig, 1) + assert row is not None + assert decrypt_secret(row.admin_password_cipher) == "next-secret" + + +def test_login_config_changes_meaning_with_visibility() -> None: + api = _app() + seen = {} + + def spy(db, employee_id, password, manual=False, auto_attempts=3): + seen["manual"] = manual + seen["attempts"] = auto_attempts + return {"employee_id": employee_id} + + api.login_and_store = spy + client = TestClient(api.app) + opened = client.get("/api/login-config") + assert opened.json() == {"show_manual_checkbox": True, "manual_checkbox_checked": False} + assert set(opened.json()) == {"show_manual_checkbox", "manual_checkbox_checked"} + + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + assert client.put("/api/admin/settings", json=_settings_body(manual_preference=True, auto_jigsaw_attempts=6)).status_code == 200 + checked = client.get("/api/login-config").json() + assert checked == {"show_manual_checkbox": True, "manual_checkbox_checked": True} + client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": False}) + assert seen == {"manual": False, "attempts": 6} + client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": True}) + assert seen["manual"] is True + + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + hidden = _settings_body(show_manual_jigsaw=False, manual_preference=True, auto_jigsaw_attempts=4) + assert client.put("/api/admin/settings", json=hidden).status_code == 200 + assert client.get("/api/login-config").json() == {"show_manual_checkbox": False, "manual_checkbox_checked": False} + client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": True}) + assert seen["manual"] is False + assert seen["attempts"] == 4 + + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + direct = _settings_body(show_manual_jigsaw=False, manual_preference=False, auto_jigsaw_attempts=9) + assert client.put("/api/admin/settings", json=direct).status_code == 200 + client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": False}) + assert seen["manual"] is True + assert seen["attempts"] == 9 + + +def test_settings_reject_interval_and_attempts_outside_range() -> None: + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + too_wide = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=1441)) + assert too_wide.status_code == 400 + assert too_wide.json()["detail"] == "定时刷新间隔须为 1 到 1440 的整数" + too_many = client.put("/api/admin/settings", json=_settings_body(auto_jigsaw_attempts=0)) + assert too_many.status_code == 400 + assert too_many.json()["detail"] == "自动滑动次数须为 1 到 10 的整数" + blank = client.put("/api/admin/settings", json=_settings_body(admin_username=" ")) + assert blank.status_code == 400 + assert blank.json()["detail"] == "请填写管理员用户名" + assert client.get("/api/admin/settings").json()["refresh_interval_minutes"] == 30 + kept = client.put("/api/admin/settings", json=_settings_body(admin_password="")) + assert kept.status_code == 200 + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + edges = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=1, auto_jigsaw_attempts=10)) + assert edges.status_code == 200 + assert edges.json()["refresh_interval_minutes"] == 1 + assert edges.json()["auto_jigsaw_attempts"] == 10 + + +def test_refresh_interval_comes_only_from_database(monkeypatch) -> None: + monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "9") + assert refresh_interval_seconds() == 30 * 60 + with SessionLocal() as db: + row = db.get(SystemConfig, 1) + assert row is not None + row.refresh_interval_minutes = 12 + db.commit() + assert refresh_interval_seconds() == 12 * 60 + monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "1440") + assert refresh_interval_seconds() == 12 * 60 + + root = Path(__file__).resolve().parents[2] + example = (root / ".env.example").read_text(encoding="utf-8") + assert "EUNIV_WORKER_INTERVAL" not in example + assert "EUNIV_SECRET_KEY" in example + assert "EUNIV_DB_PATH" in example + for folder in ("euniv", "admin", "alembic"): + for path in (root / "backend" / folder).rglob("*.py"): + assert "EUNIV_WORKER_INTERVAL" not in path.read_text(encoding="utf-8") + service_text = (root / "backend" / "euniv" / "service.py").read_text(encoding="utf-8") + assert "1800" not in service_text + + import euniv.service as service + + seen = [] + done = threading.Event() + refreshes = [] + + def wait(self, seconds): + seen.append(seconds) + if len(seen) >= 2: + done.set() + return "stop" + return "wake" + + monkeypatch.setattr(service._RefreshGate, "wait", wait) + monkeypatch.setattr(service, "refresh_stored_credentials", lambda *args, **kwargs: refreshes.append(1)) + service.start_credential_refresh() + assert done.wait(2) + assert seen == [12 * 60, 12 * 60] + assert refreshes == [] + + +def test_saving_new_interval_restarts_wait_without_refresh(monkeypatch) -> None: + import euniv.service as service + + notices = [] + monkeypatch.setattr(service, "notify_refresh_interval_changed", lambda: notices.append(1)) + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + same = client.put("/api/admin/settings", json=_settings_body(admin_username="admin")) + assert same.status_code == 200 + assert notices == [] + changed = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=45)) + assert changed.status_code == 200 + assert notices == [1] + monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "1") + assert refresh_interval_seconds() == 45 * 60 + + +class _Alive: + def __init__(self, login_name: str, password: str) -> None: + self.login_name = login_name + self.password = password + self.login_called = False + + def close(self) -> None: + return None + + def restore(self, _credential: dict) -> None: + return None + + def credential_alive(self) -> bool: + return True + + def export_credential(self) -> dict: + return dict(CREDENTIAL) + + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: + self.login_called = True + raise AssertionError("不应重新登录") + + def authorize(self, _profile: dict) -> None: + return None + + +class _Dead: + def __init__(self, login_name: str, password: str) -> None: + self.login_name = login_name + + def close(self) -> None: + return None + + def restore(self, _credential: dict) -> None: + return None + + def credential_alive(self) -> bool: + return False + + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: + raise RuntimeError("登录失败:密码错误") + + +def test_refresh_records_outcome_and_skips_paused_accounts() -> None: + import euniv.service as service + + stamped = datetime(2026, 10, 1, 8, 0, tzinfo=timezone.utc) + _add_account("alive-user") + _add_account("failed-user") + _add_account("paused-user", paused=True, refreshed_at=stamped, valid=True) + _add_account("empty-user", credential=None, refreshed_at=stamped, valid=False) + created = [] + + def factory(login_name: str, password: str): + created.append(login_name) + if login_name == "failed-user": + return _Dead(login_name, password) + return _Alive(login_name, password) + + service.refresh_stored_credentials(factory) + assert created == ["alive-user", "failed-user"] + with SessionLocal() as db: + alive = db.get(Account, "alive-user") + failed = db.get(Account, "failed-user") + paused = db.get(Account, "paused-user") + empty = db.get(Account, "empty-user") + assert alive is not None and failed is not None and paused is not None and empty is not None + assert alive.credential_valid is True + assert alive.last_refresh_at is not None + assert decrypt_secret(alive.password_cipher) == "secret-pass" + assert json.loads(decrypt_secret(alive.credential_cipher))["yxt_token"] == "yxt-1" + assert failed.credential_valid is False + assert failed.last_refresh_at is not None + assert decrypt_secret(failed.password_cipher) == "secret-pass" + assert json.loads(decrypt_secret(failed.credential_cipher))["yxt_token"] == "yxt-1" + assert paused.last_refresh_at == stamped.replace(tzinfo=None) or paused.last_refresh_at == stamped + assert paused.credential_valid is True + assert empty.credential_valid is False + assert decrypt_secret(empty.password_cipher) == "secret-pass" + + +def test_paused_account_still_updates_when_opening_home() -> None: + import euniv.service as service + + _add_account("paused-user", paused=True) + + class HomeClient(_Alive): + def __init__(self, login_name: str, password: str) -> None: + super().__init__(login_name, password) + self._token = "yxt-1" + + def home_snapshot(self) -> dict: + self._token = "yxt-2" + return {"name": "测试用户"} + + def export_credential(self) -> dict: + exported = dict(CREDENTIAL) + exported["yxt_token"] = self._token + return exported + + with SessionLocal() as db: + assert service.fetch_home(db, "paused-user", HomeClient)["name"] == "测试用户" + account = db.get(Account, "paused-user") + assert account is not None + assert account.refresh_paused is True + assert json.loads(decrypt_secret(account.credential_cipher))["yxt_token"] == "yxt-2" + + +def test_check_skips_empty_credential_and_updates_saved_one() -> None: + import admin.users as users + + stamped = datetime(2026, 10, 2, 9, 30, tzinfo=timezone.utc) + _add_account("empty-user", credential=None, refreshed_at=stamped, valid=True) + _add_account("saved-user") + calls = [] + + def factory(login_name: str, password: str): + calls.append(login_name) + return _Alive(login_name, password) + + users.build_client = factory + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + missed = client.post("/api/admin/users/empty-user/check") + assert missed.status_code == 200 + assert missed.json() == {"employee_id": "empty-user", "result": "未保存"} + assert calls == [] + with SessionLocal() as db: + empty = db.get(Account, "empty-user") + assert empty is not None + assert empty.credential_valid is True + assert empty.last_refresh_at == stamped or empty.last_refresh_at == stamped.replace(tzinfo=None) + + checked = client.post("/api/admin/users/saved-user/check") + assert checked.status_code == 200 + assert checked.json() == {"employee_id": "saved-user", "result": "有效"} + assert calls == ["saved-user"] + listed = client.get("/api/admin/users") + assert listed.status_code == 200 + body = listed.json() + assert isinstance(body, list) + saved = next(item for item in body if item["employee_id"] == "saved-user") + assert set(saved) == { + "employee_id", + "has_credential", + "refresh_paused", + "last_refresh_at", + "credential_valid", + } + assert saved["has_credential"] is True + assert saved["refresh_paused"] is False + assert saved["credential_valid"] is True + assert isinstance(saved["last_refresh_at"], str) + calls.clear() + again = client.get("/api/admin/users") + assert again.status_code == 200 + assert calls == [] + + +def test_check_all_reports_each_saved_account() -> None: + import admin.users as users + + _add_account("a-user") + _add_account("b-user") + _add_account("c-user", credential=None) + calls = [] + + def factory(login_name: str, password: str): + calls.append(login_name) + if login_name == "b-user": + raise RuntimeError("网络失败") + return _Alive(login_name, password) + + users.build_client = factory + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + response = client.post("/api/admin/users/check-all") + assert response.status_code == 200 + assert response.json() == [ + {"employee_id": "a-user", "result": "有效"}, + {"employee_id": "b-user", "result": "检查失败", "detail": "检查失败"}, + ] + assert calls == ["a-user", "b-user"] + with SessionLocal() as db: + failed = db.get(Account, "b-user") + untouched = db.get(Account, "c-user") + assert failed is not None and failed.credential_valid is None + assert failed.last_refresh_at is not None + assert untouched is not None and untouched.last_refresh_at is None + + +def test_credentials_and_delete_user() -> None: + import admin.users as users + + users.build_client = lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学")) + _add_account("6650000146") + _add_account("empty-user", credential=None) + api = _app() + admin = TestClient(api.app) + assert admin.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + secret = admin.get("/api/admin/users/6650000146/credentials") + assert secret.status_code == 200 + assert secret.json()["password"] == "secret-pass" + assert secret.json()["ucs_token"] == "ucs-1" + assert secret.json()["yxt_token"] == "yxt-1" + assert "detail" not in secret.json() + missing = admin.get("/api/admin/users/empty-user/credentials") + assert missing.json()["detail"] == "尚未完成登录或已注销" + assert missing.json()["password"] == "secret-pass" + assert missing.json()["yxt_token"] == "" + + user = TestClient(api.app) + user.cookies.set(COOKIE_NAME, encrypt_secret("6650000146")) + assert user.get("/api/session").json() == {"role": "user", "employee_id": "6650000146"} + removed = admin.delete("/api/admin/users/6650000146") + assert removed.status_code == 200 + assert removed.json() == {"ok": True} + with SessionLocal() as db: + assert db.get(Account, "6650000146") is None + assert user.get("/api/session").status_code == 401 + assert admin.get("/api/admin/users/6650000146/credentials").status_code == 404 + + +def test_pause_only_changes_refresh_flag() -> None: + _add_account("6650000146", paused=False) + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + response = client.post("/api/admin/users/6650000146/refresh", json={"paused": True}) + assert response.status_code == 200 + with SessionLocal() as db: + account = db.get(Account, "6650000146") + assert account is not None + assert account.refresh_paused is True + assert account.credential_cipher + assert decrypt_secret(account.password_cipher) == "secret-pass" + listed = client.get("/api/admin/users").json() + row = next(item for item in listed if item["employee_id"] == "6650000146") + assert row["refresh_paused"] is True + assert row["has_credential"] is True + + +def test_user_cannot_call_admin_and_logout_clears_only_its_cookie() -> None: + api = _app() + api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: {"employee_id": employee_id} + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 + _add_account("6650000146") + assert client.get("/api/admin/users").status_code == 401 + assert client.get("/api/admin/settings").status_code == 401 + assert client.post("/api/admin/logout").status_code == 200 + assert client.get("/api/session").json()["role"] == "user" + assert client.post("/api/logout").status_code == 200 + assert client.get("/api/session").status_code == 401 + + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + assert client.post("/api/logout").status_code == 200 + assert client.get("/api/session").json()["role"] == "admin" + assert client.post("/api/admin/logout").status_code == 200 + assert client.get("/api/session").status_code == 401 + + +def test_auto_attempts_count_only_rejections(monkeypatch) -> None: + monkeypatch.setattr("euniv.client.jigsaw_offset", lambda *_args: 12) + client = EunivClient.__new__(EunivClient) + loads = {"n": 0} + submits = {"n": 0} + + def load(): + loads["n"] += 1 + return b"b", b"s", 1 + + def submit(_offset: int): + submits["n"] += 1 + if submits["n"] == 1: + raise JigsawRejected("拼图未通过") + raise RuntimeError("登录失败:密码错误") + + client._load_jigsaw = load + client.submit_jigsaw = submit + client.current_puzzle = lambda: {"y": 1} + try: + client._login_with_jigsaw(False, 5) + except RuntimeError as exc: + assert "密码错误" in str(exc) + else: + raise AssertionError("密码错误应立即停止") + assert submits["n"] == 2 + assert loads["n"] == 2 + + submits["n"] = 0 + loads["n"] = 0 + + def reject(_offset: int): + submits["n"] += 1 + raise JigsawRejected("拼图未通过") + + client.submit_jigsaw = reject + try: + client._login_with_jigsaw(False, 4) + except ManualJigsaw: + pass + else: + raise AssertionError("用完次数后应交给手动拼图") + assert submits["n"] == 4 + assert loads["n"] == 5 + loads["n"] = 0 + try: + client._login_with_jigsaw(True, 4) + except ManualJigsaw: + pass + else: + raise AssertionError("直接手动时不应自动滑动") + assert loads["n"] == 1 + + +def test_settings_do_not_expose_process_switches() -> None: + api = _app() + client = TestClient(api.app) + assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 + body = client.get("/api/admin/settings").json() + assert set(body) == { + "refresh_interval_minutes", + "show_manual_jigsaw", + "manual_preference", + "auto_jigsaw_attempts", + "admin_username", + } + assert identity.password_cipher() + assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index df3647a..4ce4ca3 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -1,11 +1,10 @@ import json from fastapi.testclient import TestClient -from sqlalchemy import text from euniv.client import JigsawRejected, ManualJigsaw from euniv.crypto import decrypt_secret -from euniv.db import SessionLocal, engine, init_db +from euniv.db import SessionLocal from euniv.models import Account @@ -25,7 +24,7 @@ class FakeClient: def close(self) -> None: return None - def login(self, manual: bool = False) -> dict: + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: if manual: raise ManualJigsaw({ "big_img": "data:image/png;base64,YQ==", @@ -83,26 +82,18 @@ class FakeClient: } -def setup_function() -> None: - with engine.begin() as connection: - connection.execute(text("DROP TABLE IF EXISTS accounts")) - connection.execute(text("DROP TABLE IF EXISTS schedules")) - connection.execute(text("DROP TABLE IF EXISTS alembic_version")) - init_db() - - def test_login_stores_password_and_credential_only() -> None: import euniv.api as api_module import euniv.service as service_module - api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store( - db, employee_id, password, FakeClient, manual=manual + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ) api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient) client = TestClient(api_module.app) response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert response.status_code == 200 - assert response.json() == {"employee_id": "6650000146"} + assert response.json() == {"role": "user", "employee_id": "6650000146"} with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None @@ -110,7 +101,14 @@ def test_login_stores_password_and_credential_only() -> None: stored = json.loads(decrypt_secret(account.credential_cipher)) assert stored["yxt_token"] == "yxt-1" assert stored["ucs_token"] == "ucs-1" - assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher", "credential_cipher"} + assert set(account.__table__.columns.keys()) == { + "employee_id", + "password_cipher", + "credential_cipher", + "refresh_paused", + "last_refresh_at", + "credential_valid", + } home = client.get("/api/home") assert home.status_code == 200 @@ -147,7 +145,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None: def close(self) -> None: return None - def login(self, manual: bool = False) -> dict: + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: raise ManualJigsaw({ "big_img": "data:image/png;base64,YQ==", "small_img": "data:image/png;base64,Yg==", @@ -187,8 +185,8 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None: "yxt_token": "yxt-manual", } - api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store( - db, employee_id, password, ManualClient, manual=manual + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, ManualClient, manual=manual, auto_attempts=auto_attempts ) api_module.submit_jigsaw = service_module.submit_jigsaw client = TestClient(api_module.app) @@ -208,7 +206,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None: done = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 157}) assert done.status_code == 200 - assert done.json() == {"employee_id": "6650000146"} + assert done.json() == {"role": "user", "employee_id": "6650000146"} with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None @@ -222,12 +220,12 @@ def test_browser_session_logout_and_revoke() -> None: calls = {"login": 0} class RememberClient(FakeClient): - def login(self, manual: bool = False) -> dict: + def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: calls["login"] += 1 - return super().login(manual=manual) + return super().login(manual=manual, auto_attempts=auto_attempts) - api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store( - db, employee_id, password, RememberClient, manual=manual + api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( + db, employee_id, password, RememberClient, manual=manual, auto_attempts=auto_attempts ) client = TestClient(api_module.app) first = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) @@ -237,13 +235,13 @@ def test_browser_session_logout_and_revoke() -> None: assert account is not None before = decrypt_secret(account.credential_cipher) second = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) - assert second.json() == {"employee_id": "6650000146"} + assert second.json() == {"role": "user", "employee_id": "6650000146"} assert calls["login"] == 1 with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert decrypt_secret(account.credential_cipher) == before - assert client.get("/api/session").json() == {"employee_id": "6650000146"} + assert client.get("/api/session").json() == {"role": "user", "employee_id": "6650000146"} assert client.post("/api/logout").status_code == 200 assert client.get("/api/session").status_code == 401 with SessionLocal() as db: