初版:抖音自动续火花(从线上实例导出)
This commit is contained in:
+315
@@ -0,0 +1,315 @@
|
||||
"""用户注册表与会话令牌:为「按账号分权」提供身份校验。
|
||||
|
||||
- 用户保存在 data/users.json,密码仅存 PBKDF2-HMAC-SHA256 哈希(带随机盐),绝不存明文;
|
||||
- 会话令牌是 HMAC-SHA256 签名的「用户名|过期时间」字符串,无状态可校验、服务重启不失效,
|
||||
签名密钥首次启动时自动生成并保存到 data/auth_secret.key;
|
||||
- 兼容旧版:完全不改动 data/accounts/accounts.json 的结构。首次启动自动创建管理员账号
|
||||
admin(初始密码取 AUTH_TOKEN),历史账号默认全部归管理员,由管理员在网页「用户管理」
|
||||
中按需把账号分配给普通用户;未分配的账号对普通用户完全不可见。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .config import DATA_DIR
|
||||
|
||||
USERS_PATH = DATA_DIR / "users.json"
|
||||
SECRET_PATH = DATA_DIR / "auth_secret.key"
|
||||
|
||||
SESSION_COOKIE = "dcs_session"
|
||||
PBKDF2_ITERATIONS = 240_000
|
||||
USERNAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5]{2,32}$")
|
||||
MIN_PASSWORD_LEN = 6
|
||||
|
||||
ADMIN_USERNAME = "admin"
|
||||
|
||||
_lock = threading.Lock()
|
||||
_users_mtime_cache: tuple[float, list[dict]] | None = None
|
||||
_secret_cache: bytes | None = None
|
||||
|
||||
# 登录失败限流:同一用户名在窗口内连续失败达上限后锁定
|
||||
_login_guard = threading.Lock()
|
||||
_login_failures: dict[str, tuple[int, float]] = {} # username -> (失败次数, 窗口起点)
|
||||
MAX_LOGIN_FAILURES = 5
|
||||
LOGIN_FAILURE_WINDOW = 300 # 秒
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
# ── 密码哈希 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def hash_password(password: str, salt: bytes | None = None) -> str:
|
||||
salt = salt or secrets.token_bytes(16)
|
||||
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS)
|
||||
return f"{salt.hex()}${dk.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
salt_hex, dk_hex = str(stored).split("$", 1)
|
||||
dk = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), PBKDF2_ITERATIONS
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ── 用户注册表(data/users.json)──────────────────────────────────────────
|
||||
|
||||
|
||||
def _load_users() -> list[dict]:
|
||||
global _users_mtime_cache
|
||||
try:
|
||||
mtime = USERS_PATH.stat().st_mtime
|
||||
except OSError:
|
||||
return []
|
||||
if _users_mtime_cache and _users_mtime_cache[0] == mtime:
|
||||
return _users_mtime_cache[1]
|
||||
try:
|
||||
data = json.loads(USERS_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
data = []
|
||||
users = [u for u in data if isinstance(u, dict) and u.get("username")] if isinstance(data, list) else []
|
||||
_users_mtime_cache = (mtime, users)
|
||||
return users
|
||||
|
||||
|
||||
def _save_users(users: list[dict]) -> None:
|
||||
global _users_mtime_cache
|
||||
USERS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
USERS_PATH.write_text(
|
||||
json.dumps(users, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
try:
|
||||
USERS_PATH.chmod(0o600)
|
||||
except Exception:
|
||||
pass
|
||||
_users_mtime_cache = (USERS_PATH.stat().st_mtime, users)
|
||||
|
||||
|
||||
def _find(users: list[dict], username: str) -> dict | None:
|
||||
key = (username or "").strip().lower()
|
||||
for u in users:
|
||||
if str(u.get("username", "")).lower() == key:
|
||||
return u
|
||||
return None
|
||||
|
||||
|
||||
def get_user(username: str) -> dict | None:
|
||||
return _find(_load_users(), username)
|
||||
|
||||
|
||||
def public_user(u: dict) -> dict:
|
||||
return {k: v for k, v in u.items() if k != "password_hash"}
|
||||
|
||||
|
||||
def list_users() -> list[dict]:
|
||||
return [public_user(u) for u in sorted(_load_users(), key=lambda x: x.get("created_at", ""))]
|
||||
|
||||
|
||||
def admin_count(users: list[dict] | None = None) -> int:
|
||||
users = users if users is not None else _load_users()
|
||||
return sum(1 for u in users if u.get("is_admin"))
|
||||
|
||||
|
||||
def validate_username(username: str) -> str:
|
||||
name = (username or "").strip()
|
||||
if not USERNAME_RE.match(name):
|
||||
raise ValueError("用户名需为 2~32 位中文、字母、数字或下划线")
|
||||
return name
|
||||
|
||||
|
||||
def validate_password(password: str) -> str:
|
||||
pwd = password or ""
|
||||
if len(pwd) < MIN_PASSWORD_LEN:
|
||||
raise ValueError(f"密码长度至少 {MIN_PASSWORD_LEN} 位")
|
||||
if len(pwd) > 128:
|
||||
raise ValueError("密码过长")
|
||||
return pwd
|
||||
|
||||
|
||||
def create_user(
|
||||
username: str,
|
||||
password: str,
|
||||
is_admin: bool = False,
|
||||
account_ids: list[str] | None = None,
|
||||
) -> dict:
|
||||
name = validate_username(username)
|
||||
validate_password(password)
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
if _find(users, name):
|
||||
raise ValueError(f"用户名已存在:{name}")
|
||||
user = {
|
||||
"username": name,
|
||||
"password_hash": hash_password(password),
|
||||
"is_admin": bool(is_admin),
|
||||
"account_ids": [str(a).strip() for a in (account_ids or []) if str(a).strip()],
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
users.append(user)
|
||||
_save_users(users)
|
||||
return user
|
||||
|
||||
|
||||
def update_user(
|
||||
username: str,
|
||||
password: str | None = None,
|
||||
account_ids: list[str] | None = None,
|
||||
is_admin: bool | None = None,
|
||||
) -> dict | None:
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
user = _find(users, username)
|
||||
if user is None:
|
||||
return None
|
||||
if password is not None:
|
||||
validate_password(password)
|
||||
user["password_hash"] = hash_password(password)
|
||||
if account_ids is not None:
|
||||
user["account_ids"] = [str(a).strip() for a in account_ids if str(a).strip()]
|
||||
if is_admin is not None and user.get("is_admin") and not is_admin and admin_count(users) <= 1:
|
||||
raise ValueError("至少保留一个管理员账号")
|
||||
if is_admin is not None:
|
||||
user["is_admin"] = bool(is_admin)
|
||||
user["updated_at"] = _now()
|
||||
_save_users(users)
|
||||
return user
|
||||
|
||||
|
||||
def delete_user(username: str) -> bool:
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
user = _find(users, username)
|
||||
if user is None:
|
||||
return False
|
||||
if user.get("is_admin") and admin_count(users) <= 1:
|
||||
raise ValueError("至少保留一个管理员账号,不能删除")
|
||||
users.remove(user)
|
||||
_save_users(users)
|
||||
return True
|
||||
|
||||
|
||||
def authenticate(username: str, password: str) -> dict | None:
|
||||
user = get_user(username)
|
||||
if user is None:
|
||||
hash_password(password) # 防用户枚举:不存在的用户也执行一次等价哈希
|
||||
return None
|
||||
if not verify_password(password, user.get("password_hash", "")):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def ensure_admin(initial_password: str) -> bool:
|
||||
"""首次启动播种管理员账号(旧部署升级零迁移);已有管理员则不做事。返回是否新建。"""
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
if any(u.get("is_admin") for u in users):
|
||||
return False
|
||||
existing = _find(users, ADMIN_USERNAME)
|
||||
if existing:
|
||||
existing["is_admin"] = True
|
||||
existing["updated_at"] = _now()
|
||||
else:
|
||||
users.append({
|
||||
"username": ADMIN_USERNAME,
|
||||
"password_hash": hash_password(initial_password),
|
||||
"is_admin": True,
|
||||
"account_ids": [],
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
})
|
||||
_save_users(users)
|
||||
return True
|
||||
|
||||
|
||||
# ── 会话令牌(HMAC 签名,无状态)─────────────────────────────────────────
|
||||
|
||||
|
||||
def _secret_key() -> bytes:
|
||||
global _secret_cache
|
||||
if _secret_cache:
|
||||
return _secret_cache
|
||||
try:
|
||||
key = SECRET_PATH.read_bytes().strip()
|
||||
if len(key) >= 32:
|
||||
_secret_cache = key
|
||||
return key
|
||||
except OSError:
|
||||
pass
|
||||
key = secrets.token_hex(32).encode("ascii")
|
||||
SECRET_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
SECRET_PATH.write_bytes(key)
|
||||
try:
|
||||
SECRET_PATH.chmod(0o600)
|
||||
except Exception:
|
||||
pass
|
||||
_secret_cache = key
|
||||
return key
|
||||
|
||||
|
||||
def create_session(username: str, ttl_hours: float = 168) -> str:
|
||||
exp = int(time.time()) + int(ttl_hours * 3600)
|
||||
payload = f"{username}|{exp}"
|
||||
sig = hmac.new(_secret_key(), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return base64.urlsafe_b64encode(f"{payload}|{sig}".encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def verify_session(token: str) -> str | None:
|
||||
"""校验会话令牌,返回用户名;无效或过期返回 None。"""
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token.encode("ascii")).decode("utf-8")
|
||||
username, exp, sig = raw.split("|", 2)
|
||||
expect = hmac.new(
|
||||
_secret_key(), f"{username}|{exp}".encode("utf-8"), hashlib.sha256
|
||||
).hexdigest()
|
||||
if not hmac.compare_digest(expect, sig):
|
||||
return None
|
||||
if int(exp) < time.time():
|
||||
return None
|
||||
return username
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
# ── 登录失败限流 ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def is_locked(username: str) -> bool:
|
||||
with _login_guard:
|
||||
rec = _login_failures.get((username or "").lower())
|
||||
if not rec:
|
||||
return False
|
||||
count, window_start = rec
|
||||
if time.time() - window_start > LOGIN_FAILURE_WINDOW:
|
||||
return False
|
||||
return count >= MAX_LOGIN_FAILURES
|
||||
|
||||
|
||||
def register_login_failure(username: str) -> None:
|
||||
with _login_guard:
|
||||
key = (username or "").lower()
|
||||
count, window_start = _login_failures.get(key, (0, time.time()))
|
||||
if time.time() - window_start > LOGIN_FAILURE_WINDOW:
|
||||
count, window_start = 0, time.time()
|
||||
_login_failures[key] = (count + 1, window_start)
|
||||
|
||||
|
||||
def clear_login_failures(username: str) -> None:
|
||||
with _login_guard:
|
||||
_login_failures.pop((username or "").lower(), None)
|
||||
Reference in New Issue
Block a user