refactor: 完成项目大规模重构与功能优化

这是一次综合性的项目迭代,包含以下核心变更:
1.  **目录与模块重构**
    - 调整工作流节点类型模块目录结构,迁移节点类型相关代码
    - 重命名platform模块为system模块,更新插件配置信息
    - 重构代码生成模块导入路径
2.  **数据库与CRUD优化**
    - 统一所有CRUD类构造函数,新增数据库会话参数
    - 修复权限过滤器数据库会话使用问题
    - 更新模板生成器的CRUD代码模板
3.  **认证与安全改进**
    - 重构JWT密钥配置,移除默认密钥强制要求环境变量
    - 重命名密码工具类,统一密码加密校验逻辑
    - 优化OAuth认证流程,修复匿名认证使用问题
4.  **前端与静态资源**
    - 重构前端挂载逻辑,增加目录存在性校验
    - 使用标准StaticFiles替换自定义前端挂载实现
5.  **工具类与依赖更新**
    - 修复导入工具的表名重复检测逻辑
    - 优化限流回调代码,移除冗余依赖
    - 更新用户、租户等模块的响应模型字段
6.  **数据与配置修正**
    - 修复系统版本数据字段命名不统一问题
    - 简化枚举类校验逻辑,移除冗余注释
    - 修复测试用例中的密码工具类导入错误
This commit is contained in:
zhangtao
2026-07-11 13:03:28 +08:00
parent 5ff72b086f
commit 6a5f8cf0dd
95 changed files with 1531 additions and 1118 deletions
@@ -1,13 +1,14 @@
from typing import Annotated
from fastapi import APIRouter, Body, Path, Query, Security, status
from fastapi import APIRouter, Body, Depends, Path, Query, Security, status
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi_cache import FastAPICache
from fastapi_cache.decorator import cache
from sqlalchemy.ext.asyncio import AsyncSession
from app.common.response import ResponseSchema, StreamResponse, SuccessResponse
from app.core.base_schema import AuthSchema, BatchSetAvailable, PageResultSchema, PaginationQueryParam
from app.core.dependencies import AuthPermission
from app.core.dependencies import AuthPermission, db_getter
from app.core.router_class import OperationLogRoute
from app.utils.common_util import bytes2file_response
@@ -23,13 +24,14 @@ _ROLE_NS = "role"
@cache(expire=300, namespace=_ROLE_NS)
async def get_role_list_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:query"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
page: Annotated[PaginationQueryParam, Query(description="分页参数")],
search: Annotated[RoleQueryParam, Query(description="角色查询参数")],
) -> JSONResponse:
order_by = [{"order": "asc"}]
if page.order_by:
order_by = page.order_by
result_dict = await RoleService(auth).page(
result_dict = await RoleService(auth, db).page(
page_no=page.page_no,
page_size=page.page_size,
search=search,
@@ -41,18 +43,20 @@ async def get_role_list_controller(
@RoleRouter.get("/detail/{id}", summary="查询角色详情", response_model=ResponseSchema[RoleOutSchema])
async def get_role_detail_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:detail"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
id: Annotated[int, Path(description="角色ID", ge=1)],
) -> JSONResponse:
result_dict = await RoleService(auth).detail(id=id)
result_dict = await RoleService(auth, db).detail(id=id)
return SuccessResponse(data=result_dict, msg="获取角色详情成功")
@RoleRouter.post("/create", status_code=status.HTTP_201_CREATED, summary="创建角色", response_model=ResponseSchema[RoleOutSchema])
async def create_role_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:create"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
data: Annotated[RoleCreateSchema, Body(description="角色创建参数")],
) -> JSONResponse:
result_dict = await RoleService(auth).create(data=data)
result_dict = await RoleService(auth, db).create(data=data)
await FastAPICache.clear(namespace=_ROLE_NS)
return SuccessResponse(data=result_dict, msg="创建角色成功")
@@ -60,10 +64,11 @@ async def create_role_controller(
@RoleRouter.put("/update/{id}", summary="修改角色", response_model=ResponseSchema[RoleOutSchema])
async def update_role_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:update"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
id: Annotated[int, Path(description="角色ID", ge=1)],
data: Annotated[RoleUpdateSchema, Body(description="角色修改参数")],
) -> JSONResponse:
result_dict = await RoleService(auth).update(id=id, data=data)
result_dict = await RoleService(auth, db).update(id=id, data=data)
await FastAPICache.clear(namespace=_ROLE_NS)
return SuccessResponse(data=result_dict, msg="修改角色成功")
@@ -71,9 +76,10 @@ async def update_role_controller(
@RoleRouter.delete("/delete", summary="删除角色", response_model=ResponseSchema[None])
async def delete_role_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:delete"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
ids: Annotated[list[int], Body(description="ID列表")],
) -> JSONResponse:
await RoleService(auth).delete(ids=ids)
await RoleService(auth, db).delete(ids=ids)
await FastAPICache.clear(namespace=_ROLE_NS)
return SuccessResponse(msg="删除角色成功")
@@ -81,9 +87,10 @@ async def delete_role_controller(
@RoleRouter.patch("/status/batch", summary="批量修改角色状态", response_model=ResponseSchema[None])
async def batch_set_available_role_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:patch"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
data: Annotated[BatchSetAvailable, Body(description="状态设置")],
) -> JSONResponse:
await RoleService(auth).set_available(data=data)
await RoleService(auth, db).set_available(data=data)
await FastAPICache.clear(namespace=_ROLE_NS)
return SuccessResponse(msg="批量修改角色状态成功")
@@ -91,9 +98,10 @@ async def batch_set_available_role_controller(
@RoleRouter.put("/permission", summary="角色授权", response_model=ResponseSchema[None])
async def set_role_permission_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:permission"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
data: Annotated[RolePermissionSettingSchema, Body(description="角色授权参数")],
) -> JSONResponse:
await RoleService(auth).set_permission(data=data)
await RoleService(auth, db).set_permission(data=data)
await FastAPICache.clear(namespace=_ROLE_NS)
return SuccessResponse(msg="授权角色成功")
@@ -101,17 +109,19 @@ async def set_role_permission_controller(
@RoleRouter.get("/options", summary="获取角色下拉选项", response_model=ResponseSchema[list[dict[str, int | str]]])
async def get_role_options_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:query"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
) -> JSONResponse:
options = await RoleService(auth).get_options()
options = await RoleService(auth, db).get_options()
return SuccessResponse(data=options, msg="获取角色选项成功")
@RoleRouter.get("/export", summary="导出角色")
async def export_role_list_controller(
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:role:export"]))],
db: Annotated[AsyncSession, Depends(db_getter)],
search: Annotated[RoleQueryParam, Query(description="角色查询参数")],
) -> StreamingResponse:
role_query_result = await RoleService(auth).get_list(search=search)
role_query_result = await RoleService(auth, db).get_list(search=search)
role_export_result = RoleService.export_list(role_list=[item.model_dump() for item in role_query_result])
return StreamResponse(
@@ -1,5 +1,7 @@
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.module_platform.menu.crud import MenuCRUD
from app.api.v1.module_system.dept.crud import DeptCRUD
from app.core.base_crud import CRUDBase
@@ -13,8 +15,8 @@ from .schema import RoleCreateSchema, RoleUpdateSchema
class RoleCRUD(CRUDBase[RoleModel, RoleCreateSchema, RoleUpdateSchema]):
"""角色模块数据层"""
def __init__(self, auth: AuthSchema) -> None:
super().__init__(model=RoleModel, auth=auth)
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
super().__init__(model=RoleModel, auth=auth, db=db)
async def set_role_menus_crud(self, role_ids: list[int], menu_ids: list[int]) -> None:
"""设置角色的菜单权限
@@ -29,12 +31,12 @@ class RoleCRUD(CRUDBase[RoleModel, RoleCreateSchema, RoleUpdateSchema]):
from app.api.v1.module_platform.package.service import PackageService
roles = await self.get_list(search={"id": ("in", role_ids)})
menus = [] if not menu_ids else await MenuCRUD(self.auth).get_list(search={"id": ("in", menu_ids)})
menus = [] if not menu_ids else await MenuCRUD(self.auth, self.db).get_list(search={"id": ("in", menu_ids)})
# 非超管需校验菜单在租户套餐范围内
user = self.auth.user
if user and not user.is_superuser and user.tenant_id:
allowed_set = set[int](await PackageService(self.auth).get_tenant_available_menu_ids(user.tenant_id))
allowed_set = set[int](await PackageService(self.auth, self.db).get_tenant_available_menu_ids(user.tenant_id))
for menu in menus:
if int(menu.id) not in allowed_set:
raise CustomException(msg=f"菜单[{menu.name}]不在当前租户的功能组内,无法分配")
@@ -42,7 +44,7 @@ class RoleCRUD(CRUDBase[RoleModel, RoleCreateSchema, RoleUpdateSchema]):
for obj in roles:
obj.menus.clear()
obj.menus.extend(menus)
await self.auth.db.flush()
await self.db.flush()
async def set_role_depts_crud(self, role_ids: list[int], dept_ids: list[int]) -> None:
"""设置角色的部门权限
@@ -55,13 +57,13 @@ class RoleCRUD(CRUDBase[RoleModel, RoleCreateSchema, RoleUpdateSchema]):
- None
"""
roles = await self.get_list(search={"id": ("in", role_ids)})
depts = [] if not dept_ids else await DeptCRUD(self.auth).get_list(search={"id": ("in", dept_ids)})
depts = [] if not dept_ids else await DeptCRUD(self.auth, self.db).get_list(search={"id": ("in", dept_ids)})
for obj in roles:
relationship = obj.depts
relationship.clear()
relationship.extend(depts)
await self.auth.db.flush()
await self.db.flush()
async def get_options(self) -> list[dict[str, Any]]:
"""获取角色下拉选项,返回 [{value, label}]"""
@@ -1,5 +1,7 @@
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.base_schema import AuthSchema, BatchSetAvailable, PageResultSchema
from app.core.exceptions import CustomException
from app.utils.excel_util import ExcelUtil
@@ -20,8 +22,9 @@ class RoleService:
提供角色 CRUD、权限配置、数据权限范围设置、批量启/禁用、Excel 导出等业务能力。
"""
def __init__(self, auth: AuthSchema) -> None:
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def detail(self, id: int) -> RoleOutSchema:
"""获取角色详情
@@ -32,12 +35,12 @@ class RoleService:
返回:
- RoleOutSchema: 角色详情响应模型
"""
obj = await RoleCRUD(self.auth).get_or_404(id=id)
obj = await RoleCRUD(self.auth, self.db).get_or_404(id=id)
return RoleOutSchema.model_validate(obj)
async def get_options(self) -> list[dict[str, Any]]:
"""获取角色下拉选项,委托给 RoleCRUD"""
return await RoleCRUD(self.auth).get_options()
return await RoleCRUD(self.auth, self.db).get_options()
async def get_list(
self,
@@ -53,7 +56,7 @@ class RoleService:
返回:
- list[RoleOutSchema]: 角色响应模型列表
"""
role_list = await RoleCRUD(self.auth).get_list(search=vars(search) if search else None, order_by=order_by)
role_list = await RoleCRUD(self.auth, self.db).get_list(search=vars(search) if search else None, order_by=order_by)
return [RoleOutSchema.model_validate(role) for role in role_list]
async def page(
@@ -75,7 +78,7 @@ class RoleService:
- dict: 分页结果(结构由 ``CRUD.page`` 返回约定)
"""
offset = (page_no - 1) * page_size
return await RoleCRUD(self.auth).page(
return await RoleCRUD(self.auth, self.db).page(
offset=offset,
limit=page_size,
order_by=order_by or [{"id": "asc"}],
@@ -95,17 +98,17 @@ class RoleService:
返回:
- RoleOutSchema: 新创建的角色响应模型
"""
role = await RoleCRUD(self.auth).get(name=data.name)
role = await RoleCRUD(self.auth, self.db).get(name=data.name)
if role:
raise CustomException(msg="创建失败,该数据已存在")
obj = await RoleCRUD(self.auth).get(code=data.code)
obj = await RoleCRUD(self.auth, self.db).get(code=data.code)
if obj:
raise CustomException(msg="创建失败,编码已存在")
# 检查租户配额
await TenantService(self.auth).check_quota(self.auth.user.tenant_id, "role")
await TenantService(self.auth, self.db).check_quota(self.auth.user.tenant_id, "role")
new_role = await RoleCRUD(self.auth).create(data=data)
new_role = await RoleCRUD(self.auth, self.db).create(data=data)
return RoleOutSchema.model_validate(new_role)
async def update(self, id: int, data: RoleUpdateSchema) -> RoleOutSchema:
@@ -118,14 +121,14 @@ class RoleService:
返回:
- RoleOutSchema: 更新后的角色响应模型
"""
_ = await RoleCRUD(self.auth).get_or_404(id=id, msg="更新失败,该数据不存在")
exist_role = await RoleCRUD(self.auth).get(name=data.name)
_ = await RoleCRUD(self.auth, self.db).get_or_404(id=id, msg="更新失败,该数据不存在")
exist_role = await RoleCRUD(self.auth, self.db).get(name=data.name)
if exist_role and exist_role.id != id:
raise CustomException(msg="更新失败,名称已存在")
exist_code = await RoleCRUD(self.auth).get(code=data.code)
exist_code = await RoleCRUD(self.auth, self.db).get(code=data.code)
if exist_code and exist_code.id != id:
raise CustomException(msg="更新失败,角色编码已存在")
updated_role = await RoleCRUD(self.auth).update(id=id, data=data)
updated_role = await RoleCRUD(self.auth, self.db).update(id=id, data=data)
return RoleOutSchema.model_validate(updated_role)
async def delete(self, ids: list[int]) -> None:
@@ -141,11 +144,11 @@ class RoleService:
raise CustomException(msg="删除失败,删除对象不能为空")
# 批量校验角色存在性
roles = await RoleCRUD(self.auth).get_list(search={"id": ("in", ids)})
roles = await RoleCRUD(self.auth, self.db).get_list(search={"id": ("in", ids)})
if len(roles) != len(ids):
raise CustomException(msg="删除失败,部分ID不存在")
await RoleCRUD(self.auth).delete(ids=ids)
await RoleCRUD(self.auth, self.db).delete(ids=ids)
async def set_permission(self, data: RolePermissionSettingSchema) -> None:
"""设置角色权限
@@ -157,16 +160,16 @@ class RoleService:
- None
"""
# 设置角色菜单权限
await RoleCRUD(self.auth).set_role_menus_crud(role_ids=data.role_ids, menu_ids=data.menu_ids)
await RoleCRUD(self.auth, self.db).set_role_menus_crud(role_ids=data.role_ids, menu_ids=data.menu_ids)
# 设置数据权限范围
await RoleCRUD(self.auth).set(ids=data.role_ids, data_scope=data.data_scope)
await RoleCRUD(self.auth, self.db).set(ids=data.role_ids, data_scope=data.data_scope)
# 设置自定义数据权限部门
if data.data_scope == 5 and data.dept_ids:
await RoleCRUD(self.auth).set_role_depts_crud(role_ids=data.role_ids, dept_ids=data.dept_ids)
await RoleCRUD(self.auth, self.db).set_role_depts_crud(role_ids=data.role_ids, dept_ids=data.dept_ids)
else:
await RoleCRUD(self.auth).set_role_depts_crud(role_ids=data.role_ids, dept_ids=[])
await RoleCRUD(self.auth, self.db).set_role_depts_crud(role_ids=data.role_ids, dept_ids=[])
async def set_available(self, data: BatchSetAvailable) -> None:
"""设置角色可用状态
@@ -177,12 +180,12 @@ class RoleService:
返回:
- None
"""
roles = await RoleCRUD(self.auth).get_list(search={"id": ("in", data.ids)})
roles = await RoleCRUD(self.auth, self.db).get_list(search={"id": ("in", data.ids)})
role_map = {r.id: r for r in roles}
for rid in data.ids:
if rid not in role_map:
raise CustomException(msg="该数据不存在")
await RoleCRUD(self.auth).set(ids=data.ids, status=data.status)
await RoleCRUD(self.auth, self.db).set(ids=data.ids, status=data.status)
@staticmethod
def export_list(role_list: list[dict[str, Any]]) -> bytes: