feat: 增加管理后台的会话、配置和用户管理
This commit is contained in:
@@ -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}
|
||||
Reference in New Issue
Block a user