269 lines
9.9 KiB
Python
269 lines
9.9 KiB
Python
"""系统配置的读取、保存和启动种子。间隔与验证码选项按次读数据库。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from datetime import datetime, timezone
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from admin.identity import identity
|
|
from admin.models import SystemConfig
|
|
from admin.passwords import default_password, hash_password, is_hashed, min_length
|
|
from euniv.crypto import decrypt_secret
|
|
|
|
_INITIAL_USERNAME = "admin"
|
|
|
|
|
|
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 _configured_admin_password() -> str | None:
|
|
value = os.environ.get("EUNIV_ADMIN_PASSWORD", "").strip()
|
|
if not value:
|
|
return None
|
|
if len(value) < min_length():
|
|
raise RuntimeError(f"EUNIV_ADMIN_PASSWORD 至少需要 {min_length()} 位")
|
|
return value
|
|
|
|
|
|
def _new_admin_password() -> str:
|
|
configured = _configured_admin_password()
|
|
if configured is not None:
|
|
return configured
|
|
return default_password()
|
|
|
|
|
|
def _reversible_password(stored: str) -> str | None:
|
|
if is_hashed(stored):
|
|
return None
|
|
try:
|
|
return decrypt_secret(stored)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def ensure_admin_seed() -> None:
|
|
"""没有配置时创建管理员。旧的默认口令会作废,可逆密文会改成哈希。"""
|
|
from euniv.db import SessionLocal
|
|
|
|
reset = os.environ.get("EUNIV_ADMIN_RESET", "").strip() == "1"
|
|
with SessionLocal() as db:
|
|
row = db.scalars(select(SystemConfig).limit(1)).first()
|
|
if row is None:
|
|
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=hash_password(_new_admin_password()),
|
|
)
|
|
)
|
|
db.commit()
|
|
return
|
|
if reset:
|
|
configured = _configured_admin_password()
|
|
if configured is None:
|
|
raise RuntimeError("EUNIV_ADMIN_RESET=1 时必须设置 EUNIV_ADMIN_PASSWORD")
|
|
row.admin_password_cipher = hash_password(configured)
|
|
db.commit()
|
|
return
|
|
plain = _reversible_password(row.admin_password_cipher)
|
|
if plain is None:
|
|
return
|
|
row.admin_password_cipher = hash_password(plain)
|
|
db.commit()
|
|
|
|
|
|
def ensure_key_check() -> None:
|
|
"""密钥太短、是占位文字,或解不开已有数据时,拒绝启动。"""
|
|
from euniv.crypto import decrypt_secret, encrypt_secret, require_secret
|
|
from euniv.db import SessionLocal
|
|
|
|
require_secret()
|
|
with SessionLocal() as db:
|
|
row = load_config(db)
|
|
if not row.key_check:
|
|
row.key_check = encrypt_secret("euniv-key-check")
|
|
db.commit()
|
|
return
|
|
try:
|
|
matched = decrypt_secret(row.key_check) == "euniv-key-check"
|
|
except Exception as exc:
|
|
raise RuntimeError("EUNIV_SECRET_KEY 与已有数据不匹配,已停止启动") from exc
|
|
if not matched:
|
|
raise RuntimeError("EUNIV_SECRET_KEY 与已有数据不匹配,已停止启动")
|
|
|
|
|
|
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() -> int:
|
|
from euniv.db import SessionLocal
|
|
|
|
with SessionLocal() as owned:
|
|
return int(load_config(owned).refresh_interval_minutes) * 60
|
|
|
|
|
|
def auto_attempt_count(db: Session) -> int:
|
|
return int(load_config(db).auto_jigsaw_attempts)
|
|
|
|
|
|
def heartbeat_intervals() -> dict:
|
|
"""返回 {mode, video, document, scorm}。mode 为 'auto' 时三个值仅作备用。"""
|
|
from euniv.db import SessionLocal
|
|
|
|
with SessionLocal() as owned:
|
|
row = load_config(owned)
|
|
return {
|
|
"mode": row.heartbeat_interval_mode or "manual",
|
|
"video": int(row.heartbeat_video_seconds),
|
|
"document": int(row.heartbeat_document_seconds),
|
|
"scorm": int(row.heartbeat_scorm_seconds),
|
|
}
|
|
|
|
|
|
def hours_source_of(row: SystemConfig | None = None) -> str:
|
|
"""api:接口本月学时;history:学时历史本月分钟合计。"""
|
|
if row is None:
|
|
from euniv.db import SessionLocal
|
|
|
|
with SessionLocal() as owned:
|
|
return hours_source_of(load_config(owned))
|
|
value = str(row.hours_source or "api").strip().lower()
|
|
return value if value in ("api", "history") else "api"
|
|
|
|
|
|
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,
|
|
"heartbeat_interval_mode": row.heartbeat_interval_mode or "manual",
|
|
"heartbeat_video_seconds": int(row.heartbeat_video_seconds),
|
|
"heartbeat_document_seconds": int(row.heartbeat_document_seconds),
|
|
"heartbeat_scorm_seconds": int(row.heartbeat_scorm_seconds),
|
|
"hours_source": hours_source_of(row),
|
|
}
|
|
|
|
|
|
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 个字符")
|
|
from euniv.models import Account
|
|
|
|
if db.get(Account, username) is not None:
|
|
raise SettingsError("管理员用户名不能与已有工号相同")
|
|
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 != "":
|
|
if len(str(password)) < min_length():
|
|
raise SettingsError(f"管理员密码至少 {min_length()} 位")
|
|
if len(str(password)) > 128:
|
|
raise SettingsError("管理员密码过长")
|
|
|
|
hb_mode = str(payload.get("heartbeat_interval_mode") or "manual")
|
|
if hb_mode not in ("auto", "manual"):
|
|
raise SettingsError("心跳间隔模式须为 auto 或 manual")
|
|
hb_video = _as_int(payload.get("heartbeat_video_seconds"))
|
|
hb_doc = _as_int(payload.get("heartbeat_document_seconds"))
|
|
hb_scorm = _as_int(payload.get("heartbeat_scorm_seconds"))
|
|
if hb_video is None or not 0 <= hb_video <= 300:
|
|
raise SettingsError("视频心跳间隔须为 0 到 300 的整数")
|
|
if hb_doc is None or not 0 <= hb_doc <= 600:
|
|
raise SettingsError("文档心跳间隔须为 0 到 600 的整数")
|
|
if hb_scorm is None or not 0 <= hb_scorm <= 600:
|
|
raise SettingsError("Scorm 心跳间隔须为 0 到 600 的整数")
|
|
source = str(payload.get("hours_source") or "api").strip().lower()
|
|
if source not in ("api", "history"):
|
|
raise SettingsError("学时达标依据须为 api 或 history")
|
|
|
|
row = load_config(db)
|
|
previous_interval = int(row.refresh_interval_minutes)
|
|
previous_username = row.admin_username
|
|
previous_source = hours_source_of(row)
|
|
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
|
|
password_text = "" if password is None else str(password)
|
|
if password_text:
|
|
current = str(payload.get("admin_password_current") or "")
|
|
if not identity.password_ok(current):
|
|
raise SettingsError("当前管理员密码不正确")
|
|
row.admin_username = username
|
|
row.heartbeat_interval_mode = hb_mode
|
|
row.heartbeat_video_seconds = hb_video
|
|
row.heartbeat_document_seconds = hb_doc
|
|
row.heartbeat_scorm_seconds = hb_scorm
|
|
row.hours_source = source
|
|
if password_text:
|
|
row.admin_password_cipher = hash_password(password_text)
|
|
if previous_username != username or password_text:
|
|
row.admin_sessions_valid_after = datetime.now(timezone.utc)
|
|
with identity.exclusive():
|
|
db.commit()
|
|
identity.replace(row.admin_username, row.admin_password_cipher)
|
|
if interval != previous_interval:
|
|
from euniv.service import notify_refresh_interval_changed
|
|
|
|
notify_refresh_interval_changed()
|
|
if source != previous_source:
|
|
from euniv.service import notify_hours_source_changed
|
|
|
|
notify_hours_source_changed()
|
|
return row
|