chore: 初始化项目结构与登录鉴权模块

后端 FastAPI 六层结构(api/services/repositories/models/schemas/core),
统一响应信封、全局异常、日志脱敏;6 张表经 Alembic 迁移建库,SQL 留存
db/migration;登录鉴权含图形验证码(Redis GETDEL 防重放)、JWT、登录限流、
登出黑名单(TTL=令牌剩余有效期)、登录日志。

前端 Vue3 + TS + Element Plus 骨架,含登录页、路由守卫、请求封装与 Vite 代理。

工程配置:uv 锁定 Python 3.12、ruff 检查与格式化、editorconfig、gitattributes。

测试 184 项(单元 155 / 集成 29)全绿,浏览器端到端 8 项通过。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
liuwenxinandClaude Code committed 2026-10-09 18:46:36 +08:00
commit 273ebf4657
101 files changed
+8725

No files matched your search

+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+74
View File
@@ -0,0 +1,74 @@
"""Alembic 迁移环境。
**连接串取自 backend/.env**,不写在 alembic.ini —— 避免密码进版本库,
也避免运行期配置与迁移配置两处漂移。运行期与迁移共用同一份同步连接串
(驱动 pymysql),不存在同步/异步两套配置。
"""
import sys
from logging.config import fileConfig
from pathlib import Path
from alembic import context
from sqlalchemy import engine_from_config, pool
# 使 `app` 包在 alembic 执行时可导入(alembic 从 backend/ 目录运行)
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core.config import get_settings
from app.models import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# autogenerate 的比对基准
target_metadata = Base.metadata
# 运行期把 .env 里的连接串注入配置,覆盖 alembic.ini 中的占位值
config.set_main_option(
"sqlalchemy.url",
get_settings().database_url.render_as_string(hide_password=False),
)
def run_migrations_offline() -> None:
"""离线模式:不连库,只输出 SQL。
用于导出 `db/migration/V{n}__*.sql` 留存脚本。
"""
context.configure(
url=config.get_main_option("sqlalchemy.url"),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
# 类型变更也要被识别,否则改列类型不会生成迁移
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""在线模式:连库执行迁移。"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
# 迁移是一次性任务,用完即弃,不需要连接池
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,353 @@
"""初始化 RBAC 与登录日志表
Revision ID: 6165691326d4
Revises:
Create Date: 2026-10-09 10:58:04.316902
"""
from collections.abc import Sequence
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision: str = "6165691326d4"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"permissions",
sa.Column(
"id", mysql.BIGINT(unsigned=True), autoincrement=True, nullable=False, comment="主键ID"
),
sa.Column(
"perm_code",
sa.String(length=128),
nullable=False,
comment="权限编码,如 system:user:create",
),
sa.Column("perm_name", sa.String(length=64), nullable=False, comment="权限名称"),
sa.Column(
"perm_type",
mysql.TINYINT(),
server_default="1",
nullable=False,
comment="类型:1菜单 2按钮 3接口",
),
sa.Column(
"parent_id",
mysql.BIGINT(unsigned=True),
nullable=True,
comment="父权限ID(permissions.id),顶级为空",
),
sa.Column(
"sort_order", sa.Integer(), server_default="0", nullable=False, comment="显示排序"
),
sa.Column(
"status",
mysql.TINYINT(),
server_default="1",
nullable=False,
comment="状态:1启用 0禁用",
),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
comment="创建时间",
),
sa.Column(
"update_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
nullable=False,
comment="更新时间",
),
sa.ForeignKeyConstraint(
["parent_id"],
["permissions.id"],
name=op.f("fk_permissions_parent_id"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_permissions")),
sa.UniqueConstraint("perm_code", name=op.f("uk_permissions_perm_code")),
comment="权限表",
mysql_charset="utf8mb4",
mysql_collate="utf8mb4_general_ci",
mysql_engine="InnoDB",
)
op.create_table(
"roles",
sa.Column(
"id", mysql.BIGINT(unsigned=True), autoincrement=True, nullable=False, comment="主键ID"
),
sa.Column(
"role_code",
sa.String(length=32),
nullable=False,
comment="角色编码:admin系统管理员 user普通用户",
),
sa.Column("role_name", sa.String(length=64), nullable=False, comment="角色名称"),
sa.Column("description", sa.String(length=255), nullable=True, comment="角色说明"),
sa.Column(
"sort_order", sa.Integer(), server_default="0", nullable=False, comment="显示排序"
),
sa.Column(
"status",
mysql.TINYINT(),
server_default="1",
nullable=False,
comment="状态:1启用 0禁用",
),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
comment="创建时间",
),
sa.Column(
"update_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
nullable=False,
comment="更新时间",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_roles")),
sa.UniqueConstraint("role_code", name=op.f("uk_roles_role_code")),
comment="角色表",
mysql_charset="utf8mb4",
mysql_collate="utf8mb4_general_ci",
mysql_engine="InnoDB",
)
op.create_table(
"users",
sa.Column(
"id", mysql.BIGINT(unsigned=True), autoincrement=True, nullable=False, comment="主键ID"
),
sa.Column("username", sa.String(length=64), nullable=False, comment="登录用户名"),
sa.Column(
"password",
sa.String(length=100),
nullable=False,
comment="密码哈希(BCrypt,固定60字符)",
),
sa.Column("real_name", sa.String(length=64), nullable=True, comment="真实姓名"),
sa.Column("phone", sa.String(length=20), nullable=True, comment="手机号"),
sa.Column("email", sa.String(length=128), nullable=True, comment="邮箱"),
sa.Column(
"status",
mysql.TINYINT(),
server_default="1",
nullable=False,
comment="状态:1启用 0禁用",
),
sa.Column(
"token_version",
sa.Integer(),
server_default="1",
nullable=False,
comment="令牌版本号:改密/禁用/强制下线时+1,使已签发Token立即失效",
),
sa.Column("last_login_time", sa.DateTime(), nullable=True, comment="最后登录时间"),
sa.Column("remark", sa.String(length=255), nullable=True, comment="备注"),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
comment="创建时间",
),
sa.Column(
"update_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
nullable=False,
comment="更新时间",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
sa.UniqueConstraint("username", name=op.f("uk_users_username")),
comment="系统用户表",
mysql_charset="utf8mb4",
mysql_collate="utf8mb4_general_ci",
mysql_engine="InnoDB",
)
op.create_index(op.f("idx_users_phone"), "users", ["phone"], unique=False)
op.create_table(
"login_logs",
sa.Column(
"id", mysql.BIGINT(unsigned=True), autoincrement=True, nullable=False, comment="主键ID"
),
sa.Column(
"user_id",
mysql.BIGINT(unsigned=True),
nullable=True,
comment="用户ID(账号不存在时为空)",
),
sa.Column(
"username", sa.String(length=64), nullable=False, comment="登录用户名(原样记录)"
),
sa.Column("ip", sa.String(length=45), nullable=True, comment="客户端IP(45位兼容IPv6)"),
sa.Column(
"user_agent",
sa.String(length=255),
nullable=True,
comment="客户端User-Agent(截断存储)",
),
sa.Column(
"success",
mysql.TINYINT(),
server_default="0",
nullable=False,
comment="是否成功:1成功 0失败",
),
sa.Column(
"fail_reason",
sa.String(length=64),
nullable=True,
comment="失败原因:验证码错误/用户名或密码错误/账号锁定/账号禁用",
),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
comment="创建时间",
),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name=op.f("fk_login_logs_user_id"), ondelete="SET NULL"
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_login_logs")),
comment="登录日志表",
mysql_charset="utf8mb4",
mysql_collate="utf8mb4_general_ci",
mysql_engine="InnoDB",
)
op.create_index("idx_login_logs_create_time", "login_logs", ["create_time"], unique=False)
op.create_index("idx_login_logs_username", "login_logs", ["username"], unique=False)
op.create_table(
"role_permissions",
sa.Column(
"id", mysql.BIGINT(unsigned=True), autoincrement=True, nullable=False, comment="主键ID"
),
sa.Column(
"role_id", mysql.BIGINT(unsigned=True), nullable=False, comment="角色ID(roles.id)"
),
sa.Column(
"permission_id",
mysql.BIGINT(unsigned=True),
nullable=False,
comment="权限ID(permissions.id)",
),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
comment="创建时间",
),
sa.ForeignKeyConstraint(
["permission_id"],
["permissions.id"],
name=op.f("fk_role_permissions_permission_id"),
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["role_id"], ["roles.id"], name=op.f("fk_role_permissions_role_id"), ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_role_permissions")),
sa.UniqueConstraint(
"role_id", "permission_id", name="uk_role_permissions_role_id_permission_id"
),
comment="角色权限关联表",
mysql_charset="utf8mb4",
mysql_collate="utf8mb4_general_ci",
mysql_engine="InnoDB",
)
op.create_index(
"idx_role_permissions_permission_id", "role_permissions", ["permission_id"], unique=False
)
op.create_table(
"user_roles",
sa.Column(
"id", mysql.BIGINT(unsigned=True), autoincrement=True, nullable=False, comment="主键ID"
),
sa.Column(
"user_id", mysql.BIGINT(unsigned=True), nullable=False, comment="用户ID(users.id)"
),
sa.Column(
"role_id", mysql.BIGINT(unsigned=True), nullable=False, comment="角色ID(roles.id)"
),
sa.Column(
"create_time",
sa.DateTime(),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
comment="创建时间",
),
sa.ForeignKeyConstraint(
["role_id"], ["roles.id"], name=op.f("fk_user_roles_role_id"), ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name=op.f("fk_user_roles_user_id"), ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_user_roles")),
sa.UniqueConstraint("user_id", "role_id", name="uk_user_roles_user_id_role_id"),
comment="用户角色关联表",
mysql_charset="utf8mb4",
mysql_collate="utf8mb4_general_ci",
mysql_engine="InnoDB",
)
op.create_index("idx_user_roles_role_id", "user_roles", ["role_id"], unique=False)
# ### end Alembic commands ###
# 角色为字典数据,随结构初始化 —— 放在迁移而非 init-dev.sql,
# 保证生产环境同样具备这两个基础角色(规范要求的两个角色,见功能需规 2.5.1)
op.bulk_insert(
sa.table(
"roles",
sa.column("role_code", sa.String),
sa.column("role_name", sa.String),
sa.column("description", sa.String),
sa.column("sort_order", sa.Integer),
),
[
{
"role_code": "admin",
"role_name": "系统管理员",
"description": "全部权限,含计提参数与系数表配置",
"sort_order": 1,
},
{
"role_code": "user",
"role_name": "普通用户",
"description": "业务操作",
"sort_order": 2,
},
],
)
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index("idx_user_roles_role_id", table_name="user_roles")
op.drop_table("user_roles")
op.drop_index("idx_role_permissions_permission_id", table_name="role_permissions")
op.drop_table("role_permissions")
op.drop_index("idx_login_logs_username", table_name="login_logs")
op.drop_index("idx_login_logs_create_time", table_name="login_logs")
op.drop_table("login_logs")
op.drop_index(op.f("idx_users_phone"), table_name="users")
op.drop_table("users")
op.drop_table("roles")
op.drop_table("permissions")
# ### end Alembic commands ###