"""ORM model for the users table. Lives in the harness persistence package so it is picked up by ``Base.metadata.create_all()`` alongside ``threads_meta``, ``runs``, ``run_events``, and ``feedback``. Using the shared engine means: - One SQLite/Postgres database, one connection pool - One schema initialisation codepath - Consistent async sessions across auth and persistence reads """ from __future__ import annotations from datetime import UTC, datetime from sqlalchemy import Boolean, Index, String, text from sqlalchemy.orm import Mapped, mapped_column from deerflow.persistence.base import Base from deerflow.persistence.types import BeijingDateTime class UserRow(Base): __tablename__ = "users" # UUIDs are stored as 36-char strings for cross-backend portability. id: Mapped[str] = mapped_column(String(36), primary_key=True) email: Mapped[str] = mapped_column(String(191), unique=True, nullable=False, index=True) password_hash: Mapped[str | None] = mapped_column(String(128), nullable=True) # "admin" | "user" — kept as plain string to avoid ALTER TABLE pain # when new roles are introduced. system_role: Mapped[str] = mapped_column(String(16), nullable=False, default="user") created_at: Mapped[datetime] = mapped_column( BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC), ) # OAuth linkage (optional). A partial unique index enforces one # account per (provider, oauth_id) pair, leaving NULL/NULL rows # unconstrained so plain password accounts can coexist. oauth_provider: Mapped[str | None] = mapped_column(String(32), nullable=True) oauth_id: Mapped[str | None] = mapped_column(String(128), nullable=True) # Auth lifecycle flags needs_setup: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) token_version: Mapped[int] = mapped_column(nullable=False, default=0) # 登录白名单(放行)标记 —— **黑名单模式**。仅当系统设置 ``login_whitelist.enabled`` # 打开时生效:关 → 忽略此列,人人可登录;开 → 仅 approved=False(被管理员显式 # 「取消放行」)的用户被拦,其余(含从未登录过的新账号)放行。新账号默认 True # (首次登录即放行);存量用户由迁移回填 True。server_default=1 让迁移 ADD COLUMN # 时把已存在行置为已放行。 approved: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text("1")) # 管理员在「白名单管理」页给个别账号设置的「登录口令」(**明文**)。非空 → 该账号的 # 用户名直登(``POST /api/v1/auth/login/username``)必须带 ``?password=`` 且与此值 # 完全一致才放行(优先于全局共享口令门);为空/NULL → 走原有逻辑(全局共享口令门 # 或免口令)。明文存储是有意为之:口令本就以 URL query 明文传输,存明文才能让管理员 # 随时复制完整登录链接 ``…/login/<用户名>?password=xxxx``。仅 admin 可读写。 login_password: Mapped[str | None] = mapped_column(String(255), nullable=True) # 岗位 (position) the user is assigned to (1:1). NULL = no explicit # position → the user inherits the ``is_default`` position's grants. Drives # the subscription sync engine (see ``deerflow.services.position_sync``). position_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True) __table_args__ = ( Index( "idx_users_oauth_identity", "oauth_provider", "oauth_id", unique=True, sqlite_where=text("oauth_provider IS NOT NULL AND oauth_id IS NOT NULL"), ), )