fix: 管理员口令改为哈希并限制连续失败

This commit is contained in:
2026-11-16 02:35:15 +08:00
parent 77f80ad0e1
commit 0fbc3146d8
11 changed files with 209 additions and 26 deletions
+72 -18
View File
@@ -2,15 +2,20 @@
from __future__ import annotations
import logging
import os
import secrets
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
from admin.passwords import hash_password, is_hashed, legacy_password
from euniv.crypto import decrypt_secret
_INITIAL_USERNAME = "admin"
_INITIAL_PASSWORD = "242520"
_LOG = logging.getLogger("admin.settings")
class SettingsError(ValueError):
@@ -26,24 +31,66 @@ def load_config(db: Session) -> SystemConfig:
return row
def _configured_admin_password() -> str | None:
value = os.environ.get("EUNIV_ADMIN_PASSWORD", "").strip()
if not value:
return None
if len(value) < 8:
raise RuntimeError("EUNIV_ADMIN_PASSWORD 至少需要 8 位")
return value
def _new_admin_password() -> str:
configured = _configured_admin_password()
if configured is not None:
return configured
generated = secrets.token_urlsafe(12)
_LOG.warning("已生成随机管理员口令,请立即保存:%s", generated)
return generated
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:
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),
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
replacement = _new_admin_password() if plain == legacy_password() else plain
row.admin_password_cipher = hash_password(replacement)
db.commit()
@@ -140,6 +187,10 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
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:
@@ -147,8 +198,11 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
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("管理员密码过长")
if password is not None and password != "":
if len(str(password)) < 8:
raise SettingsError("管理员密码至少 8 位")
if len(str(password)) > 128:
raise SettingsError("管理员密码过长")
hb_mode = str(payload.get("heartbeat_interval_mode") or "manual")
if hb_mode not in ("auto", "manual"):
@@ -179,7 +233,7 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
row.heartbeat_scorm_seconds = hb_scorm
row.hours_source = source
if password is not None and password != "":
row.admin_password_cipher = encrypt_secret(str(password))
row.admin_password_cipher = hash_password(str(password))
db.commit()
identity.replace(row.admin_username, row.admin_password_cipher)
if interval != previous_interval: