第一阶段:模型 → 判定 → /auth/me → 列表。统计接口与前端管理页随后。
1) 模型与迁移(head 从 k1l2m3n4o5p6 推进到 l1m2n3o4p5q6)
· business_groups 组定义,parent_id 表达「大组 > 小组」
· business_group_phases 可见范围,独立成表以支持多选 —— 需求要求
「范围可配置、不要写死」,单列存不下多个 phase
· business_group_members 成员,一人可属多组(这是「同时看生产+维修」的实现)
只建表、不写种子数据,所以可以先部署代码再建组。
2) DataScope 判定模块(app/services/data_scope_service.py)
全仓库唯一的权限谓词来源,业务代码里不准再出现 lifecycle_phase 过滤。
两条红线照抄部门隔离的教训:
· None(不限) 与 frozenset()(空) 语义相反,绝不共用一个哨兵值
· 空集合必须显式 false() —— SQLAlchemy 对 in_(()) 生 成 IN (NULL),
一旦退化成不过滤就是全量泄漏
解析优先级:SUPER_ADMIN 硬放行(不可被分组覆盖)
> 显式分组(分组优先于角色)
> 未分组 SUPERVISOR 默认全厂
> 未分组普通用户
3) 过渡期开关 DATA_SCOPE_UNGROUPED(默认 ALL)
直接上严格模式会让所有未分组工人当场看不到自己的任务、现场停摆。
默认 ALL 先放行并打 WARNING 记录「谁还没分组」,配好组后再改 NONE。
4) /auth/me 返回 scope,phase 中文标签由服务端下发
—— 前端已有两份 phase 词表副本,不再加第三份。
5) 列表接口接入
· get_all_products:过滤加在 offset/limit 之前(其下有 6 段基于 product_ids
的批量预计算,过滤晚了等于算完再丢)
· get_all_tasks:谓词进【共享 filters】,保证 count 与 select 两条独立语句
同时生效,否则 total 与实际页不一致、移动端 hasMore 判断跟着错
· 扫码 get_product_by_serial 刻意不过滤,理由写死在 docstring 里
实测:空 scope 生成 false、受限 scope 生成 JOIN + IN 谓词;
/products 返回 2 条、/tasks 的 total 与 returned 一致。
57 lines
2.1 KiB
Python
57 lines
2.1 KiB
Python
"""通用 FastAPI 依赖"""
|
||
from __future__ import annotations
|
||
|
||
from fastapi import Depends, HTTPException, status
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.core.database import get_db
|
||
from app.core.roles import ADMIN_ROLES
|
||
from app.services.auth_service import get_current_user
|
||
from app.services.data_scope_service import DataScope, resolve_data_scope
|
||
|
||
|
||
def require_roles(*roles: str):
|
||
"""生成「限定角色」依赖,避免同一个内联判断被复制到每个端点。
|
||
|
||
用法::
|
||
|
||
@router.get("/x")
|
||
async def x(current_user: dict = Depends(require_admin)):
|
||
...
|
||
|
||
失败一律 403 且不透露允许的角色集合(避免给探测者提供线索)。
|
||
"""
|
||
allowed = frozenset(roles)
|
||
|
||
async def _guard(current_user: dict = Depends(get_current_user)) -> dict:
|
||
if (current_user or {}).get("role") not in allowed:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_403_FORBIDDEN,
|
||
detail="当前角色无权访问该接口",
|
||
)
|
||
return current_user
|
||
|
||
return _guard
|
||
|
||
|
||
# 审计日志等高权限接口复用同一实例
|
||
require_admin = require_roles(*ADMIN_ROLES)
|
||
|
||
|
||
async def get_data_scope(
|
||
db: AsyncSession = Depends(get_db),
|
||
current_user: dict = Depends(get_current_user),
|
||
) -> DataScope:
|
||
"""业务分组数据范围 —— 列表 / 统计类接口的统一入口。
|
||
|
||
⚠️ **硬依赖 get_current_user**:匿名请求直接 401,**不放行成空范围**。
|
||
两个理由:
|
||
1. 「匿名 = 空范围」会让大屏变成一个永远空白的页面,比 401 更难排查;
|
||
2. 匿名不过滤本身就是绕过口子 —— 谁能不登录看全厂数据,分组就形同虚设。
|
||
|
||
刻意**不加 TTL 缓存**:把人踢出组必须立即生效,任何缓存都会造成
|
||
「已经踢了还在看」的窗口。这里是单表 + 索引扫描,成本可忽略;
|
||
FastAPI 的依赖缓存在单请求内已经生效(同一请求多处 Depends 只解析一次)。
|
||
"""
|
||
return await resolve_data_scope(db, current_user)
|