nex_animation/backend/app/models/user.py

83 lines
3.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""用户体系:账号、角色与会话。
设计约束(和平台现有实现保持一致,不引入新依赖):
* 口令只存 PBKDF2-HMAC-SHA256 派生值(stdlib `hashlib`),不落明文、不用 bcrypt/
passlib 之类需要编译的第三方库——本机与 Docker 里都能直接跑。
* 会话是**服务端可撤销**的不透明 token:库里只存 token 的 SHA-256,
即使 DB 泄漏也拿不到可用的登录态;浏览器侧只拿 HttpOnly Cookie。
* 角色只有三档,够覆盖「谁能改配置、谁能跑生成、谁只能看」,
避免为一个小团队的本地平台做出一个用不完的 RBAC 矩阵。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
from app.models.base import TimestampMixin, as_utc, now_utc
class Role:
"""角色常量(字符串存库,便于后续加档而不改枚举迁移)。"""
ADMIN = "admin" # 管理员:账号、模型配置、全部项目
EDITOR = "editor" # 制作:建项目、改资产、发起生成与合成
VIEWER = "viewer" # 观摩:只读
ALL = (ADMIN, EDITOR, VIEWER)
LABELS = {ADMIN: "管理员", EDITOR: "制作", VIEWER: "观摩"}
RANK = {VIEWER: 1, EDITOR: 2, ADMIN: 3}
@classmethod
def label(cls, value: str) -> str:
return cls.LABELS.get(value, value)
@classmethod
def at_least(cls, value: str, minimum: str) -> bool:
return cls.RANK.get(value, 0) >= cls.RANK.get(minimum, 99)
class User(TimestampMixin, Base):
"""平台账号。"""
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
display_name: Mapped[str] = mapped_column(String(80), default="")
email: Mapped[str] = mapped_column(String(160), default="")
password_hash: Mapped[str] = mapped_column(String(300), default="")
role: Mapped[str] = mapped_column(String(16), default=Role.EDITOR, index=True)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
# 管理员建号/重置口令时置 1:前端拿到这个标记就强制先改密再进工作台。
must_change_password: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
note: Mapped[str] = mapped_column(Text, default="")
prefs_json: Mapped[dict] = mapped_column(JSON, default=dict)
created_by_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_login_ip: Mapped[str] = mapped_column(String(64), default="")
login_count: Mapped[int] = mapped_column(Integer, default=0)
class UserSession(Base):
"""一次登录 = 一行;撤销(退出/被踢/禁用)只写 revoked_at,保留审计线索。"""
__tablename__ = "user_sessions"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
label: Mapped[str] = mapped_column(String(120), default="") # 浏览器/UA 摘要
ip: Mapped[str] = mapped_column(String(64), default="")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, nullable=False)
last_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
@property
def active(self) -> bool:
return self.revoked_at is None and as_utc(self.expires_at) > now_utc()