Compare commits
5 Commits
42c883fe7d
...
42a67bfa3a
| Author | SHA1 | Date | |
|---|---|---|---|
| 42a67bfa3a | |||
| 14f707461d | |||
| 7635802a42 | |||
| 04eb87b091 | |||
| 4454047ce3 |
63
AGENTS.md
Normal file
63
AGENTS.md
Normal file
@ -0,0 +1,63 @@
|
||||
# AGENTS.md
|
||||
|
||||
本仓库(Track 生产流转系统)的工作笔记。仅在验证过之后才写入,避免传谣。
|
||||
|
||||
## 架构速览
|
||||
|
||||
- `backend/` FastAPI + SQLAlchemy 2.x(async) + Alembic,PostgreSQL。
|
||||
- `frontend/` React 19 + Vite + antd + Tailwind。路由见 `src/App.tsx`,
|
||||
管理端菜单见 `src/components/layout/AdminLayout.tsx`(`MENU` 数组)。
|
||||
- 登录不走 Track 自己的用户表,而是**只读** MOM(KCGL) 的 `sys_user`:
|
||||
`sys_user.username` 存 `"真实姓名/登录账号"`,`login()` 用
|
||||
`WHERE username LIKE '%/<账号>'` 匹配,`display_name` 由 `/` 拆解得到。
|
||||
MOM 连接配置在 `app/core/mom_database.py`(同步 psycopg2 引擎)。
|
||||
|
||||
## 本地起环境(关键,踩过的坑都在这)
|
||||
|
||||
1. **本机没有 Postgres 时需要先装**(容器内 `sudo` 可用):
|
||||
`sudo -n apt-get install -y --fix-missing postgresql postgresql-contrib`
|
||||
然后 `sudo -n pg_ctlcluster 17 main start`。
|
||||
本仓库不使用 pgvector,无需额外扩展。
|
||||
2. **数据库端口与生产默认值不同**,必须用环境变量覆盖:
|
||||
- `DATABASE_URL=postgresql+asyncpg://track:track_prod_2026@127.0.0.1:5432/track_production`
|
||||
- `MOM_DB_HOST=127.0.0.1`、`MOM_DB_PORT=5432`
|
||||
- `SECRET_KEY=<≥32 字符>`:`DEBUG=false` 时配置项会**拒绝**默认 SECRET_KEY
|
||||
(见 `app/core/config.py` 的校验),不设会直接 import 失败。
|
||||
3. 迁移:`cd backend && python3 -m alembic upgrade head`(没有全局 `alembic` 命令,
|
||||
要用 `python3 -m alembic`)。校验纯 SQL 用 `alembic upgrade head --sql`。
|
||||
4. 前端 proxy 指向 Docker 服务名 `backend:8000`。本机跑要么把
|
||||
`127.0.0.1 backend` 写进 `/etc/hosts`,要么直接给
|
||||
`VITE_API_BASE_URL=http://localhost:<port>/api/v1` 绕过 proxy。
|
||||
注意 dev server 由 `basicSsl` 起 HTTPS,跨域需要后端
|
||||
`CORS_ORIGINS` 加上 `https://localhost:1420`。
|
||||
|
||||
## 测试的坑(重要)
|
||||
|
||||
- **不要用 `starlette.testclient.TestClient` 测异步 SQLAlchemy 应用。**
|
||||
它每个请求新建事件循环,而引擎是模块级单例、池里挂着 asyncpg 连接,
|
||||
跨循环复用会报 `got Future attached to a different loop`,表现为随机 500。
|
||||
正确做法:`httpx.AsyncClient(transport=httpx.ASGITransport(app=app))`
|
||||
并在单个 `asyncio.run()` 里跑完全部请求。生产 uvicorn 单循环无此问题。
|
||||
- 仓库目前**没有** pytest 基建,也没有前端测试脚本。
|
||||
|
||||
## 已知的待修问题(截至 1.0应用 分支)
|
||||
|
||||
- **读接口大面积未鉴权**(已实测,非推测):无 token 直接 200 的包括
|
||||
`/api/v1/users/`、全部 `/api/v1/dashboard/*`(含
|
||||
`people-history/export` —— 匿名即可批量导出个人工时台账)、
|
||||
`/api/v1/analytics/*`、`/api/v1/screen/*`、`/api/v1/orders/`。
|
||||
写操作和 `/api/v1/tasks`、`/api/v1/products` 是有鉴权的。
|
||||
新增接口请统一用 `app/core/deps.py` 的 `require_admin` / `require_roles`。
|
||||
- 「管理员角色」这份规则此前散在 4 处(后端 `task_service`、`products.py` 内联、
|
||||
前端 `constants/task.ts`、`AdminProductsPage` 内联),已因此出过事故。
|
||||
**后端唯一事实来源是 `app/core/roles.py`,前端用 `constants/task.ts::isAdminRole`。**
|
||||
新增判断不要手写 `===` 比较。
|
||||
- `task_logs.task_id` 是 NOT NULL 外键,只能挂任务,不是通用审计。通用审计是
|
||||
`audit_logs`(本轮新增,由 `app/core/audit_middleware.py` 自动采集)。
|
||||
|
||||
## 约定
|
||||
|
||||
- 时间统一北京时间(`app/core/time_utils.py`),库里存 timestamptz。
|
||||
- 中文枚举标签尽量由服务端下发(如审计接口的 `module_label`/`action_label`),
|
||||
避免前端再抄一份映射开始漂移。
|
||||
- 本仓库的提交信息用中文,说明「为什么」而非「改了什么」。
|
||||
@ -3,3 +3,11 @@ SECRET_KEY=change-me-to-a-random-secret-key-in-production
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
DEBUG=true
|
||||
CORS_ORIGINS='["http://localhost:1420", "tauri://localhost"]'
|
||||
|
||||
# 日志:LOG_JSON=true 输出单行 JSON(便于采集),本地调试可设 false 换可读格式
|
||||
LOG_LEVEL=INFO
|
||||
LOG_JSON=true
|
||||
|
||||
# 错误追踪(可选):填了 DSN 且已安装 sentry-sdk 才会启用,否则自动跳过
|
||||
# SENTRY_DSN=
|
||||
# SENTRY_TRACES_SAMPLE_RATE=0.1
|
||||
|
||||
81
backend/alembic/versions/j1k2l3m4n5o6_add_audit_logs.py
Normal file
81
backend/alembic/versions/j1k2l3m4n5o6_add_audit_logs.py
Normal file
@ -0,0 +1,81 @@
|
||||
"""add_audit_logs
|
||||
|
||||
Revision ID: j1k2l3m4n5o6
|
||||
Revises: i1j2k3l4m5n6
|
||||
Create Date: 2026-09-21
|
||||
|
||||
操作审计日志表(audit_logs)
|
||||
--------------------------
|
||||
新增一张独立的审计表,用于记录 task_logs 覆盖不到的操作:
|
||||
登录、导出、产品增删改、收口、权限/配置变更等与单个任务无关的动作。
|
||||
|
||||
为什么另起一张表而不复用 task_logs:
|
||||
task_logs.task_id 是 NOT NULL 外键,只能挂在任务上,无法表达「张三导出了
|
||||
产品清单」这类动作;且缺少来源 IP / UA / 结果状态等审计必需字段。
|
||||
|
||||
存量数据无需回填(本表从上线时刻开始记录)。
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "j1k2l3m4n5o6"
|
||||
down_revision: Union[str, None] = "i1j2k3l4m5n6"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"audit_logs",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True, nullable=False),
|
||||
# 操作人
|
||||
sa.Column("user_id", sa.String(64), nullable=True, comment="操作人账号(逻辑外键→MOM)"),
|
||||
sa.Column("display_name", sa.String(100), nullable=True, comment="操作人显示名"),
|
||||
sa.Column("role", sa.String(50), nullable=True, comment="操作时角色快照"),
|
||||
# 业务语义
|
||||
sa.Column("action", sa.String(50), nullable=False, comment="动作"),
|
||||
sa.Column("module", sa.String(50), nullable=False, comment="业务模块"),
|
||||
sa.Column("target_type", sa.String(50), nullable=True),
|
||||
sa.Column("target_id", sa.String(100), nullable=True),
|
||||
sa.Column("target_name", sa.String(200), nullable=True),
|
||||
sa.Column("details", postgresql.JSONB(), nullable=True, comment="变更详情"),
|
||||
# 请求上下文
|
||||
sa.Column("ip_address", sa.String(50), nullable=True),
|
||||
sa.Column("user_agent", sa.String(500), nullable=True),
|
||||
sa.Column("method", sa.String(10), nullable=True),
|
||||
sa.Column("url", sa.String(500), nullable=True),
|
||||
sa.Column("status_code", sa.Integer(), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
# 与结构化日志对账
|
||||
sa.Column("request_id", sa.String(64), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.func.now(),
|
||||
),
|
||||
)
|
||||
|
||||
# 索引:按审计页最常用的检索维度建
|
||||
op.create_index("ix_audit_logs_created_at", "audit_logs", ["created_at"])
|
||||
op.create_index("ix_audit_logs_user_id", "audit_logs", ["user_id"])
|
||||
op.create_index("ix_audit_logs_module", "audit_logs", ["module"])
|
||||
op.create_index("ix_audit_logs_action", "audit_logs", ["action"])
|
||||
op.create_index("ix_audit_logs_target_id", "audit_logs", ["target_id"])
|
||||
op.create_index("ix_audit_logs_request_id", "audit_logs", ["request_id"])
|
||||
# 组合索引:审计页默认「按时间倒序 + 按模块/动作过滤」
|
||||
op.create_index("ix_audit_logs_module_created", "audit_logs", ["module", "created_at"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_audit_logs_module_created", table_name="audit_logs")
|
||||
op.drop_index("ix_audit_logs_request_id", table_name="audit_logs")
|
||||
op.drop_index("ix_audit_logs_target_id", table_name="audit_logs")
|
||||
op.drop_index("ix_audit_logs_action", table_name="audit_logs")
|
||||
op.drop_index("ix_audit_logs_module", table_name="audit_logs")
|
||||
op.drop_index("ix_audit_logs_user_id", table_name="audit_logs")
|
||||
op.drop_index("ix_audit_logs_created_at", table_name="audit_logs")
|
||||
op.drop_table("audit_logs")
|
||||
99
backend/app/api/v1/endpoints/audit.py
Normal file
99
backend/app/api/v1/endpoints/audit.py
Normal file
@ -0,0 +1,99 @@
|
||||
"""审计日志 API —— 查看系统操作审计记录
|
||||
|
||||
与 MOM(KCGL) /audit/logs 的接口保持同构的筛选维度(操作人/模块/动作/目标/
|
||||
时间区间),便于两端运维习惯统一;额外提供 request_id 筛选,可凭它直接跳到
|
||||
结构化日志里的那一次请求。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, time, timedelta
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import require_admin
|
||||
from app.core.time_utils import BEIJING_TZ
|
||||
from app.schemas.audit import (
|
||||
AuditLogListResponse,
|
||||
AuditLogResponse,
|
||||
AuditOption,
|
||||
AuditOptionsResponse,
|
||||
)
|
||||
from app.services import audit_service
|
||||
from app.services.audit_service import ACTION_LABELS, MODULE_LABELS
|
||||
|
||||
router = APIRouter(prefix="/audit", tags=["审计日志"])
|
||||
|
||||
|
||||
def _parse_day(value: str | None, *, end_of_day: bool = False) -> datetime | None:
|
||||
"""解析 YYYY-MM-DD 为北京时间。
|
||||
|
||||
结束日期取次日 00:00 作为上界(配合 < 判断)—— 直接取当天 23:59:59 会
|
||||
漏掉该秒内的记录,是日期区间筛选最常见的差一错误。
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
day = datetime.strptime(value, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
if end_of_day:
|
||||
return datetime.combine(day + timedelta(days=1), time.min, tzinfo=BEIJING_TZ)
|
||||
return datetime.combine(day, time.min, tzinfo=BEIJING_TZ)
|
||||
|
||||
|
||||
@router.get("/logs", response_model=AuditLogListResponse)
|
||||
async def get_audit_logs(
|
||||
user_id: str | None = Query(None, description="操作人账号(模糊匹配)"),
|
||||
module: str | None = Query(None, description="业务模块"),
|
||||
action: str | None = Query(None, description="动作类型"),
|
||||
target_id: str | None = Query(None, description="目标ID"),
|
||||
request_id: str | None = Query(None, description="请求ID(与接口日志对账)"),
|
||||
status_code: int | None = Query(None, description="响应状态码"),
|
||||
start_date: str | None = Query(None, description="起始日期 YYYY-MM-DD"),
|
||||
end_date: str | None = Query(None, description="结束日期 YYYY-MM-DD(含当天)"),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(50, ge=1, le=200),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict = Depends(require_admin),
|
||||
) -> AuditLogListResponse:
|
||||
"""审计日志分页查询(按时间倒序)"""
|
||||
start = _parse_day(start_date)
|
||||
# 结束日期用「次日 00:00」作为开区间上界,避免漏掉当天最后几条
|
||||
end_exclusive = _parse_day(end_date, end_of_day=True)
|
||||
|
||||
rows, total = await audit_service.list_audit_logs(
|
||||
db,
|
||||
user_id=user_id,
|
||||
module=module,
|
||||
action=action,
|
||||
target_id=target_id,
|
||||
request_id=request_id,
|
||||
status_code=status_code,
|
||||
start=start,
|
||||
end=end_exclusive - timedelta(microseconds=1) if end_exclusive else None,
|
||||
skip=(page - 1) * page_size,
|
||||
limit=page_size,
|
||||
)
|
||||
|
||||
items = []
|
||||
for row in rows:
|
||||
item = AuditLogResponse.model_validate(row)
|
||||
# 中文标签由服务端补,避免前端为每个枚举再维护一份映射
|
||||
item.module_label = MODULE_LABELS.get(row.module, row.module)
|
||||
item.action_label = ACTION_LABELS.get(row.action, row.action)
|
||||
items.append(item)
|
||||
|
||||
return AuditLogListResponse(items=items, total=total)
|
||||
|
||||
|
||||
@router.get("/options", response_model=AuditOptionsResponse)
|
||||
async def get_audit_options(
|
||||
current_user: dict = Depends(require_admin),
|
||||
) -> AuditOptionsResponse:
|
||||
"""筛选项:模块与动作的中文下拉"""
|
||||
return AuditOptionsResponse(
|
||||
modules=[AuditOption(value=k, label=v) for k, v in MODULE_LABELS.items()],
|
||||
actions=[AuditOption(value=k, label=v) for k, v in ACTION_LABELS.items()],
|
||||
)
|
||||
@ -1,5 +1,5 @@
|
||||
"""认证 API — 对接 MOM sys_user + 双 Token 刷新"""
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from app.schemas.user import (
|
||||
LoginRequest,
|
||||
LoginResponse,
|
||||
@ -13,8 +13,13 @@ router = APIRouter(prefix="/auth", tags=["认证"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login_endpoint(data: LoginRequest):
|
||||
def login_endpoint(data: LoginRequest, request: Request):
|
||||
"""登录 — 验证 MOM sys_user 表,返回 Access + Refresh 双 Token"""
|
||||
# 登录请求本身尚未认证,中间件拿不到操作人。但「谁在尝试登录、失败了多少次」
|
||||
# 恰恰是审计里最该有的信息,所以在校验之前就把尝试的账号写进 state:
|
||||
# 登录失败时同样留痕,且能按账号追踪暴力破解。
|
||||
# 注意:绝不把 data.password 写进 state / 审计,密码不落库。
|
||||
request.state.audit_user = data.username
|
||||
return login(data.username, data.password)
|
||||
|
||||
|
||||
|
||||
@ -17,6 +17,7 @@ from app.api.v1.endpoints.holidays import router as holidays_router
|
||||
from app.api.v1.endpoints.webhooks import router as webhooks_router
|
||||
from app.api.v1.endpoints.external_products import router as external_products_router
|
||||
from app.api.v1.endpoints.screen import router as screen_router
|
||||
from app.api.v1.endpoints.audit import router as audit_router
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
@ -37,3 +38,4 @@ api_router.include_router(holidays_router)
|
||||
api_router.include_router(webhooks_router)
|
||||
api_router.include_router(external_products_router)
|
||||
api_router.include_router(screen_router)
|
||||
api_router.include_router(audit_router)
|
||||
|
||||
195
backend/app/core/audit_middleware.py
Normal file
195
backend/app/core/audit_middleware.py
Normal file
@ -0,0 +1,195 @@
|
||||
"""审计采集中间件
|
||||
|
||||
在响应生成后,把「谁 / 何时 / 从哪来 / 调了哪个接口 / 做了什么 / 结果如何」
|
||||
落进 audit_logs。
|
||||
|
||||
为什么用中间件自动采集,而不是在每个业务函数里手写 record_audit
|
||||
------------------------------------------------------------------
|
||||
1. 手写必然漏。新加的端点很容易忘记补审计,而审计的价值恰恰建立在「完整」上。
|
||||
现状可佐证:task_logs 全项目只有 4 处写入点,凡是不挂在任务上的动作
|
||||
(登录、导出、改产品)全都没有留痕。
|
||||
2. 中间件能拿到业务函数拿不到的事实:真实来源 IP、UA、最终状态码、
|
||||
以及与结构化日志对齐的 request_id。
|
||||
3. 业务语义(module / target)由路径推导,不如手写精确,但对「谁动了什么」
|
||||
的追责场景已经够用;关键动作后续可再调 record_audit 补 details 做增强。
|
||||
|
||||
采集范围
|
||||
--------
|
||||
- 所有写操作(POST/PUT/PATCH/DELETE)
|
||||
- 少数**读但敏感**的操作:导出、下载、打印(本项目 GET /people-history/export
|
||||
就是导出,只按方法过滤会漏掉)
|
||||
|
||||
明确不采集:GET /health*、/docs、/openapi.json —— 探针与文档的噪声没有审计价值。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.services.audit_service import record_audit
|
||||
|
||||
logger = logging.getLogger("track.audit")
|
||||
|
||||
# 写操作一律采集
|
||||
_MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
||||
|
||||
# 读操作里需要留痕的(导出/下载/打印属于「读」,但把数据带出了系统)
|
||||
_SENSITIVE_READ_KEYWORDS = frozenset({"export", "download", "print"})
|
||||
|
||||
# 永久忽略的路径前缀
|
||||
_IGNORED_PREFIXES = ("/health", "/docs", "/redoc", "/openapi.json")
|
||||
|
||||
# 路径段 → 审计模块
|
||||
_PATH_MODULE: dict[str, str] = {
|
||||
"products": "product",
|
||||
"tasks": "task",
|
||||
"orders": "order",
|
||||
"records": "record",
|
||||
"print": "print",
|
||||
"materials": "material",
|
||||
"users": "user",
|
||||
"upload": "upload",
|
||||
"notifications": "notification",
|
||||
"app-version": "app",
|
||||
"analytics": "analytics",
|
||||
"dashboard": "dashboard",
|
||||
"holidays": "holiday",
|
||||
"screen": "screen",
|
||||
"webhooks": "external",
|
||||
"external": "external",
|
||||
"audit": "audit",
|
||||
"auth": "auth",
|
||||
}
|
||||
|
||||
# 路径段 → 动作(优先于按 HTTP 方法推断)
|
||||
_SEGMENT_ACTION: dict[str, str] = {
|
||||
"login": "login",
|
||||
"logout": "logout",
|
||||
"refresh": "refresh",
|
||||
"export": "export",
|
||||
"download": "export",
|
||||
"print": "print",
|
||||
"upload": "upload",
|
||||
"finalize": "finalize",
|
||||
"receive": "receive",
|
||||
"transfer": "transfer",
|
||||
"reject": "reject",
|
||||
"recall": "recall",
|
||||
"spawn": "spawn",
|
||||
"complete": "complete",
|
||||
"end": "end",
|
||||
}
|
||||
|
||||
_METHOD_ACTION: dict[str, str] = {
|
||||
"POST": "create",
|
||||
"PUT": "update",
|
||||
"PATCH": "update",
|
||||
"DELETE": "delete",
|
||||
"GET": "read",
|
||||
}
|
||||
|
||||
# 不可能是业务 ID 的路径段,避免把动作词误当成 target_id
|
||||
_NON_ID_SEGMENTS = frozenset(
|
||||
set(_SEGMENT_ACTION) | {"api", "v1", "me", "options", "export", "lookup", "batch"}
|
||||
)
|
||||
|
||||
|
||||
def _derive_module_and_action(path: str, method: str) -> tuple[str, str, str | None]:
|
||||
"""由请求路径与 HTTP 方法推导 (module, action, target_id)"""
|
||||
parts = [p for p in path.split("/") if p]
|
||||
|
||||
module = "other"
|
||||
module_idx = -1
|
||||
for i, seg in enumerate(parts):
|
||||
if seg in _PATH_MODULE:
|
||||
module = _PATH_MODULE[seg]
|
||||
module_idx = i
|
||||
break
|
||||
|
||||
action = None
|
||||
for seg in reversed(parts):
|
||||
if seg in _SEGMENT_ACTION:
|
||||
action = _SEGMENT_ACTION[seg]
|
||||
break
|
||||
if action is None:
|
||||
action = _METHOD_ACTION.get(method, method.lower())
|
||||
|
||||
target_id = None
|
||||
if module_idx >= 0 and module_idx + 1 < len(parts):
|
||||
candidate = parts[module_idx + 1]
|
||||
if candidate not in _NON_ID_SEGMENTS:
|
||||
target_id = candidate
|
||||
|
||||
return module, action, target_id
|
||||
|
||||
|
||||
class AuditMiddleware(BaseHTTPMiddleware):
|
||||
"""写操作审计采集。
|
||||
|
||||
必须注册在 RequestContextMiddleware **内层**,因为它依赖后者写入
|
||||
request.state 的 request_id 才能与结构化日志对账。
|
||||
"""
|
||||
|
||||
def _should_audit(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
if path.startswith(_IGNORED_PREFIXES):
|
||||
return False
|
||||
if request.method in _MUTATING_METHODS:
|
||||
return True
|
||||
if request.method == "GET":
|
||||
lowered = path.lower()
|
||||
return any(kw in lowered for kw in _SENSITIVE_READ_KEYWORDS)
|
||||
return False
|
||||
|
||||
async def dispatch(
|
||||
self, request: Request, call_next: RequestResponseEndpoint
|
||||
) -> Response:
|
||||
if not self._should_audit(request):
|
||||
return await call_next(request)
|
||||
|
||||
status_code = 500
|
||||
error_message: str | None = None
|
||||
try:
|
||||
response = await call_next(request)
|
||||
status_code = response.status_code
|
||||
return response
|
||||
except Exception as exc:
|
||||
# 异常最终由 ServerErrorMiddleware 转成 500;这里先标记,
|
||||
# 保证「失败的操作也有审计」——这正是选用独立 session 的目的
|
||||
error_message = f"{type(exc).__name__}: {exc}"[:1000]
|
||||
raise
|
||||
finally:
|
||||
await self._write(request, status_code, error_message)
|
||||
|
||||
async def _write(
|
||||
self, request: Request, status_code: int, error_message: str | None
|
||||
) -> None:
|
||||
try:
|
||||
module, action, target_id = _derive_module_and_action(
|
||||
request.url.path, request.method
|
||||
)
|
||||
client = request.client
|
||||
await record_audit(
|
||||
action=action,
|
||||
module=module,
|
||||
user_id=getattr(request.state, "audit_user", None),
|
||||
display_name=getattr(request.state, "audit_display_name", None),
|
||||
role=getattr(request.state, "audit_role", None),
|
||||
target_type=module,
|
||||
target_id=target_id,
|
||||
# 对产品而言路径里的 ID 就是身份证号,本身即人可读的标识
|
||||
target_name=target_id if module == "product" else None,
|
||||
ip_address=client.host if client else None,
|
||||
user_agent=request.headers.get("user-agent"),
|
||||
method=request.method,
|
||||
url=request.url.path,
|
||||
status_code=status_code,
|
||||
error_message=error_message,
|
||||
request_id=getattr(request.state, "request_id", None),
|
||||
)
|
||||
except Exception:
|
||||
# record_audit 内部已兜底;这里再兜一层,确保审计绝不冒泡成 500
|
||||
logger.exception("审计采集失败(已忽略)")
|
||||
@ -16,6 +16,17 @@ class Settings(BaseSettings):
|
||||
# ---- 调试 ----
|
||||
DEBUG: bool = True
|
||||
|
||||
# ---- 应用元信息 ----
|
||||
APP_VERSION: str = "1.0.0"
|
||||
|
||||
# ---- 日志 ----
|
||||
LOG_LEVEL: str = "INFO"
|
||||
LOG_JSON: bool = True # 生产保持 True(便于采集);本地调试可设 False 换可读格式
|
||||
|
||||
# ---- 错误追踪(可选,不装 sentry-sdk 则自动跳过)----
|
||||
SENTRY_DSN: str | None = None
|
||||
SENTRY_TRACES_SAMPLE_RATE: float = 0.0
|
||||
|
||||
# ---- CORS 跨域白名单(JSON 数组字符串,直接从 .env 的 CORS_ORIGINS 读取) ----
|
||||
CORS_ORIGINS: str = '["http://localhost:1420", "tauri://localhost"]'
|
||||
|
||||
|
||||
35
backend/app/core/deps.py
Normal file
35
backend/app/core/deps.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""通用 FastAPI 依赖"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
|
||||
from app.core.roles import ADMIN_ROLES
|
||||
from app.services.auth_service import get_current_user
|
||||
|
||||
|
||||
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)
|
||||
93
backend/app/core/health.py
Normal file
93
backend/app/core/health.py
Normal file
@ -0,0 +1,93 @@
|
||||
"""健康检查 — 存活探针与就绪探针分离
|
||||
|
||||
为什么必须拆开:
|
||||
- 存活探针(liveness)只回答「进程还活着吗」,绝不能探测外部依赖。
|
||||
否则数据库抖一下,编排系统会判定进程已死并反复重启容器,
|
||||
把一次依赖故障放大成全站雪崩。
|
||||
- 就绪探针(readiness)回答「现在能对外服务吗」。依赖不可用时返回 503,
|
||||
由负载均衡把该实例摘掉,依赖恢复后自动回来。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import anyio
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import AsyncSessionLocal
|
||||
from app.core.mom_database import mom_engine
|
||||
|
||||
logger = logging.getLogger("track.health")
|
||||
|
||||
router = APIRouter(tags=["健康检查"])
|
||||
|
||||
|
||||
async def _probe_primary_db() -> bool:
|
||||
"""主库探活 — 业务强依赖,失败即不就绪"""
|
||||
try:
|
||||
async with AsyncSessionLocal() as session:
|
||||
await session.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("主库探活失败")
|
||||
return False
|
||||
|
||||
|
||||
def _probe_mom_db_sync() -> bool:
|
||||
try:
|
||||
with mom_engine.connect() as conn:
|
||||
conn.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("MOM 库探活失败")
|
||||
return False
|
||||
|
||||
|
||||
async def _probe_mom_db() -> bool:
|
||||
# MOM 用的是同步引擎,放线程池执行,避免阻塞事件循环
|
||||
return await anyio.to_thread.run_sync(_probe_mom_db_sync)
|
||||
|
||||
|
||||
async def _collect() -> tuple[bool, dict[str, str]]:
|
||||
primary_ok = await _probe_primary_db()
|
||||
mom_ok = await _probe_mom_db()
|
||||
checks = {
|
||||
"database": "ok" if primary_ok else "fail",
|
||||
# MOM 是外部只读依赖:挂掉时登录/选料降级,但扫码、流转、看板仍可用。
|
||||
# 因此只标记 degraded、不摘流量 —— 否则 MOM 一抖就让在产车间全线停摆。
|
||||
"mom_database": "ok" if mom_ok else "degraded",
|
||||
}
|
||||
return primary_ok, checks
|
||||
|
||||
|
||||
@router.get("/health/live", include_in_schema=False)
|
||||
async def liveness() -> dict:
|
||||
"""存活探针:不触碰任何依赖,恒定快速返回"""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready", include_in_schema=False)
|
||||
async def readiness() -> JSONResponse:
|
||||
"""就绪探针:主库不可用时返回 503,让负载均衡摘流量"""
|
||||
ready, checks = await _collect()
|
||||
return JSONResponse(
|
||||
{"status": "ready" if ready else "not_ready", "checks": checks},
|
||||
status_code=200 if ready else 503,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/health", include_in_schema=False)
|
||||
async def health() -> JSONResponse:
|
||||
"""兼容旧监控脚本:语义等同就绪探针,并附带版本号"""
|
||||
ready, checks = await _collect()
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "ok" if ready else "unavailable",
|
||||
"version": settings.APP_VERSION,
|
||||
"checks": checks,
|
||||
},
|
||||
status_code=200 if ready else 503,
|
||||
)
|
||||
89
backend/app/core/logging.py
Normal file
89
backend/app/core/logging.py
Normal file
@ -0,0 +1,89 @@
|
||||
"""结构化日志 — 单行 JSON 输出 + 请求上下文注入
|
||||
|
||||
设计要点:
|
||||
1. 零第三方依赖,只用 stdlib(logging + json + contextvars)。
|
||||
2. 业务代码通过 `extra={"extra_fields": {...}}` 附加结构化字段,
|
||||
不要把可检索的字段拼进 msg 字符串 —— 拼进去就只能靠正则捞了。
|
||||
3. request_id / user 走 contextvar。contextvar 在 asyncio 下按任务隔离,
|
||||
并发请求之间不会串号;由 RequestContextMiddleware 与 get_current_user 写入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from contextvars import ContextVar
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# 请求级上下文
|
||||
request_id_var: ContextVar[str | None] = ContextVar("request_id", default=None)
|
||||
user_var: ContextVar[str | None] = ContextVar("user", default=None)
|
||||
|
||||
|
||||
class _ContextFilter(logging.Filter):
|
||||
"""把 contextvar 注入每条 record,使 JSON 自带 request_id / user"""
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
record.request_id = request_id_var.get()
|
||||
record.user = user_var.get()
|
||||
return True
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
"""单行 JSON — 便于 Loki / ELK / CloudWatch 直接解析,无需正则"""
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
payload: dict = {
|
||||
"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"msg": record.getMessage(),
|
||||
}
|
||||
if getattr(record, "request_id", None):
|
||||
payload["request_id"] = record.request_id
|
||||
if getattr(record, "user", None):
|
||||
payload["user"] = record.user
|
||||
payload.update(getattr(record, "extra_fields", None) or {})
|
||||
if record.exc_info:
|
||||
payload["exc"] = self.formatException(record.exc_info)
|
||||
return json.dumps(payload, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
class TextFormatter(logging.Formatter):
|
||||
"""本地开发可读格式(LOG_JSON=false 时启用)"""
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
line = (
|
||||
f"{self.formatTime(record, '%H:%M:%S')} "
|
||||
f"{record.levelname:<5} {record.name} - {record.getMessage()}"
|
||||
)
|
||||
extras = getattr(record, "extra_fields", None)
|
||||
if extras:
|
||||
line += " | " + " ".join(f"{k}={v}" for k, v in extras.items())
|
||||
if record.exc_info:
|
||||
line += "\n" + self.formatException(record.exc_info)
|
||||
return line
|
||||
|
||||
|
||||
def setup_logging(level: str = "INFO", json_output: bool = True) -> None:
|
||||
"""配置根 logger。必须在应用启动前调用一次。"""
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter() if json_output else TextFormatter())
|
||||
handler.addFilter(_ContextFilter())
|
||||
|
||||
root = logging.getLogger()
|
||||
# 清空既有 handler:uvicorn --reload / 多 worker 下模块可能被重复导入,
|
||||
# 不清会看到每条日志打印 N 遍
|
||||
root.handlers.clear()
|
||||
root.addHandler(handler)
|
||||
root.setLevel(level.upper())
|
||||
|
||||
# uvicorn 自带 handler 会绕过上面的 formatter,必须清掉并让它向根传播
|
||||
for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
|
||||
lg = logging.getLogger(name)
|
||||
lg.handlers.clear()
|
||||
lg.propagate = True
|
||||
|
||||
# 访问日志统一由 RequestContextMiddleware 输出(含耗时 / 用户 / request_id),
|
||||
# 故关闭 uvicorn 自带的访问日志,避免重复
|
||||
logging.getLogger("uvicorn.access").disabled = True
|
||||
87
backend/app/core/middleware.py
Normal file
87
backend/app/core/middleware.py
Normal file
@ -0,0 +1,87 @@
|
||||
"""请求上下文中间件 — request_id 生成/透传 + 结构化访问日志"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
|
||||
from app.core.logging import request_id_var, user_var
|
||||
|
||||
access_log = logging.getLogger("track.access")
|
||||
|
||||
# 探针被高频轮询,降级为 DEBUG 避免把有价值的信息淹掉
|
||||
_QUIET_PATHS = frozenset({"/health", "/health/live", "/health/ready"})
|
||||
|
||||
|
||||
class RequestContextMiddleware(BaseHTTPMiddleware):
|
||||
"""为每个请求建立可追踪上下文。
|
||||
|
||||
- request_id:优先沿用上游网关传来的 X-Request-ID,实现全链路追踪;
|
||||
没有就生成一个。响应头回写该 ID,前端报错时可直接带上,
|
||||
运维拿 ID 就能在日志里精确定位到这一次请求。
|
||||
- 访问日志:method / path / status / duration_ms / client / user。
|
||||
"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
request_id = request.headers.get("X-Request-ID") or uuid.uuid4().hex
|
||||
# 同时写入 request.state:它由 ASGI scope 承载,作用域比 contextvar 更长。
|
||||
# FastAPI 把 Exception 处理器交给 ServerErrorMiddleware(位于本中间件外层),
|
||||
# 异常传播到那里时 contextvar 已在 finally 中被重置,只有 state 还留着 ID。
|
||||
request.state.request_id = request_id
|
||||
rid_token = request_id_var.set(request_id)
|
||||
user_token = user_var.set(None)
|
||||
started = time.perf_counter()
|
||||
logged = False
|
||||
status_code = 500
|
||||
try:
|
||||
response = await call_next(request)
|
||||
status_code = response.status_code
|
||||
response.headers["X-Request-ID"] = request_id
|
||||
self._log_access(request, status_code, started)
|
||||
logged = True
|
||||
return response
|
||||
finally:
|
||||
# 异常路径也要留下访问记录,否则接口 500 时日志里反而没有痕迹
|
||||
if not logged:
|
||||
self._log_access(request, status_code, started)
|
||||
request_id_var.reset(rid_token)
|
||||
user_var.reset(user_token)
|
||||
|
||||
def _log_access(self, request: Request, status_code: int, started: float) -> None:
|
||||
path = request.url.path
|
||||
duration_ms = round((time.perf_counter() - started) * 1000, 1)
|
||||
|
||||
# user 必须从 request.state 取:本中间件在独立 task 中执行,路由内
|
||||
# 写入的 contextvar 不会回流到这里(详见 get_current_user 的说明)。
|
||||
user = getattr(request.state, "audit_user", None) or user_var.get()
|
||||
|
||||
if status_code >= 500:
|
||||
level = logging.ERROR
|
||||
elif status_code >= 400:
|
||||
level = logging.WARNING
|
||||
elif path in _QUIET_PATHS:
|
||||
level = logging.DEBUG
|
||||
else:
|
||||
level = logging.INFO
|
||||
|
||||
access_log.log(
|
||||
level,
|
||||
"%s %s -> %s (%.1fms)",
|
||||
request.method,
|
||||
path,
|
||||
status_code,
|
||||
duration_ms,
|
||||
extra={
|
||||
"extra_fields": {
|
||||
"method": request.method,
|
||||
"path": path,
|
||||
"status": status_code,
|
||||
"duration_ms": duration_ms,
|
||||
"client": request.client.host if request.client else None,
|
||||
"user": user,
|
||||
}
|
||||
},
|
||||
)
|
||||
31
backend/app/core/roles.py
Normal file
31
backend/app/core/roles.py
Normal file
@ -0,0 +1,31 @@
|
||||
"""角色定义与管理员判定 —— 单一事实来源
|
||||
|
||||
背景:角色字符串此前散落在至少三处 —— task_service.ADMIN_ROLES、
|
||||
products.py 的内联判断、以及前端 constants/task.ts。同一份规则抄多份的后果
|
||||
已经发生过:前端 constants/task.ts:233 的注释记录了一次「移动端只判了
|
||||
SUPER_ADMIN、漏了 SUPERVISOR,导致主管被误挡」的事故。
|
||||
|
||||
本模块把**角色常量与管理员判定**先收敛到一处,供后端统一引用。
|
||||
完整的「角色 × 权限点」可配置矩阵是后续工作;但任何推进都应从这里出发,
|
||||
不要再新增第四份副本。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
SUPER_ADMIN = "SUPER_ADMIN"
|
||||
SUPERVISOR = "SUPERVISOR"
|
||||
# 注意:MOM 登录返回的默认角色是小写 operator(见 auth_service.login)
|
||||
OPERATOR = "OPERATOR"
|
||||
|
||||
# 管理员角色:可执行收口、审计查看等高权限动作
|
||||
ADMIN_ROLES: frozenset[str] = frozenset({SUPER_ADMIN, SUPERVISOR})
|
||||
|
||||
ROLE_LABELS: dict[str, str] = {
|
||||
SUPER_ADMIN: "超级管理员",
|
||||
SUPERVISOR: "主管",
|
||||
OPERATOR: "操作员",
|
||||
}
|
||||
|
||||
|
||||
def is_admin(role: str | None) -> bool:
|
||||
"""role 为 None / 未知值一律视为无权限(fail-closed,不做兜底放行)"""
|
||||
return role in ADMIN_ROLES
|
||||
@ -1,22 +1,64 @@
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.core.config import settings
|
||||
from app.core.audit_middleware import AuditMiddleware
|
||||
from app.core.health import router as health_router
|
||||
from app.core.logging import request_id_var, setup_logging
|
||||
from app.core.middleware import RequestContextMiddleware
|
||||
from app.api.v1.router import api_router
|
||||
|
||||
# 日志必须在任何模块开始产日志之前配置好,故放模块顶层而非 lifespan 内
|
||||
setup_logging(level=settings.LOG_LEVEL, json_output=settings.LOG_JSON)
|
||||
|
||||
logger = logging.getLogger("track.main")
|
||||
|
||||
|
||||
def _init_error_tracking() -> None:
|
||||
"""可选错误追踪:未配置 DSN,或未安装 sentry-sdk 时静默跳过"""
|
||||
if not settings.SENTRY_DSN:
|
||||
return
|
||||
try:
|
||||
import sentry_sdk
|
||||
except ImportError:
|
||||
logger.warning(
|
||||
"已配置 SENTRY_DSN 但未安装 sentry-sdk,错误追踪未启用;"
|
||||
"需要时执行 pip install sentry-sdk"
|
||||
)
|
||||
return
|
||||
sentry_sdk.init(
|
||||
dsn=settings.SENTRY_DSN,
|
||||
traces_sample_rate=settings.SENTRY_TRACES_SAMPLE_RATE,
|
||||
environment="production" if not settings.DEBUG else "development",
|
||||
release=settings.APP_VERSION,
|
||||
)
|
||||
logger.info("错误追踪已启用 (Sentry)")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""应用生命周期:启动时初始化连接,关闭时释放资源"""
|
||||
# 启动:验证数据库连接等
|
||||
_init_error_tracking()
|
||||
logger.info(
|
||||
"服务启动",
|
||||
extra={
|
||||
"extra_fields": {
|
||||
"version": settings.APP_VERSION,
|
||||
"debug": settings.DEBUG,
|
||||
"cors_origins": settings.CORS_ORIGINS_LIST,
|
||||
}
|
||||
},
|
||||
)
|
||||
yield
|
||||
# 关闭:清理资源
|
||||
logger.info("服务关闭")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Track Production API",
|
||||
description="工厂生产流转管理系统 API",
|
||||
version="0.1.0",
|
||||
version=settings.APP_VERSION,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@ -27,12 +69,45 @@ app.add_middleware(
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
# 暴露给浏览器 JS 读取:前端报错时才能把 request_id 一起带上便于对账
|
||||
expose_headers=["X-Request-ID"],
|
||||
)
|
||||
|
||||
# Starlette 的 add_middleware 是「后添加者在外层」。执行顺序(由外到内):
|
||||
# RequestContextMiddleware -> AuditMiddleware -> CORS -> 路由
|
||||
# AuditMiddleware 必须在 RequestContext 内层,才能读到后者写入 request.state
|
||||
# 的 request_id,从而把审计记录与结构化日志对上。
|
||||
app.add_middleware(AuditMiddleware)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
"""兜底异常处理。
|
||||
|
||||
完整堆栈只进日志;响应体仅返回 request_id —— 既不把内部实现泄露给客户端,
|
||||
又让用户报障时能凭这个 ID 在日志里精确定位到本次失败。
|
||||
"""
|
||||
# 优先取 request.state(见 RequestContextMiddleware 的说明):
|
||||
# 本处理器由 ServerErrorMiddleware 调用,此时 contextvar 已被重置
|
||||
request_id = getattr(request.state, "request_id", None) or request_id_var.get()
|
||||
logger.exception(
|
||||
"未处理异常: %s %s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
extra={"extra_fields": {"method": request.method, "path": request.url.path}},
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"detail": "服务器内部错误", "request_id": request_id},
|
||||
# 该响应由 ServerErrorMiddleware(位于 RequestContextMiddleware 外层)
|
||||
# 生成,中间件没机会再往响应头写 X-Request-ID,故在此显式补上,
|
||||
# 保证报障时前端从响应头就能拿到可对账的 ID。
|
||||
headers={"X-Request-ID": request_id} if request_id else None,
|
||||
)
|
||||
|
||||
|
||||
# ---- 注册路由 ----
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "ok", "version": "0.1.0"}
|
||||
# 健康检查挂在根路径(/health*),运维探针不经过 /api/v1
|
||||
app.include_router(health_router)
|
||||
|
||||
@ -8,6 +8,7 @@ from app.models.notification import Notification
|
||||
from app.models.app_version import AppVersion
|
||||
from app.models.message import ProductMessage
|
||||
from app.models.holiday import Holiday
|
||||
from app.models.audit_log import AuditLog
|
||||
__all__ = [
|
||||
"Base",
|
||||
"ProductionOrder",
|
||||
@ -19,4 +20,5 @@ __all__ = [
|
||||
"AppVersion",
|
||||
"ProductMessage",
|
||||
"Holiday",
|
||||
"AuditLog",
|
||||
]
|
||||
|
||||
83
backend/app/models/audit_log.py
Normal file
83
backend/app/models/audit_log.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""操作审计日志模型
|
||||
|
||||
设计参考 MOM(KCGL) 的 audit_logs,但按 Track 的技术栈与诉求做了取舍:
|
||||
|
||||
- 主键用 UUID(与库内其它表一致),而非 MOM 的自增 int。
|
||||
- 增加 request_id:与 core/logging.py 的结构化日志打通 —— 凭一个 ID 就能把
|
||||
「接口访问日志」和「审计记录」对上,排障时不用再猜。MOM 无此字段。
|
||||
- 保留 module / action / target_* 的业务语义,使审计能按业务维度检索,
|
||||
而不是只能按时间翻。
|
||||
- 绝不记录请求体:登录等接口 body 含明文密码,一旦落库就成了长期泄露面。
|
||||
|
||||
与既有 task_logs 的分工:task_logs 是「任务流转轨迹」(有 task_id 非空约束,
|
||||
只能挂在任务上,供流转树渲染);本表是「操作审计」,覆盖登录、导出、
|
||||
产品增删改、权限变更等与单个任务无关的动作,且额外记录来源 IP / UA / 耗时结果。
|
||||
"""
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
from app.core.time_utils import get_beijing_time
|
||||
|
||||
|
||||
class AuditLog(Base):
|
||||
__tablename__ = "audit_logs"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,
|
||||
)
|
||||
|
||||
# ---- 操作人(逻辑外键 → MOM sys_user,仅存账号,无物理约束)----
|
||||
user_id: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, index=True, comment="操作人账号(逻辑外键→MOM)",
|
||||
)
|
||||
display_name: Mapped[str | None] = mapped_column(
|
||||
String(100), nullable=True, comment="操作人显示名",
|
||||
)
|
||||
role: Mapped[str | None] = mapped_column(
|
||||
String(50), nullable=True, comment="操作时角色快照",
|
||||
)
|
||||
|
||||
# ---- 业务语义 ----
|
||||
action: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, index=True, comment="动作: create/update/delete/export/login/...",
|
||||
)
|
||||
module: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, index=True, comment="业务模块: product/task/order/auth/print/...",
|
||||
)
|
||||
target_type: Mapped[str | None] = mapped_column(
|
||||
String(50), nullable=True, comment="目标类型(表名或实体名)",
|
||||
)
|
||||
target_id: Mapped[str | None] = mapped_column(
|
||||
String(100), nullable=True, index=True, comment="目标ID",
|
||||
)
|
||||
target_name: Mapped[str | None] = mapped_column(
|
||||
String(200), nullable=True, comment="目标显示名(如产品身份证/工单号)",
|
||||
)
|
||||
details: Mapped[dict | None] = mapped_column(
|
||||
JSONB, nullable=True, comment="变更详情 {old:{}, new:{}};禁止写入密码等敏感字段",
|
||||
)
|
||||
|
||||
# ---- 请求上下文(由中间件自动填充)----
|
||||
ip_address: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="来源IP")
|
||||
user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True, comment="浏览器UA")
|
||||
method: Mapped[str | None] = mapped_column(String(10), nullable=True, comment="HTTP方法")
|
||||
url: Mapped[str | None] = mapped_column(String(500), nullable=True, comment="请求路径")
|
||||
status_code: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="响应状态码")
|
||||
error_message: Mapped[str | None] = mapped_column(Text, nullable=True, comment="错误信息(如有)")
|
||||
|
||||
# ---- 与结构化日志对账用 ----
|
||||
request_id: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, index=True, comment="关联 core/logging 的 request_id",
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=get_beijing_time, index=True, comment="操作时间",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<AuditLog {self.action} {self.module} by {self.user_id}>"
|
||||
57
backend/app/schemas/audit.py
Normal file
57
backend/app/schemas/audit.py
Normal file
@ -0,0 +1,57 @@
|
||||
"""审计日志 Pydantic Schema"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class AuditLogResponse(BaseModel):
|
||||
"""单条审计记录"""
|
||||
id: uuid.UUID
|
||||
user_id: str | None = None
|
||||
display_name: str | None = None
|
||||
role: str | None = None
|
||||
|
||||
action: str
|
||||
action_label: str | None = None # 服务端补的中文标签,避免前端各处硬编码
|
||||
module: str
|
||||
module_label: str | None = None
|
||||
|
||||
target_type: str | None = None
|
||||
target_id: str | None = None
|
||||
target_name: str | None = None
|
||||
details: dict | None = None
|
||||
|
||||
ip_address: str | None = None
|
||||
user_agent: str | None = None
|
||||
method: str | None = None
|
||||
url: str | None = None
|
||||
status_code: int | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
# 与结构化日志对账用:拿着它就能捞到对应的接口日志
|
||||
request_id: str | None = None
|
||||
|
||||
created_at: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class AuditLogListResponse(BaseModel):
|
||||
"""审计日志分页列表"""
|
||||
items: list[AuditLogResponse]
|
||||
total: int
|
||||
|
||||
|
||||
class AuditOption(BaseModel):
|
||||
"""筛选项(value/label 结构,直接喂给前端下拉)"""
|
||||
value: str
|
||||
label: str
|
||||
|
||||
|
||||
class AuditOptionsResponse(BaseModel):
|
||||
"""筛选项集合"""
|
||||
modules: list[AuditOption]
|
||||
actions: list[AuditOption]
|
||||
200
backend/app/services/audit_service.py
Normal file
200
backend/app/services/audit_service.py
Normal file
@ -0,0 +1,200 @@
|
||||
"""审计服务 — 写入与检索
|
||||
|
||||
写入方案的取舍(与 MOM/KCGL 不同,理由如下)
|
||||
--------------------------------------------------
|
||||
MOM 用 SQLAlchemy event listener + **同事务**写入:优点是全自动、业务代码零改动;
|
||||
缺点是业务事务回滚时审计记录一起被回滚掉 —— 而失败/被拒的操作恰恰是最需要
|
||||
留痕的(比如越权尝试、参数错误导致的 4xx)。
|
||||
|
||||
Track 改为:响应生成后,用**独立 session** 写入审计。
|
||||
- 业务回滚不影响审计,失败操作照样留痕
|
||||
- 审计写入失败也不影响业务(全包裹 try/except,仅记日志)
|
||||
- 代价:审计与业务不是原子提交,极端情况(响应后进程立即被 kill)可能丢一条。
|
||||
对内部系统的操作审计,这个取舍划算。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import AsyncSessionLocal
|
||||
from app.models.audit_log import AuditLog
|
||||
|
||||
logger = logging.getLogger("track.audit")
|
||||
|
||||
# 绝不落库的敏感字段名(命中即替换为 ***)
|
||||
# 登录请求体含明文密码,一旦进审计表就成了长期泄露面
|
||||
_SENSITIVE_KEYS = frozenset(
|
||||
{"password", "passwd", "pwd", "token", "access_token", "refresh_token",
|
||||
"secret", "api_key", "authorization", "password_hash"}
|
||||
)
|
||||
|
||||
# 模块 / 动作 的中文标签(前端下拉与列表展示用)
|
||||
MODULE_LABELS: dict[str, str] = {
|
||||
"auth": "认证登录",
|
||||
"product": "产品管理",
|
||||
"task": "任务流转",
|
||||
"order": "订单管理",
|
||||
"record": "任务记录",
|
||||
"print": "标签打印",
|
||||
"material": "物料",
|
||||
"user": "用户",
|
||||
"notification": "消息通知",
|
||||
"upload": "文件上传",
|
||||
"dashboard": "看板统计",
|
||||
"analytics": "效能分析",
|
||||
"screen": "数据大屏",
|
||||
"holiday": "节假日配置",
|
||||
"app": "App版本",
|
||||
"external": "外部系统对接",
|
||||
"audit": "审计日志",
|
||||
"other": "其它",
|
||||
}
|
||||
|
||||
ACTION_LABELS: dict[str, str] = {
|
||||
"create": "新增",
|
||||
"update": "修改",
|
||||
"delete": "删除",
|
||||
"read": "查询",
|
||||
"export": "导出",
|
||||
"login": "登录",
|
||||
"logout": "登出",
|
||||
"refresh": "刷新令牌",
|
||||
"print": "打印",
|
||||
"upload": "上传",
|
||||
"finalize": "收口",
|
||||
"receive": "接收",
|
||||
"transfer": "转交",
|
||||
"reject": "驳回",
|
||||
"recall": "撤回",
|
||||
"spawn": "派发",
|
||||
"end": "结束分支",
|
||||
"complete": "完结",
|
||||
}
|
||||
|
||||
|
||||
def sanitize_details(details: dict | None) -> dict | None:
|
||||
"""递归剔除敏感字段,避免密码/令牌落库"""
|
||||
if not details:
|
||||
return details
|
||||
|
||||
def _clean(value):
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
k: ("***" if str(k).lower() in _SENSITIVE_KEYS else _clean(v))
|
||||
for k, v in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [_clean(v) for v in value]
|
||||
return value
|
||||
|
||||
return _clean(details)
|
||||
|
||||
|
||||
async def record_audit(
|
||||
*,
|
||||
action: str,
|
||||
module: str,
|
||||
user_id: str | None = None,
|
||||
display_name: str | None = None,
|
||||
role: str | None = None,
|
||||
target_type: str | None = None,
|
||||
target_id: str | None = None,
|
||||
target_name: str | None = None,
|
||||
details: dict | None = None,
|
||||
ip_address: str | None = None,
|
||||
user_agent: str | None = None,
|
||||
method: str | None = None,
|
||||
url: str | None = None,
|
||||
status_code: int | None = None,
|
||||
error_message: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""写入一条审计记录。**绝不抛异常**:审计失败不能影响业务。"""
|
||||
try:
|
||||
async with AsyncSessionLocal() as session:
|
||||
session.add(
|
||||
AuditLog(
|
||||
id=uuid.uuid4(),
|
||||
user_id=user_id,
|
||||
display_name=display_name,
|
||||
role=role,
|
||||
action=action,
|
||||
module=module,
|
||||
target_type=target_type,
|
||||
target_id=str(target_id) if target_id is not None else None,
|
||||
target_name=target_name,
|
||||
details=sanitize_details(details),
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent[:500] if user_agent else None,
|
||||
method=method,
|
||||
url=url[:500] if url else None,
|
||||
status_code=status_code,
|
||||
error_message=error_message,
|
||||
request_id=request_id,
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
except Exception:
|
||||
# 用 exception 级别但吞掉异常:保证调用方业务流程不受影响
|
||||
logger.exception(
|
||||
"审计写入失败(已忽略,不影响业务)",
|
||||
extra={"extra_fields": {"action": action, "module": module, "url": url}},
|
||||
)
|
||||
|
||||
|
||||
async def list_audit_logs(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: str | None = None,
|
||||
module: str | None = None,
|
||||
action: str | None = None,
|
||||
target_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
status_code: int | None = None,
|
||||
start: datetime | None = None,
|
||||
end: datetime | None = None,
|
||||
skip: int = 0,
|
||||
limit: int = 50,
|
||||
) -> tuple[list[AuditLog], int]:
|
||||
"""审计日志检索(按时间倒序)。返回 (当前页, 真实总数)。
|
||||
|
||||
真实总数走独立 COUNT —— 前端分页器依赖它,不能用 len(当前页)。
|
||||
"""
|
||||
filters = []
|
||||
if user_id:
|
||||
filters.append(AuditLog.user_id.ilike(f"%{user_id}%"))
|
||||
if module:
|
||||
filters.append(AuditLog.module == module)
|
||||
if action:
|
||||
filters.append(AuditLog.action == action)
|
||||
if target_id:
|
||||
filters.append(AuditLog.target_id == target_id)
|
||||
if request_id:
|
||||
filters.append(AuditLog.request_id == request_id)
|
||||
if status_code is not None:
|
||||
filters.append(AuditLog.status_code == status_code)
|
||||
if start:
|
||||
filters.append(AuditLog.created_at >= start)
|
||||
if end:
|
||||
filters.append(AuditLog.created_at <= end)
|
||||
|
||||
total = await db.scalar(
|
||||
select(func.count()).select_from(AuditLog).where(*filters)
|
||||
) or 0
|
||||
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(AuditLog)
|
||||
.where(*filters)
|
||||
.order_by(AuditLog.created_at.desc())
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
return list(rows), total
|
||||
@ -1,5 +1,5 @@
|
||||
"""认证服务 — 对接 MOM 系统 sys_user 表 + Track 自有 JWT(双 Token 架构)"""
|
||||
from fastapi import HTTPException, status, Depends
|
||||
from fastapi import HTTPException, status, Depends, Request
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from jose import JWTError, jwt
|
||||
from werkzeug.security import check_password_hash
|
||||
@ -14,6 +14,7 @@ from app.core.security import (
|
||||
TOKEN_TYPE_REFRESH,
|
||||
)
|
||||
from app.core.mom_database import MomSessionLocal
|
||||
from app.core.logging import user_var
|
||||
from app.schemas.user import LoginResponse, UserResponse
|
||||
|
||||
security = HTTPBearer()
|
||||
@ -112,6 +113,7 @@ def refresh_access_token(refresh_token: str) -> dict:
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> dict:
|
||||
"""从 Bearer Token 解析当前用户(仅接受 Access Token)"""
|
||||
@ -129,6 +131,19 @@ async def get_current_user(
|
||||
detail="请使用 Access Token 访问 API,Refresh Token 仅用于刷新",
|
||||
)
|
||||
|
||||
# 操作人身份要写两处,用途不同,缺一不可:
|
||||
# 1) contextvar —— 供本请求任务内的业务/service 日志使用;
|
||||
# 2) request.state —— 中间件在独立 task 中执行(Starlette 的
|
||||
# BaseHTTPMiddleware 用 anyio start_soon 起新 task,而 asyncio
|
||||
# 每个 Task 会复制 context),因此中间件读不到路由内改的
|
||||
# contextvar,只能通过 ASGI scope 承载的 state 拿到。
|
||||
# username 即 assignee_id 口径,比数字 id 直观得多。
|
||||
user_label = payload.get("username") or user_id
|
||||
user_var.set(user_label)
|
||||
request.state.audit_user = user_label
|
||||
request.state.audit_display_name = payload.get("display_name") or ""
|
||||
request.state.audit_role = payload.get("role") or ""
|
||||
|
||||
return payload
|
||||
except JWTError:
|
||||
raise HTTPException(status_code=401, detail="无效的 Token")
|
||||
|
||||
@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import uuid
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select, delete
|
||||
from sqlalchemy import select, delete, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
@ -22,6 +22,7 @@ from app.core.lifecycle import (
|
||||
)
|
||||
from app.models.product import Product
|
||||
from app.models.task_log import TaskLog
|
||||
from app.core.roles import ADMIN_ROLES
|
||||
from app.schemas.task import (
|
||||
TaskCreate,
|
||||
TaskUpdate,
|
||||
@ -42,7 +43,8 @@ from app.schemas.task import (
|
||||
VIRTUAL_WAREHOUSE = "virtual_warehouse"
|
||||
|
||||
# 管理员/主管角色白名单 — 拥有上帝视角操作权限
|
||||
ADMIN_ROLES = {"SUPER_ADMIN", "SUPERVISOR"}
|
||||
# 定义已收敛到 app.core.roles(单一事实来源);本模块继续以同名导出,
|
||||
# 兼容 products.py 等处 `from app.services.task_service import ADMIN_ROLES` 的既有引用
|
||||
|
||||
|
||||
async def _recalc_product_location(
|
||||
@ -457,22 +459,37 @@ async def get_all_tasks(
|
||||
assignee_id: str | None = None, skip: int = 0, limit: int = 50
|
||||
) -> TaskListResponse:
|
||||
"""获取任务列表,可按产品/负责人筛选"""
|
||||
stmt = select(Task).options(
|
||||
selectinload(Task.records),
|
||||
selectinload(Task.product),
|
||||
)
|
||||
filters = []
|
||||
if product_id:
|
||||
stmt = stmt.where(Task.product_id == product_id)
|
||||
filters.append(Task.product_id == product_id)
|
||||
if assignee_id:
|
||||
stmt = stmt.where(Task.assignee_id == assignee_id)
|
||||
stmt = stmt.offset(skip).limit(limit).order_by(Task.created_at.desc())
|
||||
filters.append(Task.assignee_id == assignee_id)
|
||||
|
||||
# 总数必须独立 COUNT:移动端「我的任务」用 total 判断 hasMore
|
||||
# (tasks.length < total),若 total 取当前页条数,首页满员时
|
||||
# hasMore 恒为 false,列表永远停在第一页。
|
||||
total = await db.scalar(
|
||||
select(func.count()).select_from(Task).where(*filters)
|
||||
) or 0
|
||||
|
||||
stmt = (
|
||||
select(Task)
|
||||
.options(
|
||||
selectinload(Task.records),
|
||||
selectinload(Task.product),
|
||||
)
|
||||
.where(*filters)
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
.order_by(Task.created_at.desc())
|
||||
)
|
||||
|
||||
result = await db.execute(stmt)
|
||||
tasks = result.scalars().all()
|
||||
|
||||
# 返回扁平列表(不递归 children,避免 MissingGreenlet)
|
||||
flat_tasks = [_to_flat_response(t) for t in tasks]
|
||||
return TaskListResponse(tasks=flat_tasks, total=len(flat_tasks))
|
||||
return TaskListResponse(tasks=flat_tasks, total=total)
|
||||
|
||||
|
||||
# ============================================================
|
||||
|
||||
@ -41,6 +41,7 @@ const AdminProductsPage = lazy(() => import("./pages/admin/AdminProductsPage"));
|
||||
const AdminTasksPage = lazy(() => import("./pages/admin/AdminTasksPage"));
|
||||
const AdminPeoplePage = lazy(() => import("./pages/admin/AdminPeoplePage"));
|
||||
const AdminPrintConfigPage = lazy(() => import("./pages/admin/AdminPrintConfigPage"));
|
||||
const AdminAuditLogPage = lazy(() => import("./pages/admin/AdminAuditLogPage"));
|
||||
const AnalyticsDashboard = lazy(() => import("./pages/admin/AnalyticsDashboard"));
|
||||
const MatrixBoard = lazy(() => import("./pages/MatrixBoard"));
|
||||
const ScreenDashboard = lazy(() => import("./pages/admin/ScreenDashboard"));
|
||||
@ -79,6 +80,7 @@ export default function App() {
|
||||
<Route path="/admin/print-config" element={<AdminPrintConfigPage />} />
|
||||
<Route path="/admin/analytics" element={<AnalyticsDashboard />} />
|
||||
<Route path="/admin/matrix" element={<MatrixBoard />} />
|
||||
<Route path="/admin/audit" element={<AdminAuditLogPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</Suspense>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { NavLink, Outlet, useLocation, useNavigate, Navigate } from "react-router-dom";
|
||||
import { QrCode, Package, ArrowLeft, LayoutDashboard, Smartphone, GitBranch, LogOut, User, Users, BarChart3, Table2, Tv } from "lucide-react";
|
||||
import { QrCode, Package, ArrowLeft, LayoutDashboard, Smartphone, GitBranch, LogOut, User, Users, BarChart3, Table2, Tv, ScrollText } from "lucide-react";
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
|
||||
const MENU = [
|
||||
@ -39,6 +39,12 @@ const MENU = [
|
||||
icon: Table2,
|
||||
description: "规格型号 × 人员/工序 在制品透视表",
|
||||
},
|
||||
{
|
||||
title: "操作审计",
|
||||
path: "/admin/audit",
|
||||
icon: ScrollText,
|
||||
description: "谁在何时操作了什么 · 含失败与被拒请求",
|
||||
},
|
||||
{
|
||||
title: "管理层大屏",
|
||||
path: "/admin/screen",
|
||||
|
||||
@ -227,7 +227,8 @@ export function overallOptionsFor(
|
||||
|
||||
/** 列表筛选枚举 — 两阶段并集(用于筛选,不是录入项) */
|
||||
/**
|
||||
* 管理角色 — 必须与后端 task_service.ADMIN_ROLES 保持一致。
|
||||
* 管理角色 — 必须与后端 app/core/roles.py 的 ADMIN_ROLES 保持一致
|
||||
* (后端那份已从 task_service 收敛到 core.roles,是全项目唯一事实来源)。
|
||||
*
|
||||
* ⚠️ 收敛到这里的理由:此前这段判断散落在多处(TaskFlowView / AdminProductsPage),
|
||||
* 而移动端那份只判了 SUPER_ADMIN、漏了 SUPERVISOR,导致主管被前端误挡。
|
||||
|
||||
355
frontend/src/pages/admin/AdminAuditLogPage.tsx
Normal file
355
frontend/src/pages/admin/AdminAuditLogPage.tsx
Normal file
@ -0,0 +1,355 @@
|
||||
/** 操作审计日志 — 谁 / 何时 / 从哪 / 对什么 / 做了什么事 / 结果如何 */
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { ScrollText, Loader2, AlertCircle, RefreshCw, Search, X } from "lucide-react";
|
||||
import { Table, Tag, Input, Select, DatePicker, Button, Tooltip, Drawer, Descriptions } from "antd";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import dayjs, { type Dayjs } from "dayjs";
|
||||
import { fetchAuditLogs, fetchAuditOptions, type AuditLogItem, type AuditOption } from "../../services/auditApi";
|
||||
import { extractErrorMessage } from "../../utils/errorMessage";
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
/** HTTP 方法配色 —— 让「这是读还是写」一眼可辨 */
|
||||
const METHOD_CLS: Record<string, string> = {
|
||||
GET: "bg-slate-100 text-slate-600",
|
||||
POST: "bg-emerald-100 text-emerald-700",
|
||||
PUT: "bg-amber-100 text-amber-700",
|
||||
PATCH: "bg-amber-100 text-amber-700",
|
||||
DELETE: "bg-red-100 text-red-700",
|
||||
};
|
||||
|
||||
/** 结果状态:2xx 正常 / 4xx 被拒 / 5xx 服务异常 */
|
||||
function statusCls(code: number | null): string {
|
||||
if (code === null) return "bg-slate-100 text-slate-500";
|
||||
if (code >= 500) return "bg-red-100 text-red-700";
|
||||
if (code >= 400) return "bg-orange-100 text-orange-700";
|
||||
return "bg-emerald-100 text-emerald-700";
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
export default function AdminAuditLogPage() {
|
||||
const [rows, setRows] = useState<AuditLogItem[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [detail, setDetail] = useState<AuditLogItem | null>(null);
|
||||
|
||||
const [modules, setModules] = useState<AuditOption[]>([]);
|
||||
const [actions, setActions] = useState<AuditOption[]>([]);
|
||||
|
||||
// 筛选条件(user_id 用受控输入,其余即时生效)
|
||||
const [userInput, setUserInput] = useState("");
|
||||
const [userId, setUserId] = useState("");
|
||||
const [module, setModule] = useState<string | undefined>();
|
||||
const [action, setAction] = useState<string | undefined>();
|
||||
const [statusCode, setStatusCode] = useState<number | undefined>();
|
||||
const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetchAuditLogs({
|
||||
user_id: userId || undefined,
|
||||
module,
|
||||
action,
|
||||
status_code: statusCode,
|
||||
start_date: range?.[0]?.format("YYYY-MM-DD"),
|
||||
// 后端按「含当天」处理结束日期,这里直接传所选日期即可
|
||||
end_date: range?.[1]?.format("YYYY-MM-DD"),
|
||||
page,
|
||||
page_size: PAGE_SIZE,
|
||||
});
|
||||
setRows(res.items);
|
||||
// total 取自后端 count 查询的真实总数,而非当前页条数
|
||||
setTotal(res.total);
|
||||
} catch (e) {
|
||||
setError(extractErrorMessage(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [userId, module, action, statusCode, range, page]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAuditOptions()
|
||||
.then((o) => {
|
||||
setModules(o.modules);
|
||||
setActions(o.actions);
|
||||
})
|
||||
.catch(() => {
|
||||
/* 筛选项拉取失败不影响列表本身 */
|
||||
});
|
||||
}, []);
|
||||
|
||||
const hasFilter = !!(userId || module || action || statusCode || range);
|
||||
|
||||
const resetFilters = () => {
|
||||
setUserInput("");
|
||||
setUserId("");
|
||||
setModule(undefined);
|
||||
setAction(undefined);
|
||||
setStatusCode(undefined);
|
||||
setRange(null);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const columns: ColumnsType<AuditLogItem> = [
|
||||
{
|
||||
title: "时间",
|
||||
dataIndex: "created_at",
|
||||
width: 165,
|
||||
render: (v: string) => (
|
||||
<span className="whitespace-nowrap text-gray-600">{dayjs(v).format("YYYY-MM-DD HH:mm:ss")}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作人",
|
||||
dataIndex: "user_id",
|
||||
width: 140,
|
||||
render: (_, r) =>
|
||||
r.user_id ? (
|
||||
<div className="leading-tight">
|
||||
<div className="text-gray-900">{r.display_name || r.user_id}</div>
|
||||
<div className="text-xs text-gray-400">{r.user_id}</div>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-gray-400">未认证</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "模块",
|
||||
dataIndex: "module_label",
|
||||
width: 110,
|
||||
render: (v, r) => <span>{v || r.module}</span>,
|
||||
},
|
||||
{
|
||||
title: "动作",
|
||||
dataIndex: "action_label",
|
||||
width: 100,
|
||||
render: (v, r) => <Tag color="blue">{v || r.action}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "请求",
|
||||
dataIndex: "method",
|
||||
width: 210,
|
||||
render: (_, r) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`rounded px-1.5 py-0.5 text-xs font-mono ${METHOD_CLS[r.method || ""] || "bg-slate-100 text-slate-600"}`}>
|
||||
{r.method}
|
||||
</span>
|
||||
<span className="truncate font-mono text-xs text-gray-500" title={r.url || ""}>
|
||||
{r.url}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "结果",
|
||||
dataIndex: "status_code",
|
||||
width: 80,
|
||||
render: (v: number | null) => <span className={`rounded px-2 py-0.5 text-xs font-mono ${statusCls(v)}`}>{v ?? "-"}</span>,
|
||||
},
|
||||
{
|
||||
title: "来源 IP",
|
||||
dataIndex: "ip_address",
|
||||
width: 130,
|
||||
render: (v: string | null) => <span className="font-mono text-xs text-gray-500">{v || "-"}</span>,
|
||||
},
|
||||
{
|
||||
title: "",
|
||||
key: "op",
|
||||
width: 70,
|
||||
render: (_, r) => (
|
||||
<Button type="link" size="small" onClick={() => setDetail(r)}>
|
||||
详情
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="flex items-center gap-2 text-xl font-semibold text-gray-900">
|
||||
<ScrollText className="h-5 w-5 text-blue-600" />
|
||||
操作审计
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
所有写操作(含被拒绝的请求)自动留痕,共 {total} 条
|
||||
</p>
|
||||
</div>
|
||||
<Button icon={<RefreshCw className="h-4 w-4" />} onClick={() => void load()} loading={loading}>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 筛选区 */}
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
placeholder="操作人账号"
|
||||
prefix={<Search className="h-4 w-4 text-gray-400" />}
|
||||
value={userInput}
|
||||
allowClear
|
||||
style={{ width: 180 }}
|
||||
onChange={(e) => setUserInput(e.target.value)}
|
||||
onPressEnter={() => {
|
||||
setPage(1);
|
||||
setUserId(userInput.trim());
|
||||
}}
|
||||
onBlur={() => {
|
||||
setPage(1);
|
||||
setUserId(userInput.trim());
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
placeholder="模块"
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
value={module}
|
||||
options={modules}
|
||||
onChange={(v) => {
|
||||
setPage(1);
|
||||
setModule(v);
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
placeholder="动作"
|
||||
allowClear
|
||||
style={{ width: 130 }}
|
||||
value={action}
|
||||
options={actions}
|
||||
onChange={(v) => {
|
||||
setPage(1);
|
||||
setAction(v);
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
placeholder="结果"
|
||||
allowClear
|
||||
style={{ width: 130 }}
|
||||
value={statusCode}
|
||||
options={[
|
||||
{ value: 200, label: "成功 (2xx/3xx)" },
|
||||
{ value: 401, label: "未认证 401" },
|
||||
{ value: 403, label: "无权限 403" },
|
||||
{ value: 422, label: "参数错误 422" },
|
||||
{ value: 500, label: "服务异常 500" },
|
||||
]}
|
||||
onChange={(v) => {
|
||||
setPage(1);
|
||||
setStatusCode(v);
|
||||
}}
|
||||
/>
|
||||
<RangePicker
|
||||
value={range}
|
||||
onChange={(v) => {
|
||||
setPage(1);
|
||||
setRange(v as [Dayjs, Dayjs] | null);
|
||||
}}
|
||||
/>
|
||||
{hasFilter && (
|
||||
<Button icon={<X className="h-4 w-4" />} onClick={resetFilters}>
|
||||
清空
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">
|
||||
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Table<AuditLogItem>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={rows}
|
||||
loading={loading && { indicator: <Loader2 className="h-5 w-5 animate-spin text-blue-600" /> }}
|
||||
size="small"
|
||||
scroll={{ x: 1000 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize: PAGE_SIZE,
|
||||
total,
|
||||
showSizeChanger: false,
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange: setPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 详情抽屉:完整 URL / UA / request_id / error_message 都在这里 */}
|
||||
<Drawer
|
||||
title="审计详情"
|
||||
width={560}
|
||||
open={!!detail}
|
||||
onClose={() => setDetail(null)}
|
||||
>
|
||||
{detail && (
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="时间">
|
||||
{dayjs(detail.created_at).format("YYYY-MM-DD HH:mm:ss")}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="操作人">
|
||||
{detail.user_id ? `${detail.display_name || ""} (${detail.user_id})` : "未认证"}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="角色">{detail.role || "-"}</Descriptions.Item>
|
||||
<Descriptions.Item label="模块 / 动作">
|
||||
{detail.module_label || detail.module} / {detail.action_label || detail.action}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="目标">
|
||||
{detail.target_id ? (
|
||||
<>
|
||||
{detail.target_name || detail.target_id}
|
||||
<span className="ml-1 text-xs text-gray-400">({detail.target_type})</span>
|
||||
</>
|
||||
) : (
|
||||
"-"
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="请求">
|
||||
<span className="font-mono text-xs">
|
||||
{detail.method} {detail.url}
|
||||
</span>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="结果">{detail.status_code ?? "-"}</Descriptions.Item>
|
||||
{detail.error_message && (
|
||||
<Descriptions.Item label="错误">
|
||||
<span className="break-all font-mono text-xs text-red-600">{detail.error_message}</span>
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
<Descriptions.Item label="来源 IP">
|
||||
<span className="font-mono text-xs">{detail.ip_address || "-"}</span>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="User-Agent">
|
||||
<span className="break-all text-xs text-gray-500">{detail.user_agent || "-"}</span>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Request ID">
|
||||
{detail.request_id ? (
|
||||
<Tooltip title="可在后端结构化日志中用它定位同一次请求">
|
||||
<span className="break-all font-mono text-xs">{detail.request_id}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
"-"
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
{detail.details && (
|
||||
<Descriptions.Item label="变更详情">
|
||||
<pre className="max-h-60 overflow-auto rounded bg-gray-50 p-2 text-xs">
|
||||
{JSON.stringify(detail.details, null, 2)}
|
||||
</pre>
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
</Descriptions>
|
||||
)}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -13,7 +13,7 @@ import {
|
||||
} from "../../services/printApi";
|
||||
import { useToast } from "../../components/ui/Toast";
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
import { getStatusConfig, lifecycleBadge } from "../../constants/task";
|
||||
import { getStatusConfig, lifecycleBadge, isAdminRole } from "../../constants/task";
|
||||
import { extractErrorMessage } from "../../utils/errorMessage";
|
||||
|
||||
const QR_BASE = "/api/v1/products/qrcode";
|
||||
@ -31,7 +31,7 @@ interface ProductGroup { groupKey: string; products: ProductResponse[]; allInWar
|
||||
export default function AdminProductsPage() {
|
||||
const { toast } = useToast();
|
||||
const { user: authUser } = useAuth();
|
||||
const isAdmin = authUser?.role === "SUPER_ADMIN" || authUser?.role === "SUPERVISOR";
|
||||
const isAdmin = isAdminRole(authUser?.role);
|
||||
const [products, setProducts] = useState<ProductResponse[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
77
frontend/src/services/auditApi.ts
Normal file
77
frontend/src/services/auditApi.ts
Normal file
@ -0,0 +1,77 @@
|
||||
/** 操作审计日志 API */
|
||||
import api from "./api";
|
||||
|
||||
export interface AuditLogItem {
|
||||
id: string;
|
||||
user_id: string | null;
|
||||
display_name: string | null;
|
||||
role: string | null;
|
||||
|
||||
action: string;
|
||||
/** 服务端补的中文标签,前端不再各自维护枚举映射 */
|
||||
action_label: string | null;
|
||||
module: string;
|
||||
module_label: string | null;
|
||||
|
||||
target_type: string | null;
|
||||
target_id: string | null;
|
||||
target_name: string | null;
|
||||
details: Record<string, unknown> | null;
|
||||
|
||||
ip_address: string | null;
|
||||
user_agent: string | null;
|
||||
method: string | null;
|
||||
url: string | null;
|
||||
status_code: number | null;
|
||||
error_message: string | null;
|
||||
|
||||
/** 拿着它可在后端结构化日志中定位同一次请求 */
|
||||
request_id: string | null;
|
||||
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AuditLogListResponse {
|
||||
items: AuditLogItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface AuditOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface AuditOptionsResponse {
|
||||
modules: AuditOption[];
|
||||
actions: AuditOption[];
|
||||
}
|
||||
|
||||
export interface AuditLogQuery {
|
||||
user_id?: string;
|
||||
module?: string;
|
||||
action?: string;
|
||||
target_id?: string;
|
||||
request_id?: string;
|
||||
status_code?: number;
|
||||
/** YYYY-MM-DD */
|
||||
start_date?: string;
|
||||
/** YYYY-MM-DD(含当天) */
|
||||
end_date?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
/** 分页查询审计日志(按时间倒序) */
|
||||
export async function fetchAuditLogs(q: AuditLogQuery = {}): Promise<AuditLogListResponse> {
|
||||
const params = Object.fromEntries(
|
||||
Object.entries(q).filter(([, v]) => v !== undefined && v !== null && v !== "")
|
||||
);
|
||||
const { data } = await api.get<AuditLogListResponse>("/audit/logs", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 获取模块/动作筛选项 */
|
||||
export async function fetchAuditOptions(): Promise<AuditOptionsResponse> {
|
||||
const { data } = await api.get<AuditOptionsResponse>("/audit/options");
|
||||
return data;
|
||||
}
|
||||
Reference in New Issue
Block a user