From 4250d0e266a758463a6f1ac72fa34d3c822e96d3 Mon Sep 17 00:00:00 2001 From: xiaojunnuo Date: Fri, 10 Jul 2026 19:24:42 +0800 Subject: [PATCH] chore: audit log first --- .trae/documents/audit-log-feature.md | 437 ++++++++++++++++++ .../lib-server/src/basic/base-controller.ts | 14 + .../lib-server/src/basic/crud-controller.ts | 24 +- .../src/locales/langs/en-US/certd.ts | 2 + .../src/locales/langs/en-US/certd/audit.ts | 4 + .../src/locales/langs/zh-CN/certd.ts | 2 + .../src/locales/langs/zh-CN/certd/audit.ts | 4 + .../src/router/source/modules/certd.ts | 11 + .../src/router/source/modules/sys.ts | 12 + .../certd-client/src/views/certd/audit/api.ts | 28 ++ .../src/views/certd/audit/crud.tsx | 102 ++++ .../src/views/certd/audit/index.vue | 24 + .../certd-client/src/views/sys/audit/api.ts | 35 ++ .../certd-client/src/views/sys/audit/crud.tsx | 124 +++++ .../src/views/sys/audit/index.vue | 24 + .../controller/sys/audit/audit-controller.ts | 39 ++ .../sys/authority/permission-controller.ts | 25 +- .../sys/authority/role-controller.ts | 25 +- .../sys/authority/user-controller.ts | 25 +- .../sys/enterprise/project-controller.ts | 32 +- .../settings/sys-safe-settings-controller.ts | 6 + .../sys/settings/sys-settings-controller.ts | 6 + .../controller/user/audit/audit-controller.ts | 32 ++ .../user/monitor/site-info-controller.ts | 25 +- .../user/open/open-key-controller.ts | 20 +- .../user/pipeline/access-controller.ts | 26 +- .../user/pipeline/notification-controller.ts | 26 +- .../user/pipeline/pipeline-controller.ts | 102 ++-- .../src/modules/auto/auto-cron.ts | 17 +- .../sys/enterprise/entity/audit-log.ts | 2 +- .../sys/enterprise/service/audit-constants.ts | 87 ++++ .../sys/enterprise/service/audit-service.ts | 129 ++++++ .../plugins/plugin-deploy-to-vod.ts | 2 +- 33 files changed, 1396 insertions(+), 77 deletions(-) create mode 100644 .trae/documents/audit-log-feature.md create mode 100644 packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts create mode 100644 packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts create mode 100644 packages/ui/certd-client/src/views/certd/audit/api.ts create mode 100644 packages/ui/certd-client/src/views/certd/audit/crud.tsx create mode 100644 packages/ui/certd-client/src/views/certd/audit/index.vue create mode 100644 packages/ui/certd-client/src/views/sys/audit/api.ts create mode 100644 packages/ui/certd-client/src/views/sys/audit/crud.tsx create mode 100644 packages/ui/certd-client/src/views/sys/audit/index.vue create mode 100644 packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts create mode 100644 packages/ui/certd-server/src/controller/user/audit/audit-controller.ts create mode 100644 packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts create mode 100644 packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts diff --git a/.trae/documents/audit-log-feature.md b/.trae/documents/audit-log-feature.md new file mode 100644 index 000000000..392259b6d --- /dev/null +++ b/.trae/documents/audit-log-feature.md @@ -0,0 +1,437 @@ +# 审计日志功能实施计划(MVP 版本) + +## 一、摘要 + +为 Certd 系统增加基础审计日志功能,记录用户关键操作(流水线增删改/执行、授权管理、站点监控、通知设置、API密钥、用户管理、角色权限、项目管理、系统设置等),支持管理员和用户分别在管理后台和用户端查看操作日志。 + +**关键发现**:`cd_audit_log` 表已通过数据库迁移 v10038 创建,`AuditLogEntity` 实体已定义,字段完整可直接使用,写入和查询功能完全未实现。 + +> **MVP 范围**:仅实现简要记录(谁在何时对什么做了什么),流水线差异对比(diffContent)后续版本再补充。 + +## 二、当前状态分析 + +### 已存在的基础设施 + +| 组件 | 路径 | 状态 | +|------|------|------| +| 审计日志表 | `cd_audit_log`(迁移 v10038__admin_mode.sql) | ✅ 已创建 | +| 审计日志实体 | `packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts` | ✅ 已定义 | +| BaseService 钩子 | `BaseService.modifyAfter(data)` | ✅ 已预留(空实现) | + +### 审计日志表字段 + +| 字段 | 类型 | 说明 | +|------|------|------| +| `id` | number (PK) | 主键 | +| `userId` | number | 操作人ID | +| `userName` | string(128) | 操作人用户名 | +| `projectId` | number | 项目ID(企业模式) | +| `projectName` | string(512) | 项目名称 | +| `type` | string(128) | 操作模块类型 | +| `action` | string(128) | 操作动作 | +| `content` | text | 操作内容摘要描述 | +| `ipAddress` | string(128) | 操作人IP | +| `createTime` | Date | 创建时间 | +| `updateTime` | Date | 修改时间 | + +**无新增字段**,直接使用现有表结构。 + +### `ctx.user` 可用字段 + +JWT 登录路径:`{ id, username, roles }` +OpenKey 认证路径:`{ id, roles, projectId }`(**无 username**) + +> **注意**:审计时若需 username 而 ctx.user.username 不存在,需要通过 userId 查询 UserEntity 获取。 + +## 三、需求范围 + +### 审计类型(type)与动作(action) + +| 序号 | 模块 | type | action | 说明 | +|------|------|------|--------|------| +| 1 | 流水线 | `pipeline` | `add`/`update`/`delete`/`execute`/`cancel`/`batchDelete`/`batchUpdate` | 记录流水线的增删改、手动执行、取消、批量操作 | +| 2 | 授权管理 | `access` | `add`/`update`/`delete` | 记录云厂商授权凭据的增删改 | +| 3 | 站点监控 | `monitor` | `add`/`update`/`delete`/`batchDelete` | 记录站点证书监控的增删改 | +| 4 | 通知设置 | `notification` | `add`/`update`/`delete` | 记录通知配置的增删改 | +| 5 | API密钥 | `openKey` | `add`/`update`/`delete` | 记录开放接口密钥的增删改 | +| 6 | 用户管理 | `user` | `add`/`update`/`delete` | 记录系统管理员对用户的增删改 | +| 7 | 角色管理 | `role` | `add`/`update`/`delete` | 记录角色的增删改 | +| 8 | 权限管理 | `permission` | `add`/`update`/`delete` | 记录权限的增删改 | +| 9 | 项目管理 | `project` | `add`/`update`/`delete`/`disable` | 记录项目的增删改/启停 | +| 10 | 系统设置 | `settings` | `update` | 记录系统配置的修改 | + +### 关键策略 + +- **存储**:仅数据库(使用已有 `cd_audit_log` 表,无新增字段/迁移) +- **粒度**:简要记录(谁对什么做了什么),无差异对比 +- **保留策略**:按 90 天自动清理(硬编码,不提供配置界面,后续迭代再补配置) +- **前端**:管理后台(`/sys/audit` 查看全部) + 用户端(`/certd/audit` 仅查看自己的) + +## 四、实施方案 + +### 4.1 后端:新增文件 + +#### 4.1.1 AuditService + +**文件**:`packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts` + +```typescript +@Provide() +export class AuditService { + @Inject() + dataSourceManager: TypeORMDataSourceManager; + + getRepository(): Repository { + return this.dataSourceManager.getDataSource('default').getRepository(AuditLogEntity); + } + + // 写入审计日志 + async log(params: { + userId: number; + type: string; + action: string; + content: string; + username?: string; + projectId?: number; + projectName?: string; + ipAddress?: string; + }): Promise; + + // 分页查询 + async page(pageReq: PageReq): Promise; + + // 删除指定天数之前的日志 + async cleanExpired(retentionDays: number): Promise; +} +``` + +**关键实现细节**: +- `log()` 中若 `username` 为空,通过 `userId` 查 `UserEntity` 获取,查询失败也写入(username留空) +- `log()` 用 try-catch 包裹,写入失败仅 log error,不影响主业务 +- `page()` 不做额外过滤,由 Controller 层控制 userId 过滤逻辑 +- `cleanExpired()` 直接 DELETE WHERE `create_time < now - retentionDays` + +#### 4.1.2 审计日志 Controller(管理后台) + +**文件**:`packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts` + +路由前缀:`/api/sys/audit` + +```typescript +@Provide() +@ApiTags(['audit']) +@Controller('/api/sys/audit') +export class SysAuditLogController { + @Inject() + auditService: AuditService; + + // POST /page - 分页查询(不过滤 userId,支持 type/action/userId/时间范围 筛选) + // POST /delete - 删除单条日志 + // POST /clean - 手动清理过期日志 +} +``` + +权限:`sys:settings:view`(查看)/ `sys:settings:edit`(删除/清理) + +#### 4.1.3 审计日志 Controller(用户端) + +**文件**:`packages/ui/certd-server/src/controller/user/audit/audit-controller.ts` + +路由前缀:`/api/pi/audit` + +```typescript +@Provide() +@ApiTags(['audit']) +@Controller('/api/pi/audit') +export class AuditLogController extends BaseController { + @Inject() + auditService: AuditService; + + // POST /page - 分页查询(自动过滤当前 userId) +} +``` + +权限:`authOnly` + +#### 4.1.4 审计日志清理 Cron 任务 + +在 `AuditService` 中注册 cron:每天凌晨 3:00 执行,保留 90 天。 + +> 清理注册方式参考 `PipelineService` 中的 `this.cron.register()` 模式。 + +### 4.2 后端:修改现有文件 + +在以下 Controller 中注入 `AuditService` 并在关键方法中调用 `this.auditService.log(...)`。 + +#### 4.2.1 PipelineController(流水线) + +**文件**:`packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `save` (新增, bean.id ≤ 0) | `add` | `创建了流水线「{title}」(ID:{id})` | +| `save` (修改, bean.id > 0) | `update` | `修改了流水线「{title}」(ID:{id})` | +| `delete` | `delete` | `删除了流水线(ID:{id})` | +| `trigger` | `execute` | `手动执行了流水线「{title}」(ID:{id})` | +| `cancel` | `cancel` | `取消了流水线执行(historyId:{historyId})` | +| `batchDelete` | `batchDelete` | `批量删除了{count}条流水线` | +| `batchUpdateGroup` | `batchUpdate` | `批量修改了{count}条流水线分组` | +| `batchUpdateTrigger` | `batchUpdate` | `批量修改了{count}条流水线触发器` | +| `batchUpdateNotification` | `batchUpdate` | `批量修改了{count}条流水线通知` | +| `batchUpdateCertApplyOptions` | `batchUpdate` | `批量修改了{count}条流水线证书申请配置` | +| `batchRerun` | `execute` | `批量重新执行了{count}条流水线` | +| `batchTransfer` | `batchUpdate` | `批量迁移了{count}条流水线` | +| `refreshWebhookKey` | `update` | `刷新了流水线(ID:{id})的Webhook密钥` | + +**接入方式**:在方法末尾、返回 `this.ok(...)` 之前调用 `this.auditService.log(...)`。对 `save` 方法,根据 `bean.id > 0` 区分 add/update。对 `delete`/`trigger`/`cancel` 等方法,由于方法签名限制,content 中尽量使用已有变量,查不到标题就用 ID 描述。 + +#### 4.2.2 AccessController(授权管理) + +**文件**:`packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了授权「{name}」(ID:{id}, 类型:{type})` | +| `update` | `update` | `修改了授权「{name}」(ID:{id})` | +| `delete` | `delete` | `删除了授权(ID:{id})` | + +#### 4.2.3 SiteInfoController(站点监控) + +**文件**:`packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了站点监控「{name}」(ID:{id}, 域名:{domain})` | +| `update` | `update` | `修改了站点监控「{name}」(ID:{id})` | +| `delete` | `delete` | `删除了站点监控(ID:{id})` | +| `batchDelete` | `batchDelete` | `批量删除了{count}条站点监控` | + +#### 4.2.4 NotificationController(通知设置) + +**文件**:`packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了通知配置「{name}」(ID:{id}, 类型:{type})` | +| `update` | `update` | `修改了通知配置「{name}」(ID:{id})` | +| `delete` | `delete` | `删除了通知配置(ID:{id})` | + +#### 4.2.5 OpenKeyController(API密钥) + +**文件**:`packages/ui/certd-server/src/controller/user/open/open-key-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了API密钥(ID:{id}, scope:{scope})` | +| `update` | `update` | `修改了API密钥(ID:{id})` | +| `delete` | `delete` | `删除了API密钥(ID:{id})` | + +#### 4.2.6 UserController(用户管理 - 管理后台) + +**文件**:`packages/ui/certd-server/src/controller/sys/authority/user-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了用户「{username}」(ID:{id})` | +| `update` | `update` | `修改了用户「{username}」(ID:{id})` | +| `delete` | `delete` | `删除了用户(ID:{id})` | + +#### 4.2.7 RoleController(角色管理 - 管理后台) + +**文件**:`packages/ui/certd-server/src/controller/sys/authority/role-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了角色「{name}」(ID:{id})` | +| `update` | `update` | `修改了角色「{name}」(ID:{id})` | +| `delete` | `delete` | `删除了角色(ID:{id})` | + +#### 4.2.8 PermissionController(权限管理 - 管理后台) + +**文件**:`packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了权限「{name}」(ID:{id})` | +| `update` | `update` | `修改了权限「{name}」(ID:{id})` | +| `delete` | `delete` | `删除了权限(ID:{id})` | + +#### 4.2.9 ProjectController(项目管理 - 管理后台) + +**文件**:`packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts` + +| 方法 | 审计 action | content 模板 | +|------|------------|-------------| +| `add` | `add` | `新增了项目「{name}」(ID:{id})` | +| `update` | `update` | `修改了项目「{name}」(ID:{id})` | +| `delete` | `delete` | `删除了项目(ID:{id})` | +| `setDisabled` | `disable` | `{启用\|禁用了}项目「{name}」(ID:{id})` | + +#### 4.2.10 系统设置 Controller + +- **SysSettingsController**:`save` → `type=settings, action=update, content=修改了系统设置` +- **SysSafeSettingsController**:`save` → `type=settings, action=update, content=修改了安全设置` + +### 4.3 后端:数据库迁移 + +**无需新增迁移**。使用已有 `cd_audit_log` 表,无新增字段。 + +### 4.4 后端:通用辅助 + +#### 4.4.1 审计日志提取 helper + +创建一个轻量的提取函数,减少 Controller 中的重复代码: + +```typescript +// 在 controller 中各方法调用示例 +async add(@Body(ALL) bean: XxxEntity) { + const result = await this.service.add(bean); + await this.auditService.log({ + userId: this.getUserId(), + username: this.ctx.user?.username, + type: 'xxx', + action: 'add', + content: `新增了xxx「${bean.name}」(ID:${result.id})`, + ipAddress: this.ctx.ip, + }); + return this.ok(result); +} +``` + +### 4.5 前端:新增文件 + +#### 4.5.1 用户端审计日志页 + +``` +packages/ui/certd-client/src/views/certd/audit/ +├── api.ts +├── crud.tsx +└── index.vue +``` + +- **路由**:`/certd/audit` +- **菜单位置**:放在「设置」子菜单中 +- **权限**:`authOnly` +- **功能**:展示当前用户的操作日志,支持按 type/action/时间范围 筛选 +- **列**:操作时间、操作类型(type)、动作(action)、内容(content)、IP地址 + +#### 4.5.2 管理后台审计日志页 + +``` +packages/ui/certd-client/src/views/sys/audit/ +├── api.ts +├── crud.tsx +└── index.vue +``` + +- **路由**:`/sys/audit` +- **菜单位置**:放在「系统管理」菜单中 +- **权限**:`sys:settings:view` +- **功能**:展示所有用户的操作日志,支持按 userId/type/action/时间范围 筛选 +- **列**:操作时间、操作人(userName)、操作类型(type)、动作(action)、内容(content)、IP地址 +- **额外操作**:删除单条、手动清理过期日志按钮(需 `sys:settings:edit` 权限) + +#### 4.5.3 路由配置 + +**修改** `packages/ui/certd-client/src/router/source/modules/certd.ts`,在 settings children 中添加: + +```typescript +{ + title: "certd.auditLog", + name: "AuditLog", + path: "/certd/audit", + component: "/certd/audit/index.vue", + meta: { + icon: "ion:document-text-outline", + auth: true, + keepAlive: true, + }, +} +``` + +**修改** `packages/ui/certd-client/src/router/source/modules/sys.ts`,在 SysRoot children 中添加: + +```typescript +{ + title: "certd.sysResources.auditLog", + name: "SysAuditLog", + path: "/sys/audit", + component: "/sys/audit/index.vue", + meta: { + icon: "ion:document-text-outline", + permission: "sys:settings:view", + keepAlive: true, + auth: true, + }, +} +``` + +#### 4.5.4 国际化 + +在 `packages/ui/certd-client/src/locales/` 的语言包中添加: + +```json +{ + "certd.auditLog": "操作日志", + "certd.sysResources.auditLog": "操作日志", + "audit.type": "操作类型", + "audit.action": "操作动作", + "audit.content": "内容", + "audit.ipAddress": "IP地址", + "audit.userName": "操作人", + "audit.createTime": "操作时间", + "audit.cleanExpired": "清理过期日志" +} +``` + +## 五、实现顺序 + +1. **Phase 1:AuditService** + - 创建 `AuditService`(`log`、`page`、`cleanExpired` 方法) + - 注册审计日志清理 cron(默认保留 90 天) + +2. **Phase 2:Controller 接入** + - `SysAuditLogController` + `AuditLogController`(日志查询接口) + - 逐个 Controller 接入审计日志: + - PipelineController + - AccessController + - SiteInfoController + - NotificationController + - OpenKeyController + - 管理后台 User/Role/Permission/Project/Settings Controllers + +3. **Phase 3:前端** + - 用户端 `/certd/audit` 页面 + - 管理后台 `/sys/audit` 页面 + - 路由 + 国际化 + +4. **Phase 4:测试** + - AuditService 单元测试 + - 验证各模块操作是否正确写入日志 + +## 六、验证步骤 + +### 后端 + +1. 运行单元测试:`cd packages/ui/certd-server && npm run test:unit` +2. 手动验证: + - 创建/修改/删除流水线 → 检查 `cd_audit_log` 表 + - 手动触发流水线 → 检查 execute 记录 + - 增删改授权/监控/通知/密钥 → 检查对应记录 + - 管理后台用户/角色/权限/项目/设置操作 → 检查记录 + +### 前端 + +1. 用户端 `/certd/audit` → 仅显示当前用户日志 +2. 管理后台 `/sys/audit` → 显示全部日志,支持筛选和清理 +3. 运行 ESLint/Prettier + +## 七、注意事项 + +1. **不记录敏感数据**:content 中不记录密码、密钥等敏感信息 +2. **不记录查询操作**:仅记录变更操作(add/update/delete/execute),不记录 page/list/info +3. **异常不影响主流程**:审计日志写入失败用 try-catch 包裹,仅 log error +4. **username 兼容性**:JWT 路径下 `ctx.user.username` 有值;OpenKey 路径下需从 UserService 查询 +5. **事务隔离**:审计日志独立写入,避免主业务事务回滚时丢失 +6. **批量操作**:批量操作一条审计记录记录概要信息,不为每个对象单独记录 +7. **后续迭代预留**:diffContent 字段和系统设置中的审计配置项在后续版本补充,本次不做迁移 diff --git a/packages/libs/lib-server/src/basic/base-controller.ts b/packages/libs/lib-server/src/basic/base-controller.ts index 5149721ef..795de3dd1 100644 --- a/packages/libs/lib-server/src/basic/base-controller.ts +++ b/packages/libs/lib-server/src/basic/base-controller.ts @@ -127,4 +127,18 @@ export abstract class BaseController { } return { projectId, userId }; } + + async auditLog(bean: { type: string; action: string; content: string; projectId?: number; projectName?: string }) { + const auditService: any = await this.applicationContext.getAsync("auditService"); + await auditService.log({ + userId: this.getUserId(), + type: bean.type, + action: bean.action, + content: bean.content, + username: this.ctx.user?.username, + projectId: bean.projectId, + projectName: bean.projectName, + ipAddress: this.ctx.ip, + }); + } } diff --git a/packages/libs/lib-server/src/basic/crud-controller.ts b/packages/libs/lib-server/src/basic/crud-controller.ts index 11f9f8291..312cfbfda 100644 --- a/packages/libs/lib-server/src/basic/crud-controller.ts +++ b/packages/libs/lib-server/src/basic/crud-controller.ts @@ -1,11 +1,11 @@ -import { ALL, Body, Post, Query } from '@midwayjs/core'; -import { BaseController } from './base-controller.js'; +import { ALL, Body, Post, Query } from "@midwayjs/core"; +import { BaseController } from "./base-controller.js"; export abstract class CrudController extends BaseController { // eslint-disable-next-line @typescript-eslint/no-unused-vars abstract getService(); - @Post('/page') + @Post("/page") async page(@Body(ALL) body: any) { const pageRet = await this.getService().page({ query: body.query ?? {}, @@ -16,7 +16,7 @@ export abstract class CrudController extends BaseController { return this.ok(pageRet); } - @Post('/list') + @Post("/list") async list(@Body(ALL) body: any) { const listRet = await this.getService().list({ query: body.query ?? {}, @@ -25,33 +25,33 @@ export abstract class CrudController extends BaseController { return this.ok(listRet); } - @Post('/add') + @Post("/add") async add(@Body(ALL) bean: any) { delete bean.id; const id = await this.getService().add(bean); return this.ok(id); } - @Post('/info') - async info(@Query('id') id: number) { + @Post("/info") + async info(@Query("id") id: number) { const bean = await this.getService().info(id); return this.ok(bean); } - @Post('/update') + @Post("/update") async update(@Body(ALL) bean: any) { await this.getService().update(bean); return this.ok(null); } - @Post('/delete') - async delete(@Query('id') id: number) { + @Post("/delete") + async delete(@Query("id") id: number) { await this.getService().delete([id]); return this.ok(null); } - @Post('/deleteByIds') - async deleteByIds(@Body('ids') ids: number[]) { + @Post("/deleteByIds") + async deleteByIds(@Body("ids") ids: number[]) { await this.getService().delete(ids); return this.ok(null); } diff --git a/packages/ui/certd-client/src/locales/langs/en-US/certd.ts b/packages/ui/certd-client/src/locales/langs/en-US/certd.ts index e5a138949..14b260b56 100644 --- a/packages/ui/certd-client/src/locales/langs/en-US/certd.ts +++ b/packages/ui/certd-client/src/locales/langs/en-US/certd.ts @@ -19,6 +19,7 @@ import sysauthority from "./certd/sys-authority"; import syscname from "./certd/sys-cname"; import tutorial from "./certd/tutorial"; import cron from "./certd/cron"; +import audit from "./certd/audit"; // Note: @ is reserved in locale messages; use {'@'} when needed. export default { @@ -43,4 +44,5 @@ export default { ...syscname, ...tutorial, ...cron, + ...audit, }; diff --git a/packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts b/packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts new file mode 100644 index 000000000..506a56977 --- /dev/null +++ b/packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts @@ -0,0 +1,4 @@ +export default { + "certd.auditLog": "Audit Log", + "certd.sysResources.auditLog": "Audit Log", +}; diff --git a/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts b/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts index e5a138949..14b260b56 100644 --- a/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts +++ b/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts @@ -19,6 +19,7 @@ import sysauthority from "./certd/sys-authority"; import syscname from "./certd/sys-cname"; import tutorial from "./certd/tutorial"; import cron from "./certd/cron"; +import audit from "./certd/audit"; // Note: @ is reserved in locale messages; use {'@'} when needed. export default { @@ -43,4 +44,5 @@ export default { ...syscname, ...tutorial, ...cron, + ...audit, }; diff --git a/packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts b/packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts new file mode 100644 index 000000000..b6d3f9b81 --- /dev/null +++ b/packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts @@ -0,0 +1,4 @@ +export default { + "certd.auditLog": "操作日志", + "certd.sysResources.auditLog": "操作日志", +}; diff --git a/packages/ui/certd-client/src/router/source/modules/certd.ts b/packages/ui/certd-client/src/router/source/modules/certd.ts index 973bbe4cf..4c5e0f0a8 100644 --- a/packages/ui/certd-client/src/router/source/modules/certd.ts +++ b/packages/ui/certd-client/src/router/source/modules/certd.ts @@ -287,6 +287,17 @@ export const certdResources = [ isMenu: true, }, }, + { + title: "certd.auditLog", + name: "AuditLog", + path: "/certd/audit", + component: "/certd/audit/index.vue", + meta: { + icon: "ion:document-text-outline", + auth: true, + keepAlive: true, + }, + }, { title: "certd.userSecurity", name: "UserSecurity", diff --git a/packages/ui/certd-client/src/router/source/modules/sys.ts b/packages/ui/certd-client/src/router/source/modules/sys.ts index c042885ba..6178cd24c 100644 --- a/packages/ui/certd-client/src/router/source/modules/sys.ts +++ b/packages/ui/certd-client/src/router/source/modules/sys.ts @@ -410,6 +410,18 @@ export const sysResources = [ }, ], }, + { + title: "certd.sysResources.auditLog", + name: "SysAuditLog", + path: "/sys/audit", + component: "/sys/audit/index.vue", + meta: { + icon: "ion:document-text-outline", + permission: "sys:settings:view", + keepAlive: true, + auth: true, + }, + }, { title: "certd.sysResources.netTest", name: "NetTest", diff --git a/packages/ui/certd-client/src/views/certd/audit/api.ts b/packages/ui/certd-client/src/views/certd/audit/api.ts new file mode 100644 index 000000000..fa9eb1ca6 --- /dev/null +++ b/packages/ui/certd-client/src/views/certd/audit/api.ts @@ -0,0 +1,28 @@ +import { request } from "/src/api/service"; + +const apiPrefix = "/pi/audit"; + +export function createAuditApi() { + return { + async GetList(query: any) { + return await request({ + url: apiPrefix + "/page", + method: "post", + data: query, + }); + }, + async DelObj(id: number) { + return await request({ + url: apiPrefix + "/delete", + method: "post", + params: { id }, + }); + }, + async GetDict() { + return await request({ + url: apiPrefix + "/dict", + method: "post", + }); + }, + }; +} diff --git a/packages/ui/certd-client/src/views/certd/audit/crud.tsx b/packages/ui/certd-client/src/views/certd/audit/crud.tsx new file mode 100644 index 000000000..e97b1e599 --- /dev/null +++ b/packages/ui/certd-client/src/views/certd/audit/crud.tsx @@ -0,0 +1,102 @@ +import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud"; + +const typeDict = dict({ + url: "/pi/audit/dict", + getData: async () => { + const { createAuditApi } = await import("./api"); + const api = createAuditApi(); + const res = await api.GetDict(); + return res.types || []; + }, +}); + +const actionDict = dict({ + url: "/pi/audit/dict", + getData: async () => { + const { createAuditApi } = await import("./api"); + const api = createAuditApi(); + const res = await api.GetDict(); + return res.actions || []; + }, +}); + +export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet { + const api = context.api; + + const pageRequest = async (query: UserPageQuery): Promise => { + return await api.GetList(query); + }; + const delRequest = async (req: DelReq) => { + return await api.DelObj(req.row.id); + }; + + return { + crudOptions: { + request: { pageRequest, delRequest }, + actionbar: { + buttons: { + add: { show: false }, + }, + }, + rowHandle: { + width: 120, + fixed: "right", + buttons: { + view: { show: false }, + edit: { show: false }, + remove: { show: true }, + }, + }, + columns: { + id: { + title: "ID", + type: "number", + column: { width: 80 }, + form: { show: false }, + }, + createTime: { + title: "操作时间", + type: "datetime", + search: { + show: true, + component: { + name: "a-range-picker", + vModel: ["createTime_start", "createTime_end"], + }, + }, + column: { width: 170, sorter: true }, + form: { show: false }, + }, + type: { + title: "操作类型", + type: "dict-select", + dict: typeDict, + search: { show: true }, + column: { width: 120 }, + form: { show: false }, + }, + action: { + title: "操作动作", + type: "dict-select", + dict: actionDict, + search: { show: true }, + column: { width: 100 }, + form: { show: false }, + }, + content: { + title: "内容", + type: "text", + search: { show: true }, + column: { minWidth: 300 }, + form: { show: false }, + }, + ipAddress: { + title: "IP地址", + type: "text", + column: { width: 140 }, + form: { show: false }, + }, + }, + }, + }; +} diff --git a/packages/ui/certd-client/src/views/certd/audit/index.vue b/packages/ui/certd-client/src/views/certd/audit/index.vue new file mode 100644 index 000000000..e77faa90d --- /dev/null +++ b/packages/ui/certd-client/src/views/certd/audit/index.vue @@ -0,0 +1,24 @@ + + + diff --git a/packages/ui/certd-client/src/views/sys/audit/api.ts b/packages/ui/certd-client/src/views/sys/audit/api.ts new file mode 100644 index 000000000..befb6053f --- /dev/null +++ b/packages/ui/certd-client/src/views/sys/audit/api.ts @@ -0,0 +1,35 @@ +import { request } from "/src/api/service"; + +const apiPrefix = "/sys/audit"; + +export function createSysAuditApi() { + return { + async GetList(query: any) { + return await request({ + url: apiPrefix + "/page", + method: "post", + data: query, + }); + }, + async DelObj(id: number) { + return await request({ + url: apiPrefix + "/delete", + method: "post", + params: { id }, + }); + }, + async Clean(retentionDays: number) { + return await request({ + url: apiPrefix + "/clean", + method: "post", + data: { retentionDays }, + }); + }, + async GetDict() { + return await request({ + url: apiPrefix + "/dict", + method: "post", + }); + }, + }; +} diff --git a/packages/ui/certd-client/src/views/sys/audit/crud.tsx b/packages/ui/certd-client/src/views/sys/audit/crud.tsx new file mode 100644 index 000000000..cb5db23e3 --- /dev/null +++ b/packages/ui/certd-client/src/views/sys/audit/crud.tsx @@ -0,0 +1,124 @@ +import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud"; + +const typeDict = dict({ + url: "/sys/audit/dict", + getData: async () => { + const { createSysAuditApi } = await import("./api"); + const api = createSysAuditApi(); + const res = await api.GetDict(); + return res.types || []; + }, +}); + +const actionDict = dict({ + url: "/sys/audit/dict", + getData: async () => { + const { createSysAuditApi } = await import("./api"); + const api = createSysAuditApi(); + const res = await api.GetDict(); + return res.actions || []; + }, +}); + +export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet { + const api = context.api; + + const pageRequest = async (query: UserPageQuery): Promise => { + return await api.GetList(query); + }; + const delRequest = async (req: DelReq) => { + return await api.DelObj(req.row.id); + }; + + const cleanExpired = async () => { + await api.Clean(90); + crudExpose.doRefresh(); + }; + + return { + crudOptions: { + request: { pageRequest, delRequest }, + actionbar: { + buttons: { + add: { show: false }, + clean: { + text: "清理过期日志(90天)", + type: "default", + click: cleanExpired, + }, + }, + }, + rowHandle: { + width: 120, + fixed: "right", + buttons: { + view: { show: false }, + edit: { show: false }, + remove: { show: true }, + }, + }, + search: { + initialForm: { + sort: { prop: "id", asc: false }, + }, + }, + columns: { + id: { + title: "ID", + type: "number", + column: { width: 80 }, + form: { show: false }, + }, + createTime: { + title: "操作时间", + type: "datetime", + search: { + show: true, + component: { + name: "a-range-picker", + vModel: ["createTime_start", "createTime_end"], + }, + }, + column: { width: 170, sorter: true }, + form: { show: false }, + }, + userName: { + title: "操作人", + type: "text", + search: { show: true }, + column: { width: 120 }, + form: { show: false }, + }, + type: { + title: "操作类型", + type: "dict-select", + dict: typeDict, + search: { show: true }, + column: { width: 120 }, + form: { show: false }, + }, + action: { + title: "操作动作", + type: "dict-select", + dict: actionDict, + search: { show: true }, + column: { width: 100 }, + form: { show: false }, + }, + content: { + title: "内容", + type: "text", + search: { show: true }, + column: { minWidth: 300 }, + form: { show: false }, + }, + ipAddress: { + title: "IP地址", + type: "text", + column: { width: 140 }, + form: { show: false }, + }, + }, + }, + }; +} diff --git a/packages/ui/certd-client/src/views/sys/audit/index.vue b/packages/ui/certd-client/src/views/sys/audit/index.vue new file mode 100644 index 000000000..5e726e449 --- /dev/null +++ b/packages/ui/certd-client/src/views/sys/audit/index.vue @@ -0,0 +1,24 @@ + + + diff --git a/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts b/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts new file mode 100644 index 000000000..514be0a56 --- /dev/null +++ b/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts @@ -0,0 +1,39 @@ +import { BaseController, Constants } from "@certd/lib-server"; +import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core"; +import { ApiTags } from "@midwayjs/swagger"; +import { AuditService } from "../../../modules/sys/enterprise/service/audit-service.js"; +import { buildAuditTypeDict, buildAuditActionDict } from "../../../modules/sys/enterprise/service/audit-constants.js"; + +@Provide() +@ApiTags(["audit"]) +@Controller("/api/sys/audit") +export class SysAuditLogController extends BaseController { + @Inject() + auditService: AuditService; + + @Post("/page", { description: Constants.per.authOnly, summary: "分页查询审计日志" }) + async page(@Body(ALL) body: any) { + const pageRet = await this.auditService.page(body); + return this.ok(pageRet); + } + + @Post("/delete", { description: Constants.per.authOnly }) + async delete(@Query("id") id: number) { + await this.auditService.delete(id); + return this.ok({}); + } + + @Post("/clean", { description: Constants.per.authOnly }) + async clean(@Body("retentionDays") retentionDays: number) { + const count = await this.auditService.cleanExpired(retentionDays || 90); + return this.ok({ deletedCount: count }); + } + + @Post("/dict", { description: Constants.per.authOnly, summary: "获取审计类型和动作字典" }) + async getDict() { + return this.ok({ + types: buildAuditTypeDict(), + actions: buildAuditActionDict(), + }); + } +} diff --git a/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts b/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts index d0277a198..ef016264c 100644 --- a/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts @@ -1,6 +1,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core"; import { CrudController } from "@certd/lib-server"; import { PermissionService } from "../../../modules/sys/authority/service/permission-service.js"; +import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; /** * 权限资源 @@ -28,7 +29,13 @@ export class PermissionController extends CrudController { @Body(ALL) bean ) { - return await super.add(bean); + const res = await super.add(bean); + await this.auditLog({ + type: AuditType.permission, + action: AuditAction.add, + content: `新增了权限「${bean.name}」(ID:${res.data})`, + }); + return res; } @Post("/update", { description: "sys:auth:per:edit" }) @@ -36,14 +43,26 @@ export class PermissionController extends CrudController { @Body(ALL) bean ) { - return await super.update(bean); + const res = await super.update(bean); + await this.auditLog({ + type: AuditType.permission, + action: AuditAction.update, + content: `修改了权限「${bean.name}」(ID:${bean.id})`, + }); + return res; } @Post("/delete", { description: "sys:auth:per:remove" }) async delete( @Query("id") id: number ) { - return await super.delete(id); + const res = await super.delete(id); + await this.auditLog({ + type: AuditType.permission, + action: AuditAction.delete, + content: `删除了权限(ID:${id})`, + }); + return res; } @Post("/tree", { description: "sys:auth:per:view" }) diff --git a/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts b/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts index 03df65471..072ff9816 100644 --- a/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts @@ -1,6 +1,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core"; import { CrudController } from "@certd/lib-server"; import { RoleService } from "../../../modules/sys/authority/service/role-service.js"; +import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; /** * 系统用户 @@ -34,7 +35,13 @@ export class RoleController extends CrudController { @Body(ALL) bean ) { - return await super.add(bean); + const res = await super.add(bean); + await this.auditLog({ + type: AuditType.role, + action: AuditAction.add, + content: `新增了角色「${bean.name}」(ID:${res.data})`, + }); + return res; } @Post("/update", { description: "sys:auth:role:edit" }) @@ -42,7 +49,13 @@ export class RoleController extends CrudController { @Body(ALL) bean ) { - return await super.update(bean); + const res = await super.update(bean); + await this.auditLog({ + type: AuditType.role, + action: AuditAction.update, + content: `修改了角色「${bean.name}」(ID:${bean.id})`, + }); + return res; } @Post("/delete", { description: "sys:auth:role:remove" }) async delete( @@ -52,7 +65,13 @@ export class RoleController extends CrudController { if (id === 1) { throw new Error("不能删除默认的管理员角色"); } - return await super.delete(id); + const res = await super.delete(id); + await this.auditLog({ + type: AuditType.role, + action: AuditAction.delete, + content: `删除了角色(ID:${id})`, + }); + return res; } @Post("/getPermissionTree", { description: "sys:auth:role:view" }) diff --git a/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts b/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts index 19d317de5..f669fe545 100644 --- a/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts @@ -6,6 +6,7 @@ import { PermissionService } from "../../../modules/sys/authority/service/permis import { Constants } from "@certd/lib-server"; import { In } from "typeorm"; import { LoginService } from "../../../modules/login/service/login-service.js"; +import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; /** * 系统用户 @@ -97,7 +98,13 @@ export class UserController extends CrudController { @Body(ALL) bean ) { - return await super.add(bean); + const res = await super.add(bean); + await this.auditLog({ + type: AuditType.user, + action: AuditAction.add, + content: `新增了用户「${bean.username}」(ID:${res.data})`, + }); + return res; } @Post("/update", { description: "sys:auth:user:edit" }) @@ -105,7 +112,13 @@ export class UserController extends CrudController { @Body(ALL) bean ) { - return await super.update(bean); + const res = await super.update(bean); + await this.auditLog({ + type: AuditType.user, + action: AuditAction.update, + content: `修改了用户「${bean.username}」(ID:${bean.id})`, + }); + return res; } @Post("/delete", { description: "sys:auth:user:remove" }) @@ -119,7 +132,13 @@ export class UserController extends CrudController { if (id === 3) { throw new Error("不能删除默认的普通用户角色"); } - return await super.delete(id); + const res = await super.delete(id); + await this.auditLog({ + type: AuditType.user, + action: AuditAction.delete, + content: `删除了用户(ID:${id})`, + }); + return res; } /** diff --git a/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts b/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts index e2b1d5c81..54a141322 100644 --- a/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts @@ -3,6 +3,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js"; import { ProjectEntity } from "../../../modules/sys/enterprise/entity/project.js"; import { merge } from "lodash-es"; +import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -38,17 +39,29 @@ export class SysProjectController extends CrudController { }; merge(bean, def); bean.userId = this.getUserId(); - return super.add({ + const res = await super.add({ ...bean, userId: -1, //企业用户id固定为-1 adminId: bean.userId, }); + await this.auditLog({ + type: AuditType.project, + action: AuditAction.add, + content: `新增了项目「${bean.name}」(ID:${res.data})`, + }); + return res; } @Post("/update", { description: "sys:settings:edit" }) async update(@Body(ALL) bean: any) { bean.userId = this.getUserId(); - return super.update(bean); + const res = await super.update(bean); + await this.auditLog({ + type: AuditType.project, + action: AuditAction.update, + content: `修改了项目「${bean.name}」(ID:${bean.id})`, + }); + return res; } @Post("/info", { description: "sys:settings:view" }) @@ -58,7 +71,13 @@ export class SysProjectController extends CrudController { @Post("/delete", { description: "sys:settings:edit" }) async delete(@Query("id") id: number) { - return super.delete(id); + const res = await super.delete(id); + await this.auditLog({ + type: AuditType.project, + action: AuditAction.delete, + content: `删除了项目(ID:${id})`, + }); + return res; } @Post("/deleteByIds", { description: "sys:settings:edit" }) @@ -69,6 +88,13 @@ export class SysProjectController extends CrudController { @Post("/setDisabled", { description: "sys:settings:edit" }) async setDisabled(@Body("id") id: number, @Body("disabled") disabled: boolean) { await this.service.setDisabled(id, disabled); + const project = await this.service.info(id); + const actionText = disabled ? "禁用了" : "启用了"; + await this.auditLog({ + type: AuditType.project, + action: AuditAction.disable, + content: `${actionText}项目「${project.name}」(ID:${id})`, + }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts b/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts index 52cc53537..49b0b8a15 100644 --- a/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts @@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core"; import { BaseController, SysSafeSetting } from "@certd/lib-server"; import { cloneDeep } from "lodash-es"; import { SafeService } from "../../../modules/sys/settings/safe-service.js"; +import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -22,6 +23,11 @@ export class SysSettingsController extends BaseController { @Post("/save", { description: "sys:settings:edit" }) async safeSave(@Body(ALL) body: any) { await this.safeService.saveSafeSetting(body); + await this.auditLog({ + type: AuditType.settings, + action: AuditAction.update, + content: "修改了安全设置", + }); return this.ok({}); } diff --git a/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts b/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts index af8e1f30d..7fc10a348 100644 --- a/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts @@ -8,6 +8,7 @@ import { http, logger, utils } from "@certd/basic"; import { CodeService } from "../../../modules/basic/service/code-service.js"; import { SmsServiceFactory } from "../../../modules/basic/sms/factory.js"; import { RuntimeDepsService } from "../../../modules/runtime-deps/runtime-deps-service.js"; +import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -66,6 +67,11 @@ export class SysSettingsController extends CrudController { @Post("/save", { description: "sys:settings:edit" }) async save(@Body(ALL) bean: SysSettingsEntity) { await this.service.save(bean); + await this.auditLog({ + type: AuditType.settings, + action: AuditAction.update, + content: "修改了系统设置", + }); return this.ok({}); } diff --git a/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts b/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts new file mode 100644 index 000000000..633b157eb --- /dev/null +++ b/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts @@ -0,0 +1,32 @@ +import { BaseController, Constants } from "@certd/lib-server"; +import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core"; +import { ApiTags } from "@midwayjs/swagger"; +import { AuditService } from "../../../modules/sys/enterprise/service/audit-service.js"; +import { buildAuditTypeDict, buildAuditActionDict } from "../../../modules/sys/enterprise/service/audit-constants.js"; + +@Provide() +@ApiTags(["audit"]) +@Controller("/api/pi/audit") +export class AuditLogController extends BaseController { + @Inject() + auditService: AuditService; + + @Post("/page", { description: Constants.per.authOnly, summary: "分页查询当前用户操作日志" }) + async page(@Body(ALL) body: any) { + const userId = this.getUserId(); + if (!body.query) { + body.query = {}; + } + body.query.userId = userId; + const pageRet = await this.auditService.page(body); + return this.ok(pageRet); + } + + @Post("/dict", { description: Constants.per.authOnly, summary: "获取审计类型和动作字典" }) + async getDict() { + return this.ok({ + types: buildAuditTypeDict(), + actions: buildAuditActionDict(), + }); + } +} diff --git a/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts b/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts index 30b211679..f181fbe4c 100644 --- a/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts +++ b/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts @@ -7,6 +7,7 @@ import { merge } from "lodash-es"; import { SiteIpService } from "../../../modules/monitor/service/site-ip-service.js"; import { utils } from "@certd/basic"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -20,7 +21,6 @@ export class SiteInfoController extends CrudController { authService: AuthService; @Inject() siteIpService: SiteIpService; - getService(): SiteInfoService { return this.service; } @@ -75,6 +75,11 @@ export class SiteInfoController extends CrudController { if (entity.disabled) { this.service.check(entity.id, true, 0); } + this.auditLog({ + type: AuditType.monitor, + action: AuditAction.add, + content: `新增了站点监控「${bean.name}」(ID:${res.id}, 域名:${bean.domain})`, + }); return this.ok(res); } @@ -88,6 +93,11 @@ export class SiteInfoController extends CrudController { if (entity.disabled) { this.service.check(entity.id, true, 0); } + this.auditLog({ + type: AuditType.monitor, + action: AuditAction.update, + content: `修改了站点监控「${bean.name}」(ID:${bean.id})`, + }); return this.ok(); } @Post("/info", { description: Constants.per.authOnly, summary: "查询站点监控详情" }) @@ -99,13 +109,24 @@ export class SiteInfoController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除站点监控" }) async delete(@Query("id") id: number) { await this.checkOwner(this.service, id, "write"); - return await super.delete(id); + const res = await super.delete(id); + this.auditLog({ + type: AuditType.monitor, + action: AuditAction.delete, + content: `删除了站点监控(ID:${id})`, + }); + return res; } @Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除站点监控" }) async batchDelete(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdWrite(); await this.service.batchDelete(body.ids, userId, projectId); + this.auditLog({ + type: AuditType.monitor, + action: AuditAction.batchDelete, + content: `批量删除了${body.ids.length}条站点监控`, + }); return this.ok(); } diff --git a/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts b/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts index a1787f85e..11f8af51c 100644 --- a/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts +++ b/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts @@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { OpenKeyService } from "../../../modules/open/service/open-key-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -14,7 +15,6 @@ export class OpenKeyController extends CrudController { service: OpenKeyService; @Inject() authService: AuthService; - getService(): OpenKeyService { return this.service; } @@ -57,6 +57,11 @@ export class OpenKeyController extends CrudController { body.projectId = projectId; body.userId = userId; const res = await this.service.add(body); + this.auditLog({ + type: AuditType.openKey, + action: AuditAction.add, + content: `新增了API密钥(ID:${res.id}, scope:${body.scope})`, + }); return this.ok(res); } @@ -66,6 +71,11 @@ export class OpenKeyController extends CrudController { delete bean.userId; delete bean.projectId; await this.service.update(bean); + this.auditLog({ + type: AuditType.openKey, + action: AuditAction.update, + content: `修改了API密钥(ID:${bean.id})`, + }); return this.ok(); } @Post("/info", { description: Constants.per.authOnly, summary: "查询开放API密钥详情" }) @@ -90,7 +100,13 @@ export class OpenKeyController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除开放API密钥" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return await super.delete(id); + const res = await super.delete(id); + this.auditLog({ + type: AuditType.openKey, + action: AuditAction.delete, + content: `删除了API密钥(ID:${id})`, + }); + return res; } @Post("/getApiToken", { description: Constants.per.authOnly, summary: "获取API测试令牌" }) diff --git a/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts index 181edd230..5872494e4 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts @@ -4,6 +4,7 @@ import { AccessService } from "@certd/lib-server"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { AccessDefine } from "@certd/pipeline"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 授权 @@ -16,7 +17,6 @@ export class AccessController extends CrudController { service: AccessService; @Inject() authService: AuthService; - getService(): AccessService { return this.service; } @@ -58,7 +58,13 @@ export class AccessController extends CrudController { const { projectId, userId } = await this.getProjectUserIdWrite(); bean.userId = userId; bean.projectId = projectId; - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ + type: AuditType.access, + action: AuditAction.add, + content: `新增了授权「${bean.name}」(ID:${res.data}, 类型:${bean.type})`, + }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新授权配置" }) @@ -66,7 +72,13 @@ export class AccessController extends CrudController { await this.checkOwner(this.getService(), bean.id, "write"); delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ + type: AuditType.access, + action: AuditAction.update, + content: `修改了授权「${bean.name}」(ID:${bean.id})`, + }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询授权配置详情" }) async info(@Query("id") id: number) { @@ -77,7 +89,13 @@ export class AccessController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除授权配置" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ + type: AuditType.access, + action: AuditAction.delete, + content: `删除了授权(ID:${id})`, + }); + return res; } @Post("/define", { description: Constants.per.authOnly, summary: "查询授权插件定义" }) diff --git a/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts index 06aca817e..bbfecb631 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts @@ -5,6 +5,7 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service import { NotificationDefine } from "@certd/pipeline"; import { checkPlus } from "@certd/plus-core"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 通知 @@ -17,7 +18,6 @@ export class NotificationController extends CrudController service: NotificationService; @Inject() authService: AuthService; - getService(): NotificationService { return this.service; } @@ -62,7 +62,13 @@ export class NotificationController extends CrudController if (define.needPlus) { checkPlus(); } - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ + type: AuditType.notification, + action: AuditAction.add, + content: `新增了通知配置「${bean.name}」(ID:${res.data}, 类型:${bean.type})`, + }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新通知配置" }) @@ -84,7 +90,13 @@ export class NotificationController extends CrudController } delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ + type: AuditType.notification, + action: AuditAction.update, + content: `修改了通知配置「${bean.name}」(ID:${bean.id})`, + }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询通知配置详情" }) async info(@Query("id") id: number) { @@ -95,7 +107,13 @@ export class NotificationController extends CrudController @Post("/delete", { description: Constants.per.authOnly, summary: "删除通知配置" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ + type: AuditType.notification, + action: AuditAction.delete, + content: `删除了通知配置(ID:${id})`, + }); + return res; } @Post("/define", { description: Constants.per.authOnly, summary: "查询通知插件定义" }) diff --git a/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts index 9b7ddece8..99e3ed9ae 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts @@ -7,6 +7,7 @@ import { HistoryService } from "../../../modules/pipeline/service/history-servic import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { PipelineEntity } from "../../../modules/pipeline/entity/pipeline.js"; +import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; const pipelineExample = ` // 流水线配置示例,实际传送时要去掉注释 @@ -123,6 +124,7 @@ export class PipelineController extends CrudController { @Inject() siteInfoService: SiteInfoService; + getService() { return this.service; } @@ -196,7 +198,8 @@ export class PipelineController extends CrudController { @Post("/save", { description: Constants.per.authOnly, summary: "新增/更新流水线" }) async save(@Body() bean: PipelineSaveDTO) { const { userId, projectId } = await this.getProjectUserIdWrite(); - if (bean.id > 0) { + const isNew = bean.id <= 0; + if (!isNew) { const { userId, projectId } = await this.checkOwner(this.getService(), bean.id, "write", true); bean.userId = userId; bean.projectId = projectId; @@ -206,16 +209,22 @@ export class PipelineController extends CrudController { } if (!this.isAdmin()) { - // 非管理员用户 不允许设置流水线有效期 delete bean.validTime; } const { version } = await this.service.save(bean as any); - //是否增加证书监控 + + const title = bean.title; + this.auditLog({ + type: AuditType.pipeline, + action: isNew ? AuditAction.add : AuditAction.update, + content: isNew ? `创建了流水线「${title}」(ID:${bean.id})` : `修改了流水线「${title}」(ID:${bean.id})`, + projectId, + }); + if (bean.addToMonitorEnabled && bean.addToMonitorDomains) { const sysPublicSettings = await this.sysSettingsService.getPublicSettings(); if (isPlus() && sysPublicSettings.certDomainAddToMonitorEnabled) { - //增加证书监控 await this.siteInfoService.doImport({ text: bean.addToMonitorDomains, userId: userId, @@ -230,6 +239,11 @@ export class PipelineController extends CrudController { async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write", true); await this.service.delete(id); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.delete, + content: `删除了流水线(ID:${id})`, + }); return this.ok({}); } @@ -253,6 +267,11 @@ export class PipelineController extends CrudController { async trigger(@Query("id") id: number, @Query("stepId") stepId?: string) { await this.checkOwner(this.getService(), id, "write", true); await this.service.trigger(id, stepId, true); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.execute, + content: `手动执行了流水线(ID:${id})`, + }); return this.ok({}); } @@ -260,6 +279,11 @@ export class PipelineController extends CrudController { async cancel(@Query("historyId") historyId: number) { await this.checkOwner(this.historyService, historyId, "write", true); await this.service.cancel(historyId); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.cancel, + content: `取消了流水线执行(historyId:${historyId})`, + }); return this.ok({}); } @@ -283,63 +307,53 @@ export class PipelineController extends CrudController { @Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除流水线" }) async batchDelete(@Body("ids") ids: number[]) { - // let { projectId ,userId} = await this.getProjectUserIdWrite() - // if(projectId){ - // await this.service.batchDelete(ids, null,projectId); - // return this.ok({}); - // } - // const isAdmin = await this.authService.isAdmin(this.ctx); - // userId = isAdmin ? undefined : userId; - // await this.service.batchDelete(ids, userId); - // return this.ok({}); await this.checkPermissionCall(async ({ userId, projectId }) => { await this.service.batchDelete(ids, userId, projectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.batchDelete, + content: `批量删除了${ids.length}条流水线`, + }); return this.ok({}); } @Post("/batchUpdateGroup", { description: Constants.per.authOnly, summary: "批量更新流水线分组" }) async batchUpdateGroup(@Body("ids") ids: number[], @Body("groupId") groupId: number) { - // let { projectId ,userId} = await this.getProjectUserIdWrite() - // if(projectId){ - // await this.service.batchUpdateGroup(ids, groupId, null,projectId); - // return this.ok({}); - // } - - // const isAdmin = await this.authService.isAdmin(this.ctx); - // userId = isAdmin ? undefined : this.getUserId(); - // await this.service.batchUpdateGroup(ids, groupId, userId); await this.checkPermissionCall(async ({ userId, projectId }) => { await this.service.batchUpdateGroup(ids, groupId, userId, projectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.batchUpdate, + content: `批量修改了${ids.length}条流水线分组`, + }); return this.ok({}); } @Post("/batchUpdateTrigger", { description: Constants.per.authOnly, summary: "批量更新流水线触发器" }) async batchUpdateTrigger(@Body("ids") ids: number[], @Body("trigger") trigger: any) { - // let { projectId ,userId} = await this.getProjectUserIdWrite() - // if(projectId){ - // await this.service.batchUpdateTrigger(ids, trigger, null,projectId); - // return this.ok({}); - // } - - // const isAdmin = await this.authService.isAdmin(this.ctx); - // userId = isAdmin ? undefined : this.getUserId(); - // await this.service.batchUpdateTrigger(ids, trigger, userId); await this.checkPermissionCall(async ({ userId, projectId }) => { await this.service.batchUpdateTrigger(ids, trigger, userId, projectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.batchUpdate, + content: `批量修改了${ids.length}条流水线触发器`, + }); return this.ok({}); } @Post("/batchUpdateNotification", { description: Constants.per.authOnly, summary: "批量更新流水线通知" }) async batchUpdateNotification(@Body("ids") ids: number[], @Body("notification") notification: any) { - // const isAdmin = await this.authService.isAdmin(this.ctx); - // const userId = isAdmin ? undefined : this.getUserId(); - // await this.service.batchUpdateNotifications(ids, notification, userId); await this.checkPermissionCall(async ({ userId, projectId }) => { await this.service.batchUpdateNotifications(ids, notification, userId, projectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.batchUpdate, + content: `批量修改了${ids.length}条流水线通知`, + }); return this.ok({}); } @@ -348,6 +362,11 @@ export class PipelineController extends CrudController { await this.checkPermissionCall(async ({ userId, projectId }) => { await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.batchUpdate, + content: `批量修改了${ids.length}条流水线证书申请配置`, + }); return this.ok({}); } @@ -356,6 +375,11 @@ export class PipelineController extends CrudController { await this.checkPermissionCall(async ({ userId, projectId }) => { await this.service.batchRerun(ids, force, userId, projectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.execute, + content: `批量重新执行了${ids.length}条流水线`, + }); return this.ok({}); } @@ -364,6 +388,11 @@ export class PipelineController extends CrudController { await this.checkPermissionCall(async ({}) => { await this.service.batchTransfer(ids, toProjectId); }); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.batchUpdate, + content: `批量迁移了${ids.length}条流水线`, + }); return this.ok({}); } @@ -371,6 +400,11 @@ export class PipelineController extends CrudController { async refreshWebhookKey(@Body("id") id: number) { await this.checkOwner(this.getService(), id, "write", true); const res = await this.service.refreshWebhookKey(id); + this.auditLog({ + type: AuditType.pipeline, + action: AuditAction.update, + content: `刷新了流水线(ID:${id})的Webhook密钥`, + }); return this.ok({ webhookKey: res, }); diff --git a/packages/ui/certd-server/src/modules/auto/auto-cron.ts b/packages/ui/certd-server/src/modules/auto/auto-cron.ts index a037b2538..1ff50b181 100644 --- a/packages/ui/certd-server/src/modules/auto/auto-cron.ts +++ b/packages/ui/certd-server/src/modules/auto/auto-cron.ts @@ -12,6 +12,7 @@ import { SiteInfoService } from "../monitor/index.js"; import { NotificationService } from "../pipeline/service/notification-service.js"; import { PipelineService } from "../pipeline/service/pipeline-service.js"; import { UserService } from "../sys/authority/service/user-service.js"; +import { AuditService } from "../sys/enterprise/service/audit-service.js"; import { ProjectService } from "../sys/enterprise/service/project-service.js"; @Provide() @@ -50,16 +51,14 @@ export class AutoCron { domainService: DomainService; @Inject() projectService: ProjectService; + @Inject() + auditService: AuditService; async init() { logger.info("加载定时trigger开始"); await this.pipelineService.onStartup(this.immediateTriggerOnce, this.onlyAdminUser); logger.info("加载定时trigger完成"); - // - // const meta = getClassMetadata(CLASS_KEY, this.echoPlugin); - // console.log('meta', meta); - // const metas = listPropertyDataFromClass(CLASS_KEY, this.echoPlugin); - // console.log('metas', metas); + await this.registerSiteMonitorCron(); await this.registerPlusExpireCheckCron(); @@ -67,6 +66,8 @@ export class AutoCron { await this.registerUserExpireCheckCron(); await this.registerDomainExpireCheckCron(); + + await this.registerAuditCleanCron(); } async registerSiteMonitorCron() { @@ -238,4 +239,10 @@ export class AutoCron { }, }); } + + async registerAuditCleanCron() { + logger.info("注册审计日志清理定时任务"); + this.auditService.registerCleanCron(); + logger.info("注册审计日志清理定时任务完成"); + } } diff --git a/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts b/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts index b053977ca..d4481b5be 100644 --- a/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts +++ b/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts @@ -10,7 +10,7 @@ export class AuditLogEntity { @Column({ name: "user_id", comment: "UserId" }) userId: number; - @Column({ name: "user_name", comment: "用户名" }) + @Column({ name: "username", comment: "用户名" }) userName: string; @Column({ name: "project_id", comment: "ProjectId" }) diff --git a/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts new file mode 100644 index 000000000..d156ad6bf --- /dev/null +++ b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts @@ -0,0 +1,87 @@ +export const AuditType = { + pipeline: "pipeline", + access: "access", + monitor: "monitor", + notification: "notification", + openKey: "openKey", + user: "user", + role: "role", + permission: "permission", + project: "project", + settings: "settings", +} as const; + +export const AuditTypeMap = { + pipeline: "流水线", + access: "授权管理", + monitor: "站点监控", + notification: "通知设置", + openKey: "API密钥", + user: "用户管理", + role: "角色管理", + permission: "权限管理", + project: "项目管理", + settings: "系统设置", +} as const; + +export const AuditAction = { + add: "add", + update: "update", + delete: "delete", + execute: "execute", + cancel: "cancel", + batchDelete: "batchDelete", + batchUpdate: "batchUpdate", + disable: "disable", +} as const; + +export const AuditActionMap = { + add: "新增", + update: "修改", + delete: "删除", + execute: "执行", + cancel: "取消", + batchDelete: "批量删除", + batchUpdate: "批量修改", + disable: "禁用", +} as const; + +export const AuditTypeColorMap: Record = { + pipeline: "blue", + access: "orange", + monitor: "green", + notification: "purple", + openKey: "red", + user: "cyan", + role: "geekblue", + permission: "lime", + project: "gold", + settings: "magenta", +}; + +export const AuditActionColorMap: Record = { + add: "green", + update: "blue", + delete: "red", + execute: "orange", + cancel: "default", + batchDelete: "volcano", + batchUpdate: "purple", + disable: "default", +}; + +export function buildAuditTypeDict() { + return Object.entries(AuditTypeMap).map(([value, label]) => ({ + value, + label, + color: AuditTypeColorMap[value], + })); +} + +export function buildAuditActionDict() { + return Object.entries(AuditActionMap).map(([value, label]) => ({ + value, + label, + color: AuditActionColorMap[value], + })); +} diff --git a/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts new file mode 100644 index 000000000..c1882582f --- /dev/null +++ b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts @@ -0,0 +1,129 @@ +import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core"; +import { TypeORMDataSourceManager } from "@midwayjs/typeorm"; +import { LessThan, Repository } from "typeorm"; +import { AuditLogEntity } from "../entity/audit-log.js"; +import { logger } from "@certd/basic"; +import { Cron } from "../../../cron/cron.js"; + +export type AuditPageReq = { + page?: { offset: number; limit: number }; + query?: { + userId?: number; + type?: string; + action?: string; + createTime_start?: string; + createTime_end?: string; + }; + sort?: { prop: string; asc: boolean }; +}; + +@Provide() +@Scope(ScopeEnum.Request, { allowDowngrade: true }) +export class AuditService { + @Inject() + dataSourceManager: TypeORMDataSourceManager; + + @Inject() + cron: Cron; + + getRepository(): Repository { + return this.dataSourceManager.getDataSource("default").getRepository(AuditLogEntity); + } + + async log(params: { userId: number; type: string; action: string; content: string; username?: string; projectId?: number; projectName?: string; ipAddress?: string }): Promise { + try { + let { username } = params; + if (!username && params.userId != null) { + const userRepo = this.dataSourceManager.getDataSource("default").getRepository("sys_user" as any); + const user = await userRepo.findOne({ where: { id: params.userId } }); + username = user?.username || ""; + } + + const repo = this.getRepository(); + const entity = new AuditLogEntity(); + entity.userId = params.userId; + entity.userName = username || ""; + entity.type = params.type; + entity.action = params.action; + entity.content = params.content; + entity.projectId = params.projectId || 0; + entity.projectName = params.projectName || ""; + entity.ipAddress = params.ipAddress || ""; + await repo.save(entity); + } catch (e) { + logger.error("写入审计日志失败:", e); + } + } + + async page(pageReq: AuditPageReq) { + const repo = this.getRepository(); + const { page, query, sort } = pageReq; + const offset = page?.offset ?? 0; + const limit = page?.limit ?? 20; + + const qb = repo.createQueryBuilder("main"); + + if (query?.userId != null) { + qb.andWhere("main.userId = :userId", { userId: query.userId }); + } + if (query?.type) { + qb.andWhere("main.type = :type", { type: query.type }); + } + if (query?.action) { + qb.andWhere("main.action = :action", { action: query.action }); + } + if (query?.createTime_start) { + qb.andWhere("main.createTime >= :start", { start: query.createTime_start }); + } + if (query?.createTime_end) { + qb.andWhere("main.createTime <= :end", { end: query.createTime_end }); + } + + if (sort?.prop) { + qb.orderBy("main." + sort.prop, sort.asc ? "ASC" : "DESC"); + } else { + qb.orderBy("main.id", "DESC"); + } + + qb.skip(offset).take(limit); + const list = await qb.getMany(); + const total = await qb.getCount(); + + return { + records: list, + total, + offset, + limit, + }; + } + + async cleanExpired(retentionDays: number): Promise { + const repo = this.getRepository(); + const cutoff = new Date(); + cutoff.setDate(cutoff.getDate() - retentionDays); + + const result = await repo.delete({ + createTime: LessThan(cutoff), + } as any); + const deletedCount = result.affected || 0; + if (deletedCount > 0) { + logger.info(`审计日志清理完成,删除 ${deletedCount} 条超过 ${retentionDays} 天的记录`); + } + return deletedCount; + } + + async delete(id: number): Promise { + const repo = this.getRepository(); + await repo.delete({ id }); + } + + registerCleanCron() { + this.cron.register({ + name: "audit.cleanExpired", + cron: "0 3 * * *", + job: async () => { + await this.cleanExpired(90); + }, + }); + } +} diff --git a/packages/ui/certd-server/src/plugins/plugin-volcengine/plugins/plugin-deploy-to-vod.ts b/packages/ui/certd-server/src/plugins/plugin-volcengine/plugins/plugin-deploy-to-vod.ts index 31bbc6be4..4fb474856 100644 --- a/packages/ui/certd-server/src/plugins/plugin-volcengine/plugins/plugin-deploy-to-vod.ts +++ b/packages/ui/certd-server/src/plugins/plugin-volcengine/plugins/plugin-deploy-to-vod.ts @@ -243,7 +243,7 @@ export class VolcengineDeployToVOD extends AbstractTaskPlugin { return { value: item.Domain, label: item.Domain, - domain : item.Domain, + domain: item.Domain, }; }); return this.ctx.utils.options.buildGroupOptions(list, this.certDomains);