feat(auth): 新增手机号与 DCAuth 设备认证登录
- 登录链路改为用户名 + 密码 + 短信验证码 + DCAuth v2 设备签名 - 新增 login_sms_codes / user_devices / device_challenges 三张表,迁移 0063/0064 - 设备绑定只比对 deviceId + publicKey,每账号一个 active 设备,管理员可重置 - 保留未绑定手机号账号的密码登录兜底,绑定后强制安全登录 - 登录页与用户管理页支持验证码、DCAuth 轮询、手机号绑定与设备重置
This commit is contained in:
@@ -0,0 +1,301 @@
|
||||
"""账号安全登录:手机号、短信验证码、DCAuth 设备认证。
|
||||
|
||||
登录链路:用户名 + 密码 + 短信验证码 + DCAuth v2 设备签名。
|
||||
旧账号未绑定手机号时仍可使用原密码登录;绑定手机号后强制走新链路。
|
||||
|
||||
MySQL 不支持 PostgreSQL 那种部分唯一索引,这里用“函数索引”实现同样的约束:
|
||||
- users.phone_unique = NULLIF(phone, ''),唯一索引 ⇒ 非空手机号唯一;
|
||||
- user_devices 上建 UNIQUE ((CASE WHEN status='active' THEN user_id END)) ⇒ 每个用户最多一个 active 设备。
|
||||
不用生成列,是因为 MySQL 禁止“生成列依赖的基列上带 ON DELETE CASCADE 的外键”。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261021_0063"
|
||||
down_revision: str | None = "20261020_0062"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
USERS = "users"
|
||||
SMS = "login_sms_codes"
|
||||
DEVICES = "user_devices"
|
||||
CHALLENGES = "device_challenges"
|
||||
|
||||
|
||||
def _table_names(bind) -> set[str]:
|
||||
return set(sa.inspect(bind).get_table_names())
|
||||
|
||||
|
||||
def _column_names(bind, table: str) -> set[str]:
|
||||
return {column["name"] for column in sa.inspect(bind).get_columns(table)}
|
||||
|
||||
|
||||
def _index_names(bind, table: str) -> set[str]:
|
||||
return {index["name"] for index in sa.inspect(bind).get_indexes(table)}
|
||||
|
||||
|
||||
def _fk_names(bind, table: str) -> set[str]:
|
||||
return {
|
||||
fk.get("name", "")
|
||||
for fk in sa.inspect(bind).get_foreign_keys(table)
|
||||
if fk.get("name")
|
||||
}
|
||||
|
||||
|
||||
def _upgrade_users(bind) -> None:
|
||||
columns = _column_names(bind, USERS)
|
||||
indexes = _index_names(bind, USERS)
|
||||
dialect = bind.dialect.name
|
||||
|
||||
additions = []
|
||||
if "phone" not in columns:
|
||||
additions.append(
|
||||
sa.Column(
|
||||
"phone",
|
||||
sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
)
|
||||
)
|
||||
if "phone_bound_at" not in columns:
|
||||
additions.append(sa.Column("phone_bound_at", sa.DateTime(), nullable=True))
|
||||
if "phone_bound_by" not in columns:
|
||||
additions.append(sa.Column("phone_bound_by", sa.Integer(), nullable=True))
|
||||
if "phone_unique" not in columns:
|
||||
additions.append(
|
||||
sa.Column(
|
||||
"phone_unique",
|
||||
sa.String(length=32),
|
||||
sa.Computed("NULLIF(phone, '')", persisted=True),
|
||||
nullable=True,
|
||||
)
|
||||
)
|
||||
|
||||
fk_name = "fk_users_phone_bound_by"
|
||||
needs_fk = fk_name not in _fk_names(bind, USERS)
|
||||
needs_index = "uq_users_phone_unique" not in indexes
|
||||
|
||||
if dialect == "sqlite":
|
||||
# SQLite 不支持 ALTER TABLE ADD GENERATED COLUMN,走 batch 重建。
|
||||
with op.batch_alter_table(USERS) as batch:
|
||||
for column in additions:
|
||||
batch.add_column(column)
|
||||
if needs_fk:
|
||||
batch.create_foreign_key(
|
||||
fk_name,
|
||||
USERS,
|
||||
["phone_bound_by"],
|
||||
["id"],
|
||||
ondelete="SET NULL",
|
||||
)
|
||||
if needs_index:
|
||||
batch.create_index(
|
||||
"uq_users_phone_unique", ["phone_unique"], unique=True
|
||||
)
|
||||
return
|
||||
|
||||
for column in additions:
|
||||
op.add_column(USERS, column)
|
||||
if needs_fk:
|
||||
op.create_foreign_key(
|
||||
fk_name,
|
||||
USERS,
|
||||
USERS,
|
||||
["phone_bound_by"],
|
||||
["id"],
|
||||
ondelete="SET NULL",
|
||||
)
|
||||
if needs_index:
|
||||
op.create_index("uq_users_phone_unique", USERS, ["phone_unique"], unique=True)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
tables = _table_names(bind)
|
||||
|
||||
if USERS in tables:
|
||||
_upgrade_users(bind)
|
||||
|
||||
if SMS not in tables:
|
||||
op.create_table(
|
||||
SMS,
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("phone", sa.String(length=32), nullable=False, server_default=""),
|
||||
sa.Column(
|
||||
"purpose", sa.String(length=16), nullable=False, server_default="login"
|
||||
),
|
||||
sa.Column("code_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("consumed_at", sa.DateTime(), nullable=True),
|
||||
sa.Column(
|
||||
"failed_attempt_count",
|
||||
sa.Integer(),
|
||||
nullable=False,
|
||||
server_default="0",
|
||||
),
|
||||
sa.Column(
|
||||
"request_ip", sa.String(length=64), nullable=False, server_default=""
|
||||
),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
[f"{USERS}.id"],
|
||||
name="fk_login_sms_codes_user_id",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_login_sms_codes_user_created",
|
||||
SMS,
|
||||
["user_id", "purpose", "created_at"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_login_sms_codes_phone_created", SMS, ["phone", "created_at"]
|
||||
)
|
||||
|
||||
if DEVICES not in tables:
|
||||
op.create_table(
|
||||
DEVICES,
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("device_id", sa.String(length=96), nullable=False),
|
||||
sa.Column("public_key", sa.String(length=128), nullable=False),
|
||||
sa.Column(
|
||||
"client_version",
|
||||
sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"status", sa.String(length=16), nullable=False, server_default="active"
|
||||
),
|
||||
sa.Column("bound_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("last_used_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("revoked_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("revoked_by", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
[f"{USERS}.id"],
|
||||
name="fk_user_devices_user_id",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["revoked_by"],
|
||||
[f"{USERS}.id"],
|
||||
name="fk_user_devices_revoked_by",
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"uq_user_devices_active_user",
|
||||
DEVICES,
|
||||
[sa.text("(CASE WHEN status = 'active' THEN user_id ELSE NULL END)")],
|
||||
unique=True,
|
||||
)
|
||||
op.create_index("ix_user_devices_device_id", DEVICES, ["device_id"])
|
||||
|
||||
if CHALLENGES not in tables:
|
||||
op.create_table(
|
||||
CHALLENGES,
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("challenge_id", sa.String(length=64), nullable=False),
|
||||
sa.Column("app", sa.String(length=32), nullable=False),
|
||||
sa.Column(
|
||||
"purpose", sa.String(length=16), nullable=False, server_default="login"
|
||||
),
|
||||
sa.Column("challenge", sa.String(length=128), nullable=False),
|
||||
sa.Column("poll_token_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
"status",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="pending",
|
||||
),
|
||||
sa.Column("user_id", sa.Integer(), nullable=True),
|
||||
sa.Column(
|
||||
"device_id", sa.String(length=96), nullable=False, server_default=""
|
||||
),
|
||||
sa.Column(
|
||||
"public_key", sa.String(length=128), nullable=False, server_default=""
|
||||
),
|
||||
sa.Column(
|
||||
"client_version",
|
||||
sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column(
|
||||
"device_ticket_hash",
|
||||
sa.String(length=64),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
sa.Column("expires_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("authorized_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("ticket_issued_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("consumed_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
[f"{USERS}.id"],
|
||||
name="fk_device_challenges_user_id",
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"challenge_id", name="uq_device_challenges_challenge_id"
|
||||
),
|
||||
)
|
||||
op.create_index("ix_device_challenges_expires", CHALLENGES, ["expires_at"])
|
||||
op.create_index(
|
||||
"ix_device_challenges_user", CHALLENGES, ["user_id", "created_at"]
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
tables = _table_names(bind)
|
||||
|
||||
for table in (CHALLENGES, DEVICES, SMS):
|
||||
if table in tables:
|
||||
op.drop_table(table)
|
||||
|
||||
if USERS not in tables:
|
||||
return
|
||||
|
||||
dialect = bind.dialect.name
|
||||
indexes = _index_names(bind, USERS)
|
||||
fks = _fk_names(bind, USERS)
|
||||
|
||||
if dialect == "sqlite":
|
||||
with op.batch_alter_table(USERS) as batch:
|
||||
if "uq_users_phone_unique" in indexes:
|
||||
batch.drop_index("uq_users_phone_unique")
|
||||
if "fk_users_phone_bound_by" in fks:
|
||||
batch.drop_constraint("fk_users_phone_bound_by", type_="foreignkey")
|
||||
for column in (
|
||||
"phone_unique",
|
||||
"phone_bound_by",
|
||||
"phone_bound_at",
|
||||
"phone",
|
||||
):
|
||||
if column in _column_names(bind, USERS):
|
||||
batch.drop_column(column)
|
||||
return
|
||||
|
||||
if "uq_users_phone_unique" in indexes:
|
||||
op.drop_index("uq_users_phone_unique", table_name=USERS)
|
||||
if "fk_users_phone_bound_by" in fks:
|
||||
op.drop_constraint("fk_users_phone_bound_by", USERS, type_="foreignkey")
|
||||
columns = _column_names(bind, USERS)
|
||||
for column in ("phone_unique", "phone_bound_by", "phone_bound_at", "phone"):
|
||||
if column in columns:
|
||||
op.drop_column(USERS, column)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""修复 revision 20261021_0063 被旧实现占用导致的“空迁移”。
|
||||
|
||||
背景(2026-10-21):
|
||||
本地曾用同一个 revision id(``20261021_0063``)落地过一版已删除的设备认证实现,
|
||||
数据库里的 ``alembic_version`` 已经指向 0063,于是新写的 0063 被判为“已执行”,
|
||||
``users.phone_bound_at`` 等列没有创建,后端启动直接报
|
||||
``Unknown column 'users.phone_bound_at'``。
|
||||
|
||||
处理方式:
|
||||
1. 把旧实现留下的 ``users.phone``(varchar(20) NULL + 整列唯一)收敛到本次模型:
|
||||
去掉旧的整列唯一索引、NULL 回填成 ''、改成 varchar(32) NOT NULL DEFAULT '';
|
||||
唯一性交给 ``phone_unique``(它会把 '' 变成 NULL,空手机号可重复)。
|
||||
2. 幂等重放 0063 的全部建表/建列逻辑。所有步骤都带存在性判断,
|
||||
因此在“0063 正常执行过”的环境里再跑一次等于 no-op。
|
||||
|
||||
这样无论目标环境是:
|
||||
- 干净库(0062)→ 0063 正常执行,0064 no-op;
|
||||
- 被旧实现标记成 0063 的库 → 0064 补齐;
|
||||
最终结构都一致,不需要人工改 ``alembic_version``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261021_0064"
|
||||
down_revision: str | None = "20261021_0063"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _load_base_revision() -> ModuleType:
|
||||
path = Path(__file__).with_name("20261021_0063_user_phone_device_auth.py")
|
||||
spec = importlib.util.spec_from_file_location("live_hub_rev_0063", path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"无法加载迁移文件: {path}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _normalize_legacy_phone_column(bind) -> None:
|
||||
"""把旧实现的 users.phone 收敛成本次模型的定义(仅 MySQL 需要)。"""
|
||||
if bind.dialect.name != "mysql":
|
||||
return
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
if "users" not in inspector.get_table_names():
|
||||
return
|
||||
|
||||
columns = {column["name"]: column for column in inspector.get_columns("users")}
|
||||
phone = columns.get("phone")
|
||||
if phone is None:
|
||||
return
|
||||
|
||||
# 旧实现把 phone 整列设成唯一;回填 '' 之后多个空手机号会撞唯一索引,必须先摘掉。
|
||||
# 直接查 information_schema:get_indexes 与 get_unique_constraints 会重复报告同一个索引,
|
||||
# 连删两次会报 “Can't DROP ... check that column/key exists”。
|
||||
unique_indexes = (
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT DISTINCT INDEX_NAME
|
||||
FROM information_schema.statistics
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'users'
|
||||
AND column_name = 'phone'
|
||||
AND non_unique = 0
|
||||
"""
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for name in unique_indexes:
|
||||
op.drop_index(name, table_name="users")
|
||||
|
||||
bind.execute(sa.text("UPDATE users SET phone = '' WHERE phone IS NULL"))
|
||||
|
||||
current_type = phone.get("type")
|
||||
needs_alter = (
|
||||
phone.get("nullable", True)
|
||||
or getattr(current_type, "length", None) != 32
|
||||
or str(current_type).lower() not in {"varchar(32)"}
|
||||
)
|
||||
if needs_alter:
|
||||
op.alter_column(
|
||||
"users",
|
||||
"phone",
|
||||
existing_type=current_type,
|
||||
type_=sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
_normalize_legacy_phone_column(bind)
|
||||
# 幂等重放 0063:已存在的列/表/索引会被跳过。
|
||||
_load_base_revision().upgrade()
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
_load_base_revision().downgrade()
|
||||
Reference in New Issue
Block a user