Compare commits
2
Commits
d42691aebb
...
5895141926
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5895141926 | ||
|
|
ad52207a93 |
@@ -1,3 +1,2 @@
|
||||
EUNIV_SECRET_KEY=请换成一串只放在服务器上的密钥
|
||||
EUNIV_DB_PATH=data/euniv.db
|
||||
EUNIV_WORKER_INTERVAL=20
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""管理后台:会话、系统配置和用户管理。"""
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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="/")
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -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())
|
||||
|
||||
@@ -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")
|
||||
+46
-13
@@ -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
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
|
||||
+120
-28
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
+23
-25
@@ -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:
|
||||
|
||||
+38
-7
@@ -3,31 +3,61 @@ import { onMounted, ref } from "vue";
|
||||
import { darkTheme, dateZhCN, NConfigProvider, NDialogProvider, NMessageProvider, zhCN } from "naive-ui";
|
||||
import LoginView from "./features/auth/LoginView.vue";
|
||||
import Shell from "./shell/Shell.vue";
|
||||
import AdminShell from "./shell/AdminShell.vue";
|
||||
import { isDark, themeOverrides } from "./shared/theme";
|
||||
import { sessionFromPayload, type AppSession } from "./shared/session";
|
||||
|
||||
const ready = ref(false);
|
||||
const employeeId = ref("");
|
||||
const session = ref<AppSession | null>(null);
|
||||
|
||||
function applyPayload(payload: unknown) {
|
||||
if (!payload || typeof payload !== "object") return null;
|
||||
return sessionFromPayload(payload);
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/session");
|
||||
if (response.ok) {
|
||||
const payload = await response.json();
|
||||
employeeId.value = String(payload.employee_id || "");
|
||||
session.value = applyPayload(await response.json().catch(() => null));
|
||||
}
|
||||
} finally {
|
||||
ready.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
async function reloadSession() {
|
||||
try {
|
||||
const response = await fetch("/api/session");
|
||||
if (response.status === 401) {
|
||||
session.value = null;
|
||||
return;
|
||||
}
|
||||
if (!response.ok) return;
|
||||
const next = applyPayload(await response.json().catch(() => null));
|
||||
if (next) session.value = next;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
async function exitSystem() {
|
||||
await fetch("/api/logout", { method: "POST" });
|
||||
employeeId.value = "";
|
||||
session.value = null;
|
||||
}
|
||||
|
||||
async function revokeAccount() {
|
||||
await fetch("/api/revoke", { method: "POST" });
|
||||
employeeId.value = "";
|
||||
session.value = null;
|
||||
}
|
||||
|
||||
async function exitAdmin() {
|
||||
await fetch("/api/admin/logout", { method: "POST" });
|
||||
session.value = null;
|
||||
}
|
||||
|
||||
function onLogin(next: AppSession) {
|
||||
session.value = next;
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -36,8 +66,9 @@ async function revokeAccount() {
|
||||
<n-message-provider class="app-root">
|
||||
<n-dialog-provider>
|
||||
<div v-if="ready" class="app-root">
|
||||
<LoginView v-if="!employeeId" @success="employeeId = $event" />
|
||||
<Shell v-else :employee-id="employeeId" @logout="exitSystem" @revoke="revokeAccount" />
|
||||
<LoginView v-if="!session" @success="onLogin" />
|
||||
<Shell v-else-if="session.kind === 'user'" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" />
|
||||
<AdminShell v-else-if="session.kind === 'admin'" :username="session.username" @logout="exitAdmin" @refresh="reloadSession" />
|
||||
</div>
|
||||
</n-dialog-provider>
|
||||
</n-message-provider>
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NInput, NInputNumber, NSwitch } from "naive-ui";
|
||||
|
||||
const emit = defineEmits<{ saved: [] }>();
|
||||
|
||||
const loading = ref(true);
|
||||
const loaded = ref(false);
|
||||
const saving = ref(false);
|
||||
const errorText = ref("");
|
||||
const successText = ref("");
|
||||
const refreshInterval = ref<number | null>(null);
|
||||
const showManualJigsaw = ref(false);
|
||||
const manualPreference = ref(false);
|
||||
const attempts = ref<number | null>(null);
|
||||
const username = ref("");
|
||||
const password = ref("");
|
||||
const confirmPassword = ref("");
|
||||
|
||||
const preferenceLabel = computed(() =>
|
||||
showManualJigsaw.value ? "默认勾选手动滑动验证码" : "先尝试自动滑动验证码",
|
||||
);
|
||||
|
||||
function detailOf(payload: unknown, fallback: string) {
|
||||
if (payload && typeof payload === "object" && "detail" in payload) {
|
||||
const detail = (payload as { detail?: unknown }).detail;
|
||||
if (typeof detail === "string" && detail) return detail;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function readNumber(value: unknown) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/admin/settings");
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !payload || typeof payload !== "object") {
|
||||
errorText.value = detailOf(payload, "系统配置没有获取到。");
|
||||
return;
|
||||
}
|
||||
const body = payload as Record<string, unknown>;
|
||||
const minutes = readNumber(body.refresh_interval_minutes);
|
||||
const count = readNumber(body.auto_jigsaw_attempts);
|
||||
if (minutes == null || count == null || typeof body.admin_username !== "string") {
|
||||
errorText.value = "系统配置没有获取到。";
|
||||
return;
|
||||
}
|
||||
refreshInterval.value = minutes;
|
||||
attempts.value = count;
|
||||
showManualJigsaw.value = body.show_manual_jigsaw === true;
|
||||
manualPreference.value = body.manual_preference === true;
|
||||
username.value = body.admin_username;
|
||||
loaded.value = true;
|
||||
} catch {
|
||||
errorText.value = "系统配置没有获取到。";
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
function invalidInteger(value: number | null, min: number, max: number) {
|
||||
return value == null || !Number.isInteger(value) || value < min || value > max;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (saving.value || !loaded.value) return;
|
||||
errorText.value = "";
|
||||
successText.value = "";
|
||||
if (invalidInteger(refreshInterval.value, 1, 1440)) {
|
||||
errorText.value = "定时刷新间隔须为 1 到 1440 的整数";
|
||||
return;
|
||||
}
|
||||
if (invalidInteger(attempts.value, 1, 10)) {
|
||||
errorText.value = "自动滑动次数须为 1 到 10 的整数";
|
||||
return;
|
||||
}
|
||||
const adminUsername = username.value.trim();
|
||||
if (!adminUsername) {
|
||||
errorText.value = "请填写管理员用户名";
|
||||
return;
|
||||
}
|
||||
const body: {
|
||||
refresh_interval_minutes: number;
|
||||
show_manual_jigsaw: boolean;
|
||||
manual_preference: boolean;
|
||||
auto_jigsaw_attempts: number;
|
||||
admin_username: string;
|
||||
admin_password?: string;
|
||||
} = {
|
||||
refresh_interval_minutes: refreshInterval.value as number,
|
||||
show_manual_jigsaw: showManualJigsaw.value,
|
||||
manual_preference: manualPreference.value,
|
||||
auto_jigsaw_attempts: attempts.value as number,
|
||||
admin_username: adminUsername,
|
||||
};
|
||||
if (password.value !== "" || confirmPassword.value !== "") {
|
||||
if (password.value !== confirmPassword.value) {
|
||||
errorText.value = "两次输入的新密码不一致";
|
||||
return;
|
||||
}
|
||||
body.admin_password = password.value;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/admin/settings", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, "没有保存。");
|
||||
return;
|
||||
}
|
||||
password.value = "";
|
||||
confirmPassword.value = "";
|
||||
successText.value = "已保存";
|
||||
emit("saved");
|
||||
} catch {
|
||||
errorText.value = "没有保存。";
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page admin-page">
|
||||
<form class="settings-form" @submit.prevent="save">
|
||||
<header class="page-head">
|
||||
<h2>系统配置</h2>
|
||||
<n-button type="primary" attr-type="submit" :loading="saving" :disabled="!loaded">保存</n-button>
|
||||
</header>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<n-alert v-else-if="successText" class="admin-alert" type="success">{{ successText }}</n-alert>
|
||||
<div class="admin-scroll">
|
||||
<p v-if="loading && !loaded" class="admin-status">正在获取</p>
|
||||
<div v-else-if="loaded">
|
||||
<div class="form-row">
|
||||
<label for="refresh-interval">定时刷新间隔</label>
|
||||
<div class="setting-control">
|
||||
<n-input-number id="refresh-interval" v-model:value="refreshInterval" :min="1" :max="1440" :precision="0" />
|
||||
<span class="setting-unit">分钟</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="show-manual">显示手动滑动验证码</label>
|
||||
<n-switch id="show-manual" v-model:value="showManualJigsaw" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="manual-preference">{{ preferenceLabel }}</label>
|
||||
<n-switch id="manual-preference" v-model:value="manualPreference" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="auto-attempts">自动滑动次数</label>
|
||||
<div class="setting-control">
|
||||
<n-input-number id="auto-attempts" v-model:value="attempts" :min="1" :max="10" :precision="0" />
|
||||
<span class="setting-unit">次</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-username">管理员用户名</label>
|
||||
<n-input id="admin-username" v-model:value="username" autocomplete="username" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-password">新密码</label>
|
||||
<n-input id="admin-password" v-model:value="password" type="password" show-password-on="click" autocomplete="new-password" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="admin-password-again">再输入一次</label>
|
||||
<n-input id="admin-password-again" v-model:value="confirmPassword" type="password" show-password-on="click" autocomplete="new-password" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,359 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NModal, useDialog } from "naive-ui";
|
||||
|
||||
interface UserRow {
|
||||
employee_id: string;
|
||||
has_credential: boolean;
|
||||
refresh_paused: boolean;
|
||||
last_refresh_at: string | null;
|
||||
credential_valid: boolean | null;
|
||||
}
|
||||
|
||||
interface SecretField {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const dialog = useDialog();
|
||||
const loading = ref(true);
|
||||
const errorText = ref("");
|
||||
const users = ref<UserRow[]>([]);
|
||||
const liveResults = ref<Record<string, string>>({});
|
||||
const checkingId = ref("");
|
||||
const checkingAll = ref(false);
|
||||
const credentialOpen = ref(false);
|
||||
const credentialTitle = ref("凭据");
|
||||
const credentialLoading = ref(false);
|
||||
const credentialError = ref("");
|
||||
const credentialNote = ref("");
|
||||
const credentialFields = ref<SecretField[]>([]);
|
||||
|
||||
const tokenFields: { label: string; key: string }[] = [
|
||||
{ label: "统一认证 token", key: "ucs_token" },
|
||||
{ label: "账号标识", key: "ucs_account_id" },
|
||||
{ label: "用户标识", key: "ucs_user_id" },
|
||||
{ label: "ssoinfo", key: "ucs_ssoinfo" },
|
||||
{ label: "unionId", key: "ucs_union_id" },
|
||||
{ label: "学习平台 token", key: "yxt_token" },
|
||||
];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function detailOf(payload: unknown, fallback: string) {
|
||||
if (isRecord(payload) && typeof payload.detail === "string" && payload.detail) return payload.detail;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function textOf(value: unknown) {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function readValid(value: unknown): boolean | null {
|
||||
if (value === true) return true;
|
||||
if (value === false) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function asUser(value: unknown): UserRow | null {
|
||||
if (!isRecord(value) || (typeof value.employee_id !== "string" && typeof value.employee_id !== "number")) return null;
|
||||
return {
|
||||
employee_id: String(value.employee_id),
|
||||
has_credential: value.has_credential === true,
|
||||
refresh_paused: value.refresh_paused === true,
|
||||
last_refresh_at: typeof value.last_refresh_at === "string" && value.last_refresh_at ? value.last_refresh_at : null,
|
||||
credential_valid: readValid(value.credential_valid),
|
||||
};
|
||||
}
|
||||
|
||||
function formatRefreshTime(value: string | null) {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const pad = (part: number) => String(part).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
function checkLabel(payload: Record<string, unknown>) {
|
||||
const result = payload.result;
|
||||
if (result === "有效" || result === "已失效" || result === "检查失败") return result;
|
||||
if (result === "未保存" || result === "未保存凭证") return "未保存凭证";
|
||||
return "检查失败";
|
||||
}
|
||||
|
||||
function validityText(row: UserRow) {
|
||||
const live = liveResults.value[row.employee_id];
|
||||
if (live) return live;
|
||||
if (row.refresh_paused) return "未检查";
|
||||
if (row.credential_valid === true) return "有效";
|
||||
if (row.credential_valid === false) return "已失效";
|
||||
return "未检查";
|
||||
}
|
||||
|
||||
function validityClass(text: string) {
|
||||
if (text === "有效") return "ok";
|
||||
if (text === "已失效" || text === "检查失败") return "late";
|
||||
return "quiet";
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/admin/users");
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, "用户列表没有获取到。");
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(payload)) {
|
||||
errorText.value = detailOf(payload, "用户列表没有获取到。");
|
||||
return;
|
||||
}
|
||||
errorText.value = "";
|
||||
users.value = payload.map(asUser).filter((item): item is UserRow => item !== null);
|
||||
} catch {
|
||||
errorText.value = "用户列表没有获取到。";
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function remember(employeeId: string, label: string) {
|
||||
liveResults.value = { ...liveResults.value, [employeeId]: label };
|
||||
}
|
||||
|
||||
async function checkOne(row: UserRow) {
|
||||
if (checkingId.value || checkingAll.value) return;
|
||||
checkingId.value = row.employee_id;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/check`, { method: "POST" });
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !isRecord(payload)) {
|
||||
remember(row.employee_id, "检查失败");
|
||||
errorText.value = detailOf(payload, "检查失败");
|
||||
return;
|
||||
}
|
||||
const label = checkLabel(payload);
|
||||
remember(row.employee_id, label);
|
||||
errorText.value = label === "检查失败" ? detailOf(payload, "") : "";
|
||||
} catch {
|
||||
remember(row.employee_id, "检查失败");
|
||||
errorText.value = "检查失败";
|
||||
} finally {
|
||||
checkingId.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function checkAll() {
|
||||
if (checkingId.value || checkingAll.value || !users.value.length) return;
|
||||
checkingAll.value = true;
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch("/api/admin/users/check-all", { method: "POST" });
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, "检查失败");
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(payload)) {
|
||||
errorText.value = detailOf(payload, "检查失败");
|
||||
return;
|
||||
}
|
||||
const next = { ...liveResults.value };
|
||||
const notes: string[] = [];
|
||||
for (const item of payload) {
|
||||
if (!isRecord(item) || item.employee_id == null) continue;
|
||||
const employeeId = String(item.employee_id);
|
||||
const label = checkLabel(item);
|
||||
next[employeeId] = label;
|
||||
if (label === "检查失败") {
|
||||
const detail = typeof item.detail === "string" ? item.detail : "";
|
||||
if (detail) notes.push(`${employeeId}:${detail}`);
|
||||
}
|
||||
}
|
||||
liveResults.value = next;
|
||||
errorText.value = notes.join(";");
|
||||
} catch {
|
||||
errorText.value = "检查失败";
|
||||
} finally {
|
||||
checkingAll.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetCredential() {
|
||||
credentialFields.value = [];
|
||||
credentialNote.value = "";
|
||||
credentialError.value = "";
|
||||
}
|
||||
|
||||
function applyCredential(payload: Record<string, unknown>) {
|
||||
const note = textOf(payload.detail);
|
||||
const password = textOf(payload.password);
|
||||
const tokens = tokenFields.map((item) => ({ label: item.label, value: textOf(payload[item.key]) }));
|
||||
const hasToken = tokens.some((item) => item.value !== "");
|
||||
if (note && !hasToken) {
|
||||
credentialNote.value = note;
|
||||
credentialFields.value = password ? [{ label: "密码", value: password }] : [];
|
||||
return;
|
||||
}
|
||||
credentialNote.value = "";
|
||||
credentialFields.value = [{ label: "密码", value: password }, ...tokens];
|
||||
}
|
||||
|
||||
function onCredentialShow(show: boolean) {
|
||||
credentialOpen.value = show;
|
||||
if (!show) resetCredential();
|
||||
}
|
||||
|
||||
async function openCredentials(row: UserRow) {
|
||||
credentialTitle.value = `工号 ${row.employee_id} 的凭据`;
|
||||
resetCredential();
|
||||
credentialLoading.value = true;
|
||||
credentialOpen.value = true;
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/credentials`);
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !isRecord(payload)) {
|
||||
credentialError.value = detailOf(payload, "凭据没有获取到。");
|
||||
return;
|
||||
}
|
||||
applyCredential(payload);
|
||||
} catch {
|
||||
credentialError.value = "凭据没有获取到。";
|
||||
} finally {
|
||||
credentialLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function setPaused(row: UserRow, paused: boolean) {
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/refresh`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ paused }),
|
||||
});
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, "自动刷新没有改成。");
|
||||
return;
|
||||
}
|
||||
row.refresh_paused = paused;
|
||||
} catch {
|
||||
errorText.value = "自动刷新没有改成。";
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRefresh(row: UserRow) {
|
||||
const paused = !row.refresh_paused;
|
||||
dialog.warning({
|
||||
title: paused ? "停止自动刷新" : "恢复自动刷新",
|
||||
content: paused ? `停止工号 ${row.employee_id} 的自动刷新?` : `恢复工号 ${row.employee_id} 的自动刷新?`,
|
||||
positiveText: paused ? "停止" : "恢复",
|
||||
negativeText: "取消",
|
||||
onPositiveClick: () => setPaused(row, paused),
|
||||
});
|
||||
}
|
||||
|
||||
async function removeUser(row: UserRow) {
|
||||
errorText.value = "";
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}`, { method: "DELETE" });
|
||||
const payload: unknown = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
errorText.value = detailOf(payload, "没有删除。");
|
||||
return;
|
||||
}
|
||||
users.value = users.value.filter((item) => item.employee_id !== row.employee_id);
|
||||
const next = { ...liveResults.value };
|
||||
delete next[row.employee_id];
|
||||
liveResults.value = next;
|
||||
} catch {
|
||||
errorText.value = "没有删除。";
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDelete(row: UserRow) {
|
||||
dialog.warning({
|
||||
title: "删除用户",
|
||||
content: `删除工号 ${row.employee_id}?`,
|
||||
positiveText: "删除",
|
||||
negativeText: "取消",
|
||||
positiveButtonProps: { type: "error" },
|
||||
onPositiveClick: () => removeUser(row),
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page admin-page">
|
||||
<header class="page-head">
|
||||
<h2>用户管理</h2>
|
||||
<n-button :loading="checkingAll" :disabled="checkingAll || checkingId !== '' || !users.length" @click="checkAll">检查全部</n-button>
|
||||
</header>
|
||||
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
|
||||
<div class="admin-scroll">
|
||||
<p v-if="loading" class="admin-status">正在获取</p>
|
||||
<table v-else-if="users.length" class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>工号</th>
|
||||
<th>凭证</th>
|
||||
<th>凭据是否有效</th>
|
||||
<th>上次刷新时间</th>
|
||||
<th>自动刷新</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in users" :key="row.employee_id">
|
||||
<td class="employee">{{ row.employee_id }}</td>
|
||||
<td>{{ row.has_credential ? "已保存凭证" : "未保存凭证" }}</td>
|
||||
<td :class="validityClass(validityText(row))">{{ validityText(row) }}</td>
|
||||
<td class="when">{{ formatRefreshTime(row.last_refresh_at) }}</td>
|
||||
<td>{{ row.refresh_paused ? "已停止" : "开启" }}</td>
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<n-button size="small" :loading="checkingId === row.employee_id" :disabled="checkingAll || checkingId !== ''" @click="checkOne(row)">检查</n-button>
|
||||
<n-button size="small" @click="openCredentials(row)">查看凭据</n-button>
|
||||
<n-button size="small" @click="confirmRefresh(row)">{{ row.refresh_paused ? "恢复自动刷新" : "停止自动刷新" }}</n-button>
|
||||
<n-button size="small" type="error" quaternary @click="confirmDelete(row)">删除</n-button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else-if="!errorText" class="admin-status">没有用户</p>
|
||||
</div>
|
||||
<n-modal
|
||||
:show="credentialOpen"
|
||||
preset="card"
|
||||
:title="credentialTitle"
|
||||
:style="{ width: 'min(720px, calc(100vw - 32px))' }"
|
||||
:content-style="{ maxHeight: 'min(70vh, 640px)', overflow: 'auto' }"
|
||||
@update:show="onCredentialShow"
|
||||
>
|
||||
<p v-if="credentialLoading" class="admin-status">正在获取</p>
|
||||
<n-alert v-else-if="credentialError" type="error">{{ credentialError }}</n-alert>
|
||||
<div v-else>
|
||||
<p v-if="credentialNote" class="credential-note">{{ credentialNote }}</p>
|
||||
<div v-for="field in credentialFields" :key="field.label" class="secret-field">
|
||||
<div class="secret-label">{{ field.label }}</div>
|
||||
<div class="secret-value">{{ field.value }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
<n-button @click="credentialOpen = false">关闭</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,8 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { NAlert, NButton, NCheckbox, NIcon, NInput, NTooltip } from "naive-ui";
|
||||
import { ChevronForward, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||
import { isDark, toggleTheme } from "../../shared/theme";
|
||||
import { sessionFromPayload, type AppSession } from "../../shared/session";
|
||||
|
||||
interface JigsawPuzzle {
|
||||
big_img: string;
|
||||
@@ -14,10 +15,21 @@ interface JigsawPuzzle {
|
||||
piece_height: number;
|
||||
}
|
||||
|
||||
const emit = defineEmits<{ success: [employeeId: string] }>();
|
||||
interface LoginPayload {
|
||||
role?: string;
|
||||
username?: string;
|
||||
employee_id?: string;
|
||||
attempt_id?: string;
|
||||
jigsaw?: JigsawPuzzle;
|
||||
detail?: unknown;
|
||||
}
|
||||
|
||||
const emit = defineEmits<{ success: [session: AppSession] }>();
|
||||
const employeeId = ref("");
|
||||
const password = ref("");
|
||||
const submitting = ref(false);
|
||||
const configReady = ref(false);
|
||||
const showManual = ref(false);
|
||||
const manualJigsaw = ref(false);
|
||||
const errorText = ref("");
|
||||
const attemptId = ref("");
|
||||
@@ -33,17 +45,40 @@ const maxOffset = computed(() => {
|
||||
return Math.max(puzzle.width - puzzle.piece_width, 0);
|
||||
});
|
||||
|
||||
function applyResult(payload: { employee_id?: string; attempt_id?: string; jigsaw?: JigsawPuzzle }) {
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/login-config");
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (response.ok && payload && typeof payload === "object") {
|
||||
showManual.value = Boolean((payload as { show_manual_checkbox?: unknown }).show_manual_checkbox);
|
||||
manualJigsaw.value = showManual.value && Boolean((payload as { manual_checkbox_checked?: unknown }).manual_checkbox_checked);
|
||||
} else if (payload && typeof payload === "object" && typeof (payload as { detail?: unknown }).detail === "string") {
|
||||
errorText.value = (payload as { detail: string }).detail;
|
||||
}
|
||||
} catch {
|
||||
showManual.value = false;
|
||||
manualJigsaw.value = false;
|
||||
} finally {
|
||||
configReady.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
function applyResult(payload: LoginPayload) {
|
||||
if (payload.jigsaw && payload.attempt_id) {
|
||||
attemptId.value = payload.attempt_id;
|
||||
jigsaw.value = payload.jigsaw;
|
||||
offset.value = 0;
|
||||
return;
|
||||
}
|
||||
const next = sessionFromPayload(payload);
|
||||
if (!next) {
|
||||
errorText.value = "登录失败";
|
||||
return;
|
||||
}
|
||||
password.value = "";
|
||||
attemptId.value = "";
|
||||
jigsaw.value = null;
|
||||
emit("success", String(payload.employee_id || employeeId.value.trim()));
|
||||
emit("success", next);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
@@ -56,7 +91,7 @@ async function submit() {
|
||||
body: JSON.stringify({
|
||||
employee_id: employeeId.value.trim(),
|
||||
password: password.value,
|
||||
manual_jigsaw: manualJigsaw.value,
|
||||
manual_jigsaw: showManual.value ? manualJigsaw.value : false,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
@@ -141,7 +176,7 @@ function onPointerUp() {
|
||||
<label for="password">密码</label>
|
||||
<n-input id="password" v-model:value="password" type="password" show-password-on="click" placeholder="密码" autocomplete="current-password" :disabled="!!jigsaw || submitting" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div v-if="showManual" class="form-row">
|
||||
<span></span>
|
||||
<n-checkbox v-model:checked="manualJigsaw" :disabled="!!jigsaw || submitting">手动滑动验证码</n-checkbox>
|
||||
</div>
|
||||
@@ -176,7 +211,7 @@ function onPointerUp() {
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="gate-actions">
|
||||
<n-button type="primary" attr-type="submit" :loading="submitting" :disabled="!employeeId.trim() || !password">登录</n-button>
|
||||
<n-button type="primary" attr-type="submit" :loading="submitting" :disabled="!configReady || !employeeId.trim() || !password">登录</n-button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
export interface AdminSession {
|
||||
kind: "admin";
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface UserSession {
|
||||
kind: "user";
|
||||
employeeId: string;
|
||||
}
|
||||
|
||||
export type AppSession = AdminSession | UserSession;
|
||||
|
||||
export function sessionFromPayload(payload: object): AppSession | null {
|
||||
const body = payload as { role?: unknown; username?: unknown; employee_id?: unknown };
|
||||
if (body.role === "admin") {
|
||||
return { kind: "admin", username: typeof body.username === "string" ? body.username : "" };
|
||||
}
|
||||
if (body.role === "user" || (typeof body.employee_id === "string" && body.employee_id) || typeof body.employee_id === "number") {
|
||||
return { kind: "user", employeeId: body.employee_id == null ? "" : String(body.employee_id) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import { NButton, NIcon, NLayout, NLayoutSider, NMenu, NTooltip } from "naive-ui";
|
||||
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||
import { isDark, toggleTheme } from "../shared/theme";
|
||||
import { adminNavOptions, type AdminPageKey } from "./adminNavigation";
|
||||
import UsersView from "../features/admin/UsersView.vue";
|
||||
import SettingsView from "../features/admin/SettingsView.vue";
|
||||
|
||||
defineProps<{ username: string }>();
|
||||
const emit = defineEmits<{ logout: []; refresh: [] }>();
|
||||
const page = ref<AdminPageKey>("users");
|
||||
const collapsed = ref(window.innerWidth < 800);
|
||||
|
||||
function onResize() {
|
||||
if (window.innerWidth < 800) collapsed.value = true;
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener("resize", onResize));
|
||||
onUnmounted(() => window.removeEventListener("resize", onResize));
|
||||
|
||||
function onMenu(key: string) {
|
||||
if (key === "users" || key === "settings") page.value = key;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-layout has-sider class="shell">
|
||||
<n-layout-sider
|
||||
bordered
|
||||
collapse-mode="width"
|
||||
:collapsed-width="64"
|
||||
:width="220"
|
||||
:collapsed="collapsed"
|
||||
show-trigger
|
||||
:native-scrollbar="false"
|
||||
:content-style="{ height: '100%', display: 'flex', flexDirection: 'column' }"
|
||||
@collapse="collapsed = true"
|
||||
@expand="collapsed = false"
|
||||
>
|
||||
<div class="sider-body">
|
||||
<div class="sider-brand" :class="{ compact: collapsed }">
|
||||
<div class="brand-mark" aria-hidden="true">E</div>
|
||||
<strong v-if="!collapsed">EunivTools</strong>
|
||||
</div>
|
||||
<n-menu
|
||||
:collapsed="collapsed"
|
||||
:collapsed-width="64"
|
||||
:collapsed-icon-size="22"
|
||||
:value="page"
|
||||
:options="adminNavOptions"
|
||||
@update:value="onMenu"
|
||||
/>
|
||||
<div class="sider-user" :class="{ compact: collapsed }">
|
||||
<n-icon :size="18"><PersonOutline /></n-icon>
|
||||
<div v-if="!collapsed" class="who">
|
||||
<strong>{{ username }}</strong>
|
||||
<span>已登录</span>
|
||||
</div>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button quaternary circle size="small" :aria-label="isDark ? '切换到日间' : '切换到夜间'" @click="toggleTheme">
|
||||
<template #icon><n-icon><MoonOutline v-if="!isDark" /><SunnyOutline v-else /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
{{ isDark ? "切换到日间" : "切换到夜间" }}
|
||||
</n-tooltip>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button class="logout-btn" quaternary circle size="small" aria-label="退出" @click="emit('logout')">
|
||||
<template #icon><n-icon><LogOutOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</template>
|
||||
退出
|
||||
</n-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</n-layout-sider>
|
||||
<n-layout class="content" :native-scrollbar="false" content-style="height: 100%; min-height: 0; overflow: hidden; display: flex; flex-direction: column;">
|
||||
<UsersView v-if="page === 'users'" />
|
||||
<SettingsView v-else-if="page === 'settings'" @saved="emit('refresh')" />
|
||||
</n-layout>
|
||||
</n-layout>
|
||||
</template>
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Component } from "vue";
|
||||
import { h } from "vue";
|
||||
import { NIcon } from "naive-ui";
|
||||
import { PeopleOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
|
||||
function renderIcon(icon: Component) {
|
||||
return () => h(NIcon, null, { default: () => h(icon) });
|
||||
}
|
||||
|
||||
export type AdminPageKey = "users" | "settings";
|
||||
|
||||
export const adminNavOptions = [
|
||||
{ label: "用户管理", key: "users" as const, icon: renderIcon(PeopleOutline) },
|
||||
{ label: "系统配置", key: "settings" as const, icon: renderIcon(SettingsOutline) },
|
||||
];
|
||||
@@ -696,3 +696,156 @@ select {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.admin-page {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.admin-page .page-head {
|
||||
flex: none;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.admin-page .page-head h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.admin-page > .settings-form {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.admin-alert {
|
||||
flex: none;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.admin-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.admin-status {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.settings-form .form-row {
|
||||
grid-template-columns: max-content minmax(160px, 280px);
|
||||
justify-content: start;
|
||||
}
|
||||
|
||||
.settings-form .form-row label {
|
||||
min-width: 15em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.setting-control .n-input-number {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.setting-unit {
|
||||
flex: none;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.admin-table {
|
||||
width: 100%;
|
||||
min-width: 820px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.admin-table th,
|
||||
.admin-table td {
|
||||
padding: 10px 16px 10px 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.admin-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
background: var(--bg);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.admin-table .employee,
|
||||
.admin-table .when {
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin-table .ok {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.admin-table .late {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.admin-table .quiet {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.credential-note {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.secret-field {
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.secret-field:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.secret-label {
|
||||
margin-bottom: 4px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.secret-value {
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.settings-form .form-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.settings-form .form-row label {
|
||||
min-width: 0;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user