343 lines
14 KiB
Python
343 lines
14 KiB
Python
"""认证与授权服务:口令散列、会话令牌、请求级当前用户、账号播种。
|
||
|
||
平台跑在局域网里,之前所有人共用一个「隐形管理员」,谁改了模型配置、
|
||
谁把分镜删了都查不到人。这一层把「是谁在做」补齐:
|
||
|
||
* 口令:PBKDF2-HMAC-SHA256(stdlib,无编译依赖),恒定时间比较;
|
||
* 会话:不透明 token 只以 SHA-256 落库,浏览器拿 HttpOnly Cookie,
|
||
同时兼容 `Authorization: Bearer`(给脚本/curl 用);
|
||
* 上下文:用 contextvar 保存当前请求的用户,`events.log_event` 默认拿它当 actor,
|
||
这样审计留痕不用改几十个调用点。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import contextvars
|
||
import hashlib
|
||
import hmac
|
||
import logging
|
||
import re
|
||
import secrets
|
||
from contextlib import contextmanager
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
from sqlalchemy import delete, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from app.config import settings
|
||
from app.models import EventLog, User, UserSession
|
||
from app.models.base import as_utc, now_utc
|
||
from app.models.user import Role
|
||
|
||
logger = logging.getLogger("nex.auth")
|
||
|
||
PBKDF2_ITERATIONS = 180_000 # 仅作文档性默认值,实际取 settings.password_iterations
|
||
USERNAME_RE = re.compile(r"^[a-zA-Z0-9_.\-一-鿿]{2,60}$")
|
||
|
||
# ------------------------------------------------------------------ 口令
|
||
def hash_password(password: str, *, iterations: int | None = None) -> str:
|
||
iterations = int(iterations or settings.password_iterations)
|
||
salt = secrets.token_urlsafe(16)
|
||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode("utf-8"), iterations)
|
||
return f"pbkdf2_sha256${iterations}${salt}${digest.hex()}"
|
||
|
||
|
||
def verify_password(password: str, stored: str) -> bool:
|
||
if not stored or not password:
|
||
return False
|
||
try:
|
||
scheme, iterations, salt, hexdigest = stored.split("$", 3)
|
||
except ValueError:
|
||
return False
|
||
if scheme != "pbkdf2_sha256":
|
||
return False
|
||
candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode("utf-8"), int(iterations))
|
||
return hmac.compare_digest(candidate.hex(), hexdigest)
|
||
|
||
|
||
def password_problem(password: str, *, username: str = "") -> str:
|
||
"""口令强度:返回问题描述,空串表示合格。"""
|
||
minimum = max(6, settings.password_min_length)
|
||
if len(password or "") < minimum:
|
||
return f"密码至少 {minimum} 位"
|
||
if username and (password == username or password in f"{username}{username}"):
|
||
return "密码不能与登录名相同"
|
||
if password in ("12345678", "password", "qwertyui"):
|
||
return "密码过于常见,请换一个"
|
||
return ""
|
||
|
||
|
||
# ------------------------------------------------------------------ 会话令牌
|
||
def new_token() -> str:
|
||
return secrets.token_urlsafe(32)
|
||
|
||
|
||
def _hash_token(token: str) -> str:
|
||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||
|
||
|
||
def ttl() -> timedelta:
|
||
return timedelta(hours=max(1, settings.session_ttl_hours))
|
||
|
||
|
||
def issue_session(db: Session, user: User, *, ip: str = "", label: str = "") -> tuple[UserSession, str]:
|
||
"""签发一次登录会话,返回 (会话行, 明文 token)。明文只在响应里出现一次。"""
|
||
token = new_token()
|
||
session = UserSession(user_id=user.id, token_hash=_hash_token(token),
|
||
ip=ip[:64], label=label[:120], expires_at=now_utc() + ttl())
|
||
db.add(session)
|
||
user.last_login_at = now_utc()
|
||
user.last_login_ip = ip[:64]
|
||
user.login_count = int(user.login_count or 0) + 1
|
||
db.commit()
|
||
db.refresh(session)
|
||
return session, token
|
||
|
||
|
||
def resolve_token(db: Session, token: str) -> tuple[User | None, UserSession | None]:
|
||
if not token:
|
||
return None, None
|
||
session = db.scalars(select(UserSession).where(UserSession.token_hash == _hash_token(token))).first()
|
||
if session is None:
|
||
return None, None
|
||
if session.revoked_at is not None or as_utc(session.expires_at) <= now_utc():
|
||
return None, session
|
||
user = db.get(User, session.user_id)
|
||
if user is None or not user.is_active:
|
||
return None, session
|
||
_touch(db, session)
|
||
return user, session
|
||
|
||
|
||
def _touch(db: Session, session: UserSession) -> None:
|
||
"""滑动续期:距上次记录超过 1 分钟才写库;剩余寿命过半才延长过期时间。
|
||
|
||
每个静态缩略图请求都会命中这里,不加节流会把浏览变成写放大。
|
||
"""
|
||
stamp = now_utc()
|
||
if (stamp - as_utc(session.last_seen_at)).total_seconds() < 60:
|
||
return
|
||
session.last_seen_at = stamp
|
||
if as_utc(session.expires_at) - stamp < ttl() / 2:
|
||
session.expires_at = stamp + ttl()
|
||
db.commit()
|
||
|
||
|
||
def revoke(db: Session, session: UserSession) -> None:
|
||
session.revoked_at = now_utc()
|
||
db.commit()
|
||
|
||
|
||
def revoke_all(db: Session, user_id: int, *, except_session_id: int | None = None) -> int:
|
||
stmt = select(UserSession).where(UserSession.user_id == user_id, UserSession.revoked_at.is_(None))
|
||
if except_session_id:
|
||
stmt = stmt.where(UserSession.id != except_session_id)
|
||
rows = list(db.scalars(stmt).all())
|
||
for row in rows:
|
||
row.revoked_at = now_utc()
|
||
db.commit()
|
||
return len(rows)
|
||
|
||
|
||
def purge_expired(db: Session, *, keep_days: int = 30) -> int:
|
||
"""清掉早已失效的历史会话行(保留期内的撤销记录留在库里做审计)。"""
|
||
cutoff = now_utc() - timedelta(days=max(1, keep_days))
|
||
result = db.execute(delete(UserSession).where(UserSession.expires_at < cutoff))
|
||
db.commit()
|
||
return int(result.rowcount or 0)
|
||
|
||
|
||
def active_sessions(db: Session, user_id: int) -> list[UserSession]:
|
||
rows = db.scalars(select(UserSession).where(UserSession.user_id == user_id)
|
||
.order_by(UserSession.last_seen_at.desc())).all()
|
||
return [row for row in rows if row.active]
|
||
|
||
|
||
# ------------------------------------------------------------------ 请求上下文
|
||
_current_user: contextvars.ContextVar[User | None] = contextvars.ContextVar("nex_current_user", default=None)
|
||
|
||
|
||
def local_user() -> User:
|
||
"""AUTH_ENABLED=false 时给中间件用的虚拟管理员:不落库,只让端点照常跑。"""
|
||
user = User(id=0, username="local", display_name="本地模式", email="",
|
||
password_hash="", role=Role.ADMIN, is_active=True, must_change_password=False)
|
||
return user
|
||
|
||
|
||
def current_user() -> User | None:
|
||
return _current_user.get()
|
||
|
||
|
||
def actor_name() -> str:
|
||
"""给 events.log_event 用的操作人标识。
|
||
|
||
用**登录名**而不是显示名:显示名可以重名、可以随便改,写进审计流水就再也对不回
|
||
账号;而且项目状态里的 created_by/updated_by 存的也是登录名,两边必须是同一个口径,
|
||
否则同一个人在「流程事件」里叫「平台管理员」、在「基本信息」里叫 admin。
|
||
"""
|
||
user = _current_user.get()
|
||
if user is None:
|
||
return ""
|
||
return user.username
|
||
|
||
|
||
@contextmanager
|
||
def request_context(user: User | None):
|
||
token = _current_user.set(user)
|
||
try:
|
||
yield
|
||
finally:
|
||
_current_user.reset(token)
|
||
|
||
|
||
# ------------------------------------------------------------------ 序列化
|
||
def public_user(db: Session, user: User) -> dict:
|
||
return {
|
||
"id": user.id,
|
||
"username": user.username,
|
||
"display_name": user.display_name or user.username,
|
||
"email": user.email or "",
|
||
"role": user.role,
|
||
"role_label": Role.label(user.role),
|
||
"is_active": bool(user.is_active),
|
||
"must_change_password": bool(user.must_change_password),
|
||
"note": user.note or "",
|
||
"prefs": user.prefs_json or {},
|
||
"last_login_at": user.last_login_at,
|
||
"last_login_ip": user.last_login_ip or "",
|
||
"login_count": int(user.login_count or 0),
|
||
"created_at": user.created_at,
|
||
# 谁开的这个号:users.created_by_id 早就在存,但没随接口出来,
|
||
# 「用户管理」页看不到归属,出事后无法追到经办人。
|
||
"created_by_id": user.created_by_id,
|
||
"created_by": _username_of(db, user.created_by_id),
|
||
"active_sessions": len(active_sessions(db, user.id)),
|
||
}
|
||
|
||
|
||
def _username_of(db: Session, user_id: int | None) -> str:
|
||
if not user_id:
|
||
return ""
|
||
row = db.get(User, user_id)
|
||
return row.username if row is not None else ""
|
||
|
||
|
||
def public_session(row: UserSession, *, current_id: int | None = None) -> dict:
|
||
return {"id": row.id, "label": row.label or "未知设备", "ip": row.ip or "",
|
||
"created_at": row.created_at, "last_seen_at": row.last_seen_at, "expires_at": row.expires_at,
|
||
"active": bool(row.active), "current": current_id is not None and row.id == current_id}
|
||
|
||
|
||
# ------------------------------------------------------------------ 账号管理
|
||
class AuthError(Exception):
|
||
"""业务化的认证错误,API 层统一翻译成 401/403/400。"""
|
||
|
||
def __init__(self, status: int, detail: str) -> None:
|
||
super().__init__(detail)
|
||
self.status = status
|
||
self.detail = detail
|
||
|
||
|
||
def validate_username(username: str) -> str:
|
||
name = (username or "").strip()
|
||
if not USERNAME_RE.match(name):
|
||
raise AuthError(400, "登录名只能使用中英文、数字、下划线、点号与短横线,长度 2–60")
|
||
return name
|
||
|
||
|
||
def create_user(db: Session, *, username: str, password: str, display_name: str = "", email: str = "",
|
||
role: str = Role.EDITOR, actor: User | None = None, must_change: bool | None = None,
|
||
note: str = "") -> User:
|
||
name = validate_username(username)
|
||
if db.scalars(select(User).where(User.username == name)).first():
|
||
raise AuthError(409, "该登录名已存在")
|
||
if role not in Role.ALL:
|
||
raise AuthError(400, "角色只能是 管理员 / 制作 / 观摩")
|
||
problem = password_problem(password, username=name)
|
||
if problem:
|
||
raise AuthError(400, problem)
|
||
user = User(username=name, display_name=(display_name or name).strip()[:80], email=(email or "").strip()[:160],
|
||
password_hash=hash_password(password), role=role, is_active=True,
|
||
must_change_password=(password == settings.bootstrap_password) if must_change is None else must_change,
|
||
note=(note or "")[:500], prefs_json={}, created_by_id=actor.id if actor else None)
|
||
db.add(user)
|
||
db.flush()
|
||
log_audit(db, "user.created", message=f"新建账号 {user.username}({Role.label(user.role)})",
|
||
entity_type="user", entity_id=user.id, actor=actor)
|
||
db.commit()
|
||
db.refresh(user)
|
||
return user
|
||
|
||
|
||
def set_password(db: Session, user: User, password: str, *, actor: User | None = None,
|
||
revoke_sessions: bool = False, must_change: bool = False) -> None:
|
||
problem = password_problem(password, username=user.username)
|
||
if problem:
|
||
raise AuthError(400, problem)
|
||
user.password_hash = hash_password(password)
|
||
user.must_change_password = must_change
|
||
db.add(EventLog(project_id=None, level="info", action="user.password_changed", entity_type="user",
|
||
entity_id=user.id, message=f"重置 {user.username} 的登录密码",
|
||
data_json={"by": (actor.username if actor else "self")},
|
||
actor=(actor.username if actor else user.username)))
|
||
db.commit()
|
||
if revoke_sessions:
|
||
revoke_all(db, user.id)
|
||
|
||
|
||
def log_audit(db: Session, action: str, *, message: str = "", level: str = "info",
|
||
entity_type: str = "user", entity_id: int | None = None,
|
||
actor: User | None = None, data: dict | None = None, project_id: int | None = None) -> EventLog:
|
||
"""账号/登录类审计:复用事件流,前端「事件」页与项目事件同一条时间线。"""
|
||
event = EventLog(project_id=project_id, level=level, action=action, entity_type=entity_type,
|
||
entity_id=entity_id, message=message[:4000], data_json=data or {},
|
||
actor=(actor.username if actor else "system"))
|
||
db.add(event)
|
||
return event
|
||
|
||
|
||
def bootstrap(db: Session) -> User | None:
|
||
"""首次启动播种管理员;库里已有账号时什么都不做(幂等)。"""
|
||
if db.scalars(select(User).limit(1)).first() is not None:
|
||
return None
|
||
admin = User(username=settings.bootstrap_username,
|
||
display_name=settings.bootstrap_display_name,
|
||
email="", password_hash=hash_password(settings.bootstrap_password),
|
||
role=Role.ADMIN, is_active=True,
|
||
must_change_password=True,
|
||
note="系统初始化自动创建,请尽快修改默认密码", prefs_json={})
|
||
db.add(admin)
|
||
db.flush()
|
||
log_audit(db, "user.bootstrap", message=f"初始化管理员账号 {admin.username}", entity_id=admin.id)
|
||
db.commit()
|
||
db.refresh(admin)
|
||
logger.warning("已播种初始管理员 %s / %s —— 首次登录后请立即修改密码",
|
||
settings.bootstrap_username, settings.bootstrap_password)
|
||
return admin
|
||
|
||
|
||
def authenticate(db: Session, username: str, password: str) -> User:
|
||
name = (username or "").strip()
|
||
user = db.scalars(select(User).where(User.username == name)).first()
|
||
if user is None or not verify_password(password or "", user.password_hash):
|
||
log_audit(db, "user.login_failed", message=f"登录失败:{name or '(空账号)'}", level="warn")
|
||
db.commit()
|
||
raise AuthError(401, "登录名或密码不正确")
|
||
if not user.is_active:
|
||
raise AuthError(403, "该账号已被停用,请联系管理员")
|
||
return user
|
||
|
||
|
||
# ------------------------------------------------------------------ 统计
|
||
def counts(db: Session) -> dict:
|
||
rows = db.scalars(select(User)).all()
|
||
now = now_utc()
|
||
return {"total": len(rows),
|
||
"active": sum(1 for u in rows if u.is_active),
|
||
"disabled": sum(1 for u in rows if not u.is_active),
|
||
"admins": sum(1 for u in rows if u.role == Role.ADMIN and u.is_active),
|
||
"pending_password": sum(1 for u in rows if u.must_change_password and u.is_active),
|
||
"online": sum(1 for u in rows
|
||
if u.last_login_at
|
||
and (now - as_utc(u.last_login_at)).total_seconds() < 900),
|
||
"sessions": len([s for s in db.scalars(select(UserSession)).all() if s.active])}
|