Compare commits

..

6 Commits

Author SHA1 Message Date
xiaojunnuo 947fe729cb chore: 继续完善审计日志 2026-07-13 00:53:19 +08:00
xiaojunnuo bfb3ee4c43 chore: 登录失败也记录日志 2026-07-12 22:28:51 +08:00
xiaojunnuo bab1df2c78 chore(i18n): add permanent VIP label and handle permanent VIP case
为国际化多语言添加永久VIP的翻译文本,同时在激活成功弹窗中处理永久会员的过期日期显示逻辑,当过期时间为-1时显示永久而非固定日期
2026-07-12 17:37:25 +08:00
xiaojunnuo 00eabec771 Merge branch 'v2-dev' into v2_audit_log 2026-07-12 17:28:21 +08:00
xiaojunnuo f2855d6dac feat: 支持审计日志,操作日志 2026-07-12 02:29:54 +08:00
xiaojunnuo 4250d0e266 chore: audit log first 2026-07-10 19:24:42 +08:00
143 changed files with 3726 additions and 1582 deletions
@@ -1,412 +0,0 @@
# 插件依赖按需加载方案
## 背景与目标
### 当前问题
- `packages/ui/certd-server/node_modules` 包含 50+ 个插件的所有依赖,体积庞大
- 大量云厂商 SDK(AWS、阿里云、腾讯云、华为云等)只在特定插件中使用
- 用户通常只使用少数几个插件,但必须安装所有依赖
### 目标
实现依赖的按需下载和加载:
1. 插件依赖独立管理,不占用主 `node_modules` 空间
2. 只有当用户首次使用某插件时,才动态下载该插件需要的依赖
3. 依赖安装完成后,通过 `await import()` 从独立路径加载
4. 保持现有插件代码的最小改动
## 当前架构分析
### 插件加载机制
- 插件位于 `packages/ui/certd-server/src/plugins/` 下(50+ 个插件目录)
- `AutoLoadPlugins` 类在启动时扫描 `dist/plugins` 目录并动态导入
- 插件注册到不同的 registry`accessRegistry`, `pluginRegistry`, `dnsProviderRegistry`
- 插件代码已经使用 `await import()` 进行懒加载(如 `await import("@aws-sdk/client-acm")`
### 重型依赖分布
`packages/ui/certd-server/package.json` 分析,以下依赖体积大且仅特定插件使用:
**云厂商 SDK(按插件分组):**
- **AWS 插件**`@aws-sdk/client-acm`, `@aws-sdk/client-cloudfront`, `@aws-sdk/client-iam`, `@aws-sdk/client-route-53`, `@aws-sdk/client-s3`, `@aws-sdk/client-sts`
- **阿里云插件**`@alicloud/openapi-client`, `@alicloud/pop-core`, `@alicloud/tea-typescript`, `@alicloud/fc20230330`
- **腾讯云插件**`tencentcloud-sdk-nodejs`, `cos-nodejs-sdk-v5`
- **华为云插件**`@huaweicloud/huaweicloud-sdk-cdn`, `@huaweicloud/huaweicloud-sdk-core`
- **Azure 插件**`@azure/arm-dns`, `@azure/identity`
- **Google Cloud 插件**`@google-cloud/dns`, `@google-cloud/publicca`
- **火山引擎插件**`@volcengine/openapi`, `@volcengine/tos-sdk`
**网络/工具库:**
- `ssh2`, `socks`, `socks-proxy-agent`SSH 相关插件)
- `ali-oss`, `qiniu`, `basic-ftp`(存储/传输插件)
- `nodemailer`(邮件通知插件)
**通用依赖(保留在主 package.json):**
- `@midwayjs/*` 系列(框架核心)
- `@certd/*` 系列(项目内部包)
- `axios`, `lodash-es`, `dayjs`, `js-yaml` 等基础工具
## 设计方案
### 架构概览
```
packages/ui/certd-server/
├── package.json # 主依赖(框架、通用工具)
├── node_modules/ # 主依赖安装目录
├── optional-deps/ # 新增:可选依赖管理目录
│ ├── package.json # 可选依赖总配置(用于 pnpm install
│ ├── pnpm-lock.yaml # 可选依赖锁文件
│ └── node_modules/ # 可选依赖安装目录
├── src/
│ └── modules/
│ └── dependency/ # 新增:依赖管理模块
│ ├── dependency-manager.ts # 核心:依赖管理器
│ ├── dependency-registry.ts # 依赖注册表(插件 -> 依赖映射)
│ └── types.ts # 类型定义
```
### 核心组件
#### 1. 依赖管理器(DependencyManager
**职责:**
- 检查依赖是否已安装
- 动态执行 `pnpm install` 安装缺失依赖
- 提供从 `optional-deps/node_modules` 加载依赖的方法
- 并发控制:避免多个插件同时触发安装
**关键方法:**
```typescript
class DependencyManager {
// 确保依赖已安装,返回依赖模块
async ensureAndImport<T>(packageName: string): Promise<T>
// 检查依赖是否已安装
async isInstalled(packageName: string): Promise<boolean>
// 安装依赖(带锁,避免并发)
async installDependencies(packages: string[]): Promise<void>
// 从 optional-deps/node_modules 加载依赖
async loadModule<T>(packageName: string): Promise<T>
}
```
**实现要点:**
- 使用文件锁(如 `proper-lockfile`)防止并发安装
- 安装前检查 `optional-deps/node_modules/{packageName}` 是否存在
- 安装命令:`pnpm install --dir optional-deps --ignore-workspace`
- 加载时使用绝对路径:`import('file:///absolute/path/to/optional-deps/node_modules/package')`
#### 2. 依赖注册表(DependencyRegistry
**职责:**
- 维护插件名称到依赖列表的映射
- 提供依赖查询接口
**数据结构:**
```typescript
interface PluginDependencyConfig {
pluginName: string;
dependencies: {
packageName: string;
version: string;
optional?: boolean; // 是否可选(安装失败不阻塞)
}[];
}
// 示例注册
dependencyRegistry.register('plugin-aws', [
{ packageName: '@aws-sdk/client-acm', version: '^3.964.0' },
{ packageName: '@aws-sdk/client-cloudfront', version: '^3.964.0' },
{ packageName: '@aws-sdk/client-route-53', version: '^3.964.0' },
]);
```
#### 3. 插件集成
**改造现有插件代码:**
改造前(`plugin-aws/libs/aws-client.ts`):
```typescript
const { ACMClient, ImportCertificateCommand } = await import("@aws-sdk/client-acm");
```
改造后:
```typescript
import { DependencyManager } from "../../../modules/dependency/dependency-manager.js";
const depManager = new DependencyManager();
const { ACMClient, ImportCertificateCommand } = await depManager.ensureAndImport("@aws-sdk/client-acm");
```
**简化方案(推荐):**
创建辅助函数,减少改动量:
```typescript
// src/modules/dependency/import-helper.ts
export async function importOptionalDep<T>(packageName: string): Promise<T> {
const depManager = new DependencyManager();
return await depManager.ensureAndImport<T>(packageName);
}
// 插件中使用
import { importOptionalDep } from "../../../modules/dependency/import-helper.js";
const { ACMClient } = await importOptionalDep("@aws-sdk/client-acm");
```
### 实施步骤
#### 阶段一:基础设施搭建
1. 创建 `optional-deps/` 目录结构
2. 生成 `optional-deps/package.json`(包含所有可选依赖)
3. 实现 `DependencyManager` 核心逻辑
4. 实现依赖安装锁机制
5. 编写单元测试
#### 阶段二:依赖迁移
6. 从主 `package.json` 移除可选依赖
7. 将依赖添加到 `optional-deps/package.json`
8. 创建依赖注册表,映射插件到依赖
#### 阶段三:插件改造
9. 创建 `import-helper.ts` 辅助函数
10. 逐步改造插件代码,使用 `importOptionalDep` 加载依赖
11. 优先改造重型依赖(AWS、阿里云、腾讯云等)
#### 阶段四:测试与优化
12. 端到端测试:验证依赖按需安装和加载
13. 性能优化:缓存已加载的模块
14. 错误处理:安装失败时的降级策略
15. 文档:编写使用说明和迁移指南
## 关键技术决策
### 1. 依赖分组策略
**选择:按插件分组**
- 每个插件声明自己需要的依赖
- 优点:职责清晰,易于维护
- 缺点:可能有重复依赖(但 pnpm 会去重)
**备选:按功能分组**
- 将依赖按功能分组(如 "aws-deps", "aliyun-deps"
- 优点:更细粒度控制
- 缺点:增加复杂度
### 2. 安装触发时机
**选择:首次使用时触发**
- 在插件的 `execute()``getClient()` 方法中触发安装
- 优点:真正的按需加载
- 缺点:首次使用有延迟
**备选:启动时预检查**
- 启动时扫描启用的插件,预安装依赖
- 优点:避免运行时延迟
- 缺点:可能安装不需要的依赖
### 3. 依赖路径解析
**选择:使用绝对路径 + `file://` 协议**
```typescript
const modulePath = path.resolve(__dirname, '../../optional-deps/node_modules', packageName);
return await import(`file://${modulePath}/index.js`);
```
**原因:**
- Node.js ESM 要求明确的 URL 格式
- 避免模块解析冲突
### 4. 并发控制
**选择:文件锁 + 内存锁双重保护**
- 使用 `proper-lockfile` 锁定 `optional-deps/` 目录
- 内存中使用 `Map` 记录正在安装的依赖
- 避免多个插件同时触发安装
### 5. 错误处理
**策略:**
- 安装失败时记录日志,抛出明确的错误信息
- 提供手动安装命令提示:`请运行: cd optional-deps && pnpm install`
- 支持降级:某些非核心依赖安装失败时,插件可以部分功能可用
## 验证方案
### 单元测试
1. 测试 `DependencyManager.isInstalled()` 正确检测依赖状态
2. 测试 `DependencyManager.installDependencies()` 成功安装依赖
3. 测试并发安装时的锁机制
4. 测试从 `optional-deps/node_modules` 加载模块
### 集成测试
1. 清空 `optional-deps/node_modules`
2. 启动服务,验证不触发安装
3. 调用 AWS 插件,验证触发安装并成功加载
4. 再次调用,验证不重复安装
5. 验证主 `node_modules` 体积减少
### 性能测试
1. 测量首次安装依赖的耗时
2. 测量后续加载的耗时(应该与正常 import 相近)
3. 对比改造前后的 `node_modules` 大小
## 风险与挑战
### 1. 首次使用延迟
**风险:** 用户首次使用插件时需要等待依赖安装(可能几十秒)
**缓解:**
- 在 UI 上显示安装进度
- 提供预安装命令:`pnpm run install-optional-deps`
- 文档说明首次使用会有延迟
### 2. 离线环境
**风险:** 离线环境无法下载依赖
**缓解:**
- 提供完整安装包(包含所有可选依赖)
- 支持手动复制 `node_modules`
### 3. 版本冲突
**风险:** 可选依赖与主依赖版本冲突
**缓解:**
- 使用 `--ignore-workspace` 隔离安装
- 定期同步主依赖版本
### 4. TypeScript 类型
**风险:** 动态导入的类型推断
**缓解:**
- 保留 `@types/*` 在主 `devDependencies`
- 使用泛型和类型断言
## 预期收益
1. **空间节省:**`node_modules` 体积减少 60-70%(估算)
2. **安装速度:** 初始 `pnpm install` 速度提升 3-5 倍
3. **用户体验:** 不使用的插件不占用空间,按需加载
4. **维护性:** 依赖分组清晰,易于管理
## 后续优化
1. **依赖预热:** 在后台预安装常用插件依赖
2. **依赖缓存:** 支持从 CDN 或本地缓存安装
3. **依赖更新:** 提供命令批量更新可选依赖
4. **插件市场:** 支持从远程下载插件及其依赖配置
## 附录:依赖分类清单
### 可选依赖(迁移到 optional-deps/package.json
**AWS 相关(plugin-aws, plugin-aws-cn):**
```json
{
"@aws-sdk/client-acm": "^3.964.0",
"@aws-sdk/client-cloudfront": "^3.964.0",
"@aws-sdk/client-iam": "^3.964.0",
"@aws-sdk/client-route-53": "^3.964.0",
"@aws-sdk/client-s3": "^3.964.0",
"@aws-sdk/client-sts": "^3.990.0"
}
```
**阿里云相关(plugin-aliyun, plugin-lib/aliyun):**
```json
{
"@alicloud/fc20230330": "^4.1.7",
"@alicloud/openapi-client": "^0.4.12",
"@alicloud/openapi-util": "^0.3.2",
"@alicloud/pop-core": "^1.7.10",
"@alicloud/sts-sdk": "^1.0.2",
"@alicloud/tea-typescript": "^1.8.0",
"@alicloud/tea-util": "^1.4.10",
"ali-oss": "^6.21.0"
}
```
**腾讯云相关(plugin-tencent, plugin-lib/tencent):**
```json
{
"tencentcloud-sdk-nodejs": "^4.1.112",
"cos-nodejs-sdk-v5": "^2.14.6"
}
```
**华为云相关(plugin-huawei):**
```json
{
"@huaweicloud/huaweicloud-sdk-cdn": "3.1.185",
"@huaweicloud/huaweicloud-sdk-core": "3.1.185",
"@huaweicloud/huaweicloud-sdk-elb": "3.1.185",
"@huaweicloud/huaweicloud-sdk-iam": "3.1.185",
"esdk-obs-nodejs": "^3.25.6"
}
```
**Azure 相关(plugin-azure):**
```json
{
"@azure/arm-dns": "^5.1.0",
"@azure/identity": "^4.13.1"
}
```
**Google Cloud 相关(plugin-google, plugin-cert/google):**
```json
{
"@google-cloud/dns": "^5.3.1",
"@google-cloud/publicca": "^1.3.0"
}
```
**火山引擎相关(plugin-volcengine):**
```json
{
"@volcengine/openapi": "^1.28.1",
"@volcengine/tos-sdk": "^2.9.1"
}
```
**SSH/网络相关(plugin-host, plugin-lib/ssh):**
```json
{
"ssh2": "^1.17.0",
"socks": "^2.8.3",
"socks-proxy-agent": "^8.0.4",
"basic-ftp": "^5.0.5"
}
```
**其他存储/传输(plugin-qiniu, plugin-lib/qiniu):**
```json
{
"qiniu": "^7.12.0"
}
```
**邮件通知(plugin-notification/email):**
```json
{
"nodemailer": "^6.9.16"
}
```
### 主依赖(保留在主 package.json
**框架核心:**
- `@midwayjs/*` 系列
- `@koa/cors`
- `typeorm`, `better-sqlite3`, `mysql2`, `pg`
**项目内部包:**
- `@certd/*` 系列
**通用工具:**
- `axios`, `lodash-es`, `dayjs`, `js-yaml`
- `crypto-js`, `jsonwebtoken`, `bcryptjs`
- `reflect-metadata`, `uuid`, `nanoid`
- 等等
## 总结
本方案通过引入独立的可选依赖管理机制,实现了插件依赖的按需下载和加载。核心思路是:
1. **隔离管理:**`optional-deps/` 目录下维护独立的 `package.json``node_modules`
2. **动态安装:** 通过 `DependencyManager` 在首次使用时触发 `pnpm install`
3. **路径加载:** 使用绝对路径从独立目录加载依赖模块
4. **最小改动:** 通过辅助函数 `importOptionalDep` 简化插件代码改造
该方案可以显著减少主 `node_modules` 体积,提升初始安装速度,同时保持现有架构的兼容性和可维护性。
+24 -1
View File
@@ -212,6 +212,29 @@ Certd 是可私有化部署的 SSL/TLS 证书自动化管理平台,提供 Web
## 注意事项
### 换行符(LF / CRLF
- 本项目源码使用 **LF** 换行符。Windows 上通过 Python 写文件时,open(path, "w", encoding="utf-8") 默认使用 **CRLF**,会破坏文件格式。
- **修复方案**:写文件时用 open(path, "w", encoding="utf-8", newline="\n") 明确指定 LF。
- 如果已经写入 CRLF,用以下 PowerShell 修复:
`powershell
git add --renormalize . && git commit -m "fix line endings"
`
### 旧版数据兼容
- 新增插件参数时,必须要考虑旧版数据兼容,比如新增一个deployType参数,有两种值:`default``custom`,需要在使用时判空,走旧版逻辑。
- 新增插件参数时,必须要考虑旧版数据兼容,比如新增一个deployType参数,有两种值:`default``custom`,需要在使用时判空,走旧版逻辑。
## 前端路由与国际化
- 路由 `meta.title`**i18n 国际化 key**,必须在 `src/locales/langs/zh-CN/``src/locales/langs/en-US/` 对应的模块文件中添加翻译。
- 示例:路由 `title: "certd.auditLog"` 需要在中英 locales 文件中有对应 key`"certd.auditLog": "操作日志"` / `"certd.auditLog": "Audit Log"`)。
- 菜单通过路由自动生成,需设置 `meta.isMenu: true` 才会出现在左侧菜单。
- Plus 版功能菜单需设置 `meta.show: () => { const settingStore = useSettingStore(); return settingStore.isPlus; }`
## 审计日志
- 审计日志是 Plus 版功能,非 Plus 版不会写入。
- Controller 继承 `BaseController`,通过 `this.auditLog({ content: "xxx" })` 记录日志。
- `getAuditType()` 返回类型常量,中间件自动从 ctx.path 判定 scope`/api/sys/` → system,其他 → user)。
- 操作日志有系统级(scope=system)和用户级(scope=user)区分。
-1
View File
@@ -1 +0,0 @@

-1
View File
@@ -39,7 +39,6 @@
"test:unit": "cross-env NODE_ENV=unittest pnpm -r --workspace-concurrency=1 run test:unit",
"pub": "echo 1",
"dev": "pnpm run -r --parallel compile ",
"lint_all": "pnpm run -r --parallel lint ",
"pub_all": "node ./scripts/pub-all.js",
"release": "time /t >trigger/release.trigger && git add trigger/release.trigger && git commit -m \"build: release\" && git push",
"publish_to_atomgit": "node --experimental-json-modules ./scripts/publish-atomgit.js",
+9 -2
View File
@@ -3,7 +3,7 @@ import { FormItemProps } from "../dt/index.js";
import { HttpClient, ILogger, utils } from "@certd/basic";
import * as _ from "lodash-es";
import { PluginRequestHandleReq } from "../plugin/index.js";
import { IServiceGetter, getRuntimeDepsService } from "../service/index.js";
import { IRuntimeDepsService, IServiceGetter } from "../service/index.js";
// export type AccessRequestHandleReqInput<T = any> = {
// id?: number;
@@ -48,13 +48,20 @@ export type AccessContext = {
export abstract class BaseAccess implements IAccess {
ctx!: AccessContext;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
return await getRuntimeDepsService().importRuntime(specifier, this.ctx.logger);
if (!this.runtimeDepsService) {
throw new Error("runtimeDepsService 未初始化");
}
return await this.runtimeDepsService.importRuntime(specifier, this.ctx.logger);
}
async setCtx(ctx: AccessContext) {
this.ctx = ctx;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
}
async onRequest(req: AccessRequestHandleReq) {
@@ -3,7 +3,7 @@ import { Registrable } from "../registry/index.js";
import { FormItemProps, HistoryResult, Pipeline } from "../dt/index.js";
import { HttpClient, ILogger, utils } from "@certd/basic";
import * as _ from "lodash-es";
import { IEmailService, IServiceGetter, getRuntimeDepsService } from "../service/index.js";
import { IEmailService, IRuntimeDepsService, IServiceGetter } from "../service/index.js";
export type NotificationBody = {
userId?: number;
@@ -89,9 +89,13 @@ export abstract class BaseNotification implements INotification {
ctx!: NotificationContext;
http!: HttpClient;
logger!: ILogger;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
if (!this.runtimeDepsService) {
return await import(specifier);
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
}
async doSend(body: NotificationBody) {
@@ -105,6 +109,9 @@ export abstract class BaseNotification implements INotification {
this.ctx = ctx;
this.http = ctx.http;
this.logger = ctx.logger;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
}
setDefine = (define: NotificationDefine) => {
this.define = define;
+10 -3
View File
@@ -10,7 +10,7 @@ import { INotificationService } from "../notification/index.js";
import { Registrable } from "../registry/index.js";
import { IPluginConfigService } from "../service/config.js";
import { TaskEmitter } from "../service/emit.js";
import { ICnameProxyService, IEmailService, IServiceGetter, IUrlService, getRuntimeDepsService } from "../service/index.js";
import { ICnameProxyService, IEmailService, IRuntimeDepsService, IServiceGetter, IUrlService } from "../service/index.js";
export type PluginRequestHandleReq<T = any> = {
typeName: string;
@@ -76,7 +76,7 @@ export type ITaskPlugin = {
execute(): Promise<void | string>;
onRequest(req: PluginRequestHandleReq<any>): Promise<any>;
setCtx(ctx: TaskInstanceContext): Promise<void>;
importRuntime(specifier: string): Promise<any>;
importRuntime?(specifier: string): Promise<any>;
[key: string]: any;
};
@@ -150,9 +150,13 @@ export abstract class AbstractTaskPlugin implements ITaskPlugin {
logger!: ILogger;
http!: HttpClient;
accessService!: IAccessService;
runtimeDepsService!: IRuntimeDepsService;
async importRuntime(specifier: string) {
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
if (!this.runtimeDepsService) {
throw new Error("runtimeDepsService 未初始化");
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
}
clearLastStatus() {
@@ -174,6 +178,9 @@ export abstract class AbstractTaskPlugin implements ITaskPlugin {
this.logger = ctx.logger;
this.accessService = ctx.accessService;
this.http = ctx.http;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
// 将证书加入secret
// @ts-ignore
if (this.cert && this.cert.crt && this.cert.key) {
+27 -3
View File
@@ -1,3 +1,27 @@
// 类型已迁至 runtime-deps-service.ts,通过 index.ts 重新导出
// 此文件保留空壳,避免已有引用报错
export * from "./runtime-deps-service.js";
/**
* 运行时动态导入函数类型
*/
export type ImportRuntime = (specifier: string, logger?: ILogger) => Promise<any>;
/**
* 日志接口
*/
export type ILogger = {
info: (message: string) => void;
};
/**
* 运行时依赖服务参数
*/
export type EnsureRuntimeDepsOptions = {
pluginKeys: string | string[];
logger?: ILogger;
};
/**
* 运行时依赖服务接口
*/
export interface IRuntimeDepsService {
ensureRuntimeDependencies(options: EnsureRuntimeDepsOptions): Promise<any>;
importRuntime: ImportRuntime;
}
+1 -2
View File
@@ -28,8 +28,7 @@
"cross-env": "^7.0.3",
"esmock": "^2.7.5",
"prettier": "3.3.3",
"tslib": "^2.8.1",
"eslint": "^8.57.0"
"tslib": "^2.8.1"
},
"gitHead": "268cd6cc9cb4f1f3d5d5d77859a82f18f0cb6db7"
}
+1 -2
View File
@@ -39,8 +39,7 @@
"js-yaml": "^3.11.0",
"mocha": "^10.6.0",
"prettier": "3.3.3",
"tslib": "^2.8.1",
"eslint": "^8.57.0"
"tslib": "^2.8.1"
},
"engines": {
"node": ">= 8.6.0",
@@ -0,0 +1,34 @@
/// <reference types="mocha" />
import assert from "node:assert/strict";
import { AuditLogContext } from "./audit.js";
// AuditLog decorator and getAuditLogOptions are removed since auditLog()
// now signals audit intent directly via ctx.auditLog.enabled
describe("AuditLogContext type", () => {
it("supports enabled flag", () => {
const ctx: AuditLogContext = {
type: "pipeline",
action: "删除流水线",
append: ["ID:5"],
content: "删除了流水线(ID:5)",
projectId: 3,
enabled: true,
};
assert.equal(ctx.enabled, true);
assert.equal(ctx.type, "pipeline");
assert.equal(ctx.content, "删除了流水线(ID:5)");
assert.equal(ctx.projectId, 3);
});
it("works with minimal fields", () => {
const ctx: AuditLogContext = {
enabled: true,
append: ["提交2条"],
};
assert.equal(ctx.enabled, true);
});
});
@@ -0,0 +1,44 @@
export type AuditLogOptions = {
type?: string;
action?: string;
content?: string;
template?: string;
disabled?: boolean;
};
export type AuditLogContext = {
type?: string;
action?: string;
append?: string | string[];
content?: string;
projectId?: number;
enabled?: boolean;
scope?: string;
userId?: number;
username?: string;
success?: boolean;
};
/** 审计日志方法的参数类型 */
export type AuditLogParam = {
type?: string;
action?: string;
content?: string;
append?: string | string[];
projectId?: number;
userId?: number;
username?: string;
};
/** AuditService.log() 参数类型 */
export type AuditLogWriteParam = {
userId: number;
type: string;
action: string;
content: string;
username?: string;
projectId?: number;
ipAddress?: string;
scope?: string;
success?: boolean;
};
@@ -3,6 +3,7 @@ import type { IMidwayContainer } from "@midwayjs/core";
import * as koa from "@midwayjs/koa";
import { Constants } from "./constants.js";
import { isEnterprise } from "./mode.js";
import type { AuditLogContext, AuditLogParam } from "./audit.js";
export abstract class BaseController {
@Inject()
@@ -127,4 +128,43 @@ export abstract class BaseController {
}
return { projectId, userId };
}
getAuditType(): string {
return "unknown";
}
auditLog(bean: AuditLogParam = {}) {
const auditLog = this.ensureAuditLogContext();
auditLog.enabled = true;
if (bean.userId != null) {
auditLog.userId = bean.userId;
}
if (bean.username != null) {
auditLog.username = bean.username;
}
if (bean.type != null) {
auditLog.type = bean.type;
}
if (bean.action != null) {
auditLog.action = bean.action;
}
if (bean.projectId != null) {
auditLog.projectId = bean.projectId;
}
if (bean.content) {
auditLog.content = bean.content;
}
if (bean.append) {
const items = Array.isArray(bean.append) ? bean.append : [bean.append];
const old = Array.isArray(auditLog.append) ? auditLog.append : auditLog.append ? [auditLog.append] : [];
auditLog.append = [...old, ...items].filter(item => item && String(item).trim());
}
}
private ensureAuditLogContext(): AuditLogContext {
if (!this.ctx.auditLog) {
this.ctx.auditLog = {};
}
return this.ctx.auditLog;
}
}
+35 -35
View File
@@ -1,21 +1,21 @@
export const Constants = {
dataDir: './data',
dataDir: "./data",
role: {
defaultUser: 3,
},
per: {
//无需登录
guest: '_guest_',
guest: "_guest_",
//无需登录
anonymous: '_guest_',
anonymous: "_guest_",
//无需登录,有 token 时解析当前用户
guestOptionalAuth: '_guestOptionalAuth_',
guestOptionalAuth: "_guestOptionalAuth_",
//仅需要登录
authOnly: '_authOnly_',
authOnly: "_authOnly_",
//仅需要登录
loginOnly: '_authOnly_',
loginOnly: "_authOnly_",
open: '_open_',
open: "_open_",
},
res: {
serverError(message: string) {
@@ -26,102 +26,102 @@ export const Constants = {
},
error: {
code: 1,
message: 'Internal server error',
message: "Internal server error",
},
success: {
code: 0,
message: 'success',
message: "success",
},
validation: {
code: 10,
message: '参数错误',
message: "参数错误",
},
needvip: {
code: 88,
message: '需要VIP',
message: "需要VIP",
},
needsuite: {
code: 89,
message: '需要购买或升级套餐',
message: "需要购买或升级套餐",
},
loginError: {
code: 2,
message: '登录失败',
message: "登录失败",
},
codeError: {
code: 3,
message: '验证码错误',
message: "验证码错误",
},
auth: {
code: 401,
message: '您还未登录或token已过期',
message: "您还未登录或token已过期",
},
permission: {
code: 402,
message: '您没有权限',
message: "您没有权限",
},
param: {
code: 400,
message: '参数错误',
message: "参数错误",
},
notFound: {
code: 404,
message: '页面/文件/资源不存在',
message: "页面/文件/资源不存在",
},
preview: {
code: 10001,
message: '对不起,预览环境不允许修改此数据',
message: "对不起,预览环境不允许修改此数据",
},
siteOff:{
siteOff: {
code: 10010,
message: '站点已关闭',
message: "站点已关闭",
},
need2fa:{
need2fa: {
code: 10020,
message: '需要2FA认证',
message: "需要2FA认证",
},
openKeyError: {
code: 20000,
message: 'ApiToken错误',
message: "ApiToken错误",
},
openKeySignError: {
code: 20001,
message: 'ApiToken签名错误',
message: "ApiToken签名错误",
},
openKeyExpiresError: {
code: 20002,
message: 'ApiToken时间戳错误',
message: "ApiToken时间戳错误",
},
openKeySignTypeError: {
code: 20003,
message: 'ApiToken签名类型不支持',
message: "ApiToken签名类型不支持",
},
openParamError: {
code: 20010,
message: '请求参数错误',
message: "请求参数错误",
},
openCertNotFound: {
code: 20011,
message: '证书不存在',
message: "证书不存在",
},
openCertNotReady: {
code: 20012,
message: '证书还未生成',
message: "证书还未生成",
},
openCertApplying: {
code: 20013,
message: '证书正在申请中,请稍后重新获取',
message: "证书正在申请中,请稍后重新获取",
},
openDomainNoVerifier:{
openDomainNoVerifier: {
code: 20014,
message: '域名校验方式未配置',
message: "域名校验方式未配置",
},
openEmailNotFound: {
code: 20021,
message: '用户邮箱还未配置',
message: "用户邮箱还未配置",
},
},
systemUserId: 0, // 系统级别userid固定为0
enterpriseUserId: -1 // 企业模式用户id固定为-1
enterpriseUserId: -1, // 企业模式用户id固定为-1
};
@@ -0,0 +1,20 @@
import { createRequestParamDecorator } from "@midwayjs/core";
export const AuditLog = (opts: { type?: string; action?: string; content?: string; enabled?: boolean } = {}) => {
return createRequestParamDecorator(ctx => {
if (!ctx.auditLog) {
ctx.auditLog = {};
}
ctx.auditLog.enabled = opts.enabled !== false;
if (opts.type != null) {
ctx.auditLog.type = opts.type;
}
if (opts.action != null) {
ctx.auditLog.action = opts.action;
}
if (opts.content != null) {
ctx.auditLog.content = opts.content;
}
return ctx.auditLog;
});
};
@@ -0,0 +1 @@
export * from "./decoractor.js";
@@ -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<T> extends BaseController {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
abstract getService<T>();
@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<T> 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<T> 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);
}
@@ -1,12 +1,14 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 通用异常
*/
export class LoginErrorException extends BaseException {
leftCount: number;
constructor(message, leftCount: number) {
super('LoginErrorException', Constants.res.loginError.code, message ? message : Constants.res.loginError.message);
userId?: number;
constructor(message, leftCount: number, userId?: number) {
super("LoginErrorException", Constants.res.loginError.code, message ? message : Constants.res.loginError.message);
this.leftCount = leftCount;
this.userId = userId;
}
}
+10 -8
View File
@@ -1,8 +1,10 @@
export * from './base-controller.js';
export * from './constants.js';
export * from './crud-controller.js';
export * from './enum-item.js';
export * from './exception/index.js';
export * from './result.js';
export * from './base-service.js';
export * from "./mode.js"
export * from "./base-controller.js";
export * from "./constants.js";
export * from "./crud-controller.js";
export * from "./enum-item.js";
export * from "./exception/index.js";
export * from "./result.js";
export * from "./base-service.js";
export * from "./audit.js";
export * from "./mode.js";
export * from "./core/index.js";
+8 -8
View File
@@ -1,12 +1,12 @@
let adminMode = "saas"
let adminMode = "saas";
export function setAdminMode(mode:string = "saas"){
adminMode = mode
export function setAdminMode(mode: string = "saas") {
adminMode = mode;
}
export function getAdminMode(){
return adminMode
export function getAdminMode() {
return adminMode;
}
export function isEnterprise(){
return adminMode === "enterprise"
}
export function isEnterprise() {
return adminMode === "enterprise";
}
@@ -1,6 +1,15 @@
import { HttpClient, ILogger, utils } from "@certd/basic";
import { upperFirst } from "lodash-es";
import { accessRegistry, FormItemProps, IAccessService, IServiceGetter, PluginRequestHandleReq, Registrable, getRuntimeDepsService } from "@certd/pipeline";
import {upperFirst} from "lodash-es";
import {
accessRegistry,
FormItemProps,
IAccessService,
IRuntimeDepsService,
IServiceGetter,
PluginRequestHandleReq,
Registrable
} from "@certd/pipeline";
export type AddonRequestHandleReqInput<T = any> = {
id?: number;
@@ -10,7 +19,7 @@ export type AddonRequestHandleReqInput<T = any> = {
export type AddonRequestHandleReq<T = any> = {
addonType: string;
} & PluginRequestHandleReq<AddonRequestHandleReqInput<T>>;
} &PluginRequestHandleReq<AddonRequestHandleReqInput<T>>;
export type AddonInputDefine = FormItemProps & {
title: string;
@@ -39,6 +48,8 @@ export type AddonInstanceConfig = {
};
};
export interface IAddon {
ctx: AddonContext;
[key: string]: any;
@@ -56,9 +67,13 @@ export abstract class BaseAddon implements IAddon {
ctx!: AddonContext;
http!: HttpClient;
logger!: ILogger;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
if (!this.runtimeDepsService) {
return await import(specifier);
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
}
title!: string;
@@ -70,7 +85,7 @@ export abstract class BaseAddon implements IAddon {
if (accessId == null) {
throw new Error("您还没有配置授权");
}
const accessService = await this.ctx.serviceGetter.get<IAccessService>("accessService");
const accessService = await this.ctx.serviceGetter.get<IAccessService>("accessService")
let res: any = null;
if (isCommon) {
res = await accessService.getCommonById(accessId);
@@ -103,12 +118,15 @@ export abstract class BaseAddon implements IAddon {
this.ctx = ctx;
this.http = ctx.http;
this.logger = ctx.logger;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
}
setDefine = (define: AddonDefine) => {
setDefine = (define:AddonDefine) => {
this.define = define;
};
async onRequest(req: AddonRequestHandleReq) {
async onRequest(req:AddonRequestHandleReq) {
if (!req.action) {
throw new Error("action is required");
}
@@ -126,8 +144,10 @@ export abstract class BaseAddon implements IAddon {
}
throw new Error(`action ${req.action} not found`);
}
}
export interface IAddonGetter {
getById<T = any>(id: any): Promise<T>;
getCommonById<T = any>(id: any): Promise<T>;
+32 -37
View File
@@ -1,8 +1,8 @@
import * as path from "path";
import * as fs from "fs";
import { QueryRunner, Table } from "typeorm";
import { FlywayHistory } from "./entity.js";
import * as crypto from "crypto";
import * as path from 'path';
import * as fs from 'fs';
import { QueryRunner, Table } from 'typeorm';
import { FlywayHistory } from './entity.js';
import * as crypto from 'crypto';
/**
* 脚本文件信息
@@ -32,10 +32,10 @@ const DefaultLogger = {
},
};
let customLogger: any = null;
export function setFlywayLogger(logger: any) {
let customLogger:any = null;
export function setFlywayLogger (logger: any) {
customLogger = logger;
}
};
export class Flyway {
scriptDir;
@@ -45,8 +45,8 @@ export class Flyway {
connection;
logger;
constructor(opts: any) {
this.scriptDir = opts.scriptDir ?? "db/migration";
this.flywayTableName = opts.flywayTableName ?? "flyway_history";
this.scriptDir = opts.scriptDir ?? 'db/migration';
this.flywayTableName = opts.flywayTableName ?? 'flyway_history';
this.baseline = opts.baseline ?? false;
this.allowHashNotMatch = opts.allowHashNotMatch ?? false;
this.logger = customLogger || opts.logger || DefaultLogger;
@@ -54,9 +54,9 @@ export class Flyway {
}
async run(ignores?: (RegExp | string)[]) {
this.logger.info("[ midfly ] start-------------");
this.logger.info('[ midfly ] start-------------');
if (!fs.existsSync(this.scriptDir)) {
this.logger.info("[ midfly ] scriptDir<" + this.scriptDir + "> not found");
this.logger.info('[ midfly ] scriptDir<' + this.scriptDir + '> not found');
return;
}
@@ -77,7 +77,7 @@ export class Flyway {
continue;
}
if (!file.isBaseline) {
this.logger.info("need exec script file: ", file.script);
this.logger.info('need exec script file: ', file.script);
//执行sql文件
if (/\.sql$/.test(file.script)) {
await this.execSql(filepath, queryRunner);
@@ -87,7 +87,7 @@ export class Flyway {
// await this.execJsOrTs(filepath, t);
// }
} else {
this.logger.info("baseline script file: ", file.script);
this.logger.info('baseline script file: ', file.script);
}
await this.storeSqlExecLog(file.script, filepath, true, queryRunner);
await queryRunner.commitTransaction();
@@ -95,15 +95,10 @@ export class Flyway {
this.logger.error(err);
await this.storeSqlExecLog(file.script, filepath, false, queryRunner);
await queryRunner.rollbackTransaction();
if (err.code === "SQLITE_IOERR_WRITE") {
this.logger.warn("SQLite数据库写入失败,可能您的操作系统版本太低,请将「certd:latest」镜像改为「certd:slim」即可。(如需指定版本可以修改成「certd:[version]-slim」)", file.script);
}
throw err;
}
}
this.logger.info("[ midfly ] end-------------");
this.logger.info('[ midfly ] end-------------');
}
private async storeSqlExecLog(filename: string, filepath: string, success: boolean, queryRunner: QueryRunner) {
@@ -165,17 +160,17 @@ export class Flyway {
name: this.flywayTableName,
columns: [
{
name: "id",
name: 'id',
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationId,
}),
isGenerated: true,
generationStrategy: "increment",
generationStrategy: 'increment',
isPrimary: true,
isNullable: false,
},
{
name: "timestamp",
name: 'timestamp',
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationTimestamp,
}),
@@ -183,23 +178,23 @@ export class Flyway {
isNullable: false,
},
{
name: "name",
name: 'name',
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName,
}),
isNullable: false,
},
{
name: "hash",
name: 'hash',
type: this.connection.driver.normalizeType({
type: this.connection.driver.mappedDataTypes.migrationName,
}),
isNullable: true,
},
{
name: "success",
name: 'success',
type: this.connection.driver.normalizeType({
type: "boolean",
type: 'boolean',
}),
isNullable: true,
},
@@ -215,7 +210,7 @@ export class Flyway {
}
let ret = false;
for (const ignore of ignores) {
if (typeof ignore === "string" && file === ignore) {
if (typeof ignore === 'string' && file === ignore) {
ret = true;
break;
}
@@ -238,20 +233,20 @@ export class Flyway {
if (history.hash !== hash && this.allowHashNotMatch === false) {
throw new Error(file + `hash conflict ,old: ${history.hash} != new: ${hash}`);
}
this.logger.info("[ midfly ] script<" + file + "> already executed");
this.logger.info('[ midfly ] script<' + file + '> already executed');
return true;
}
this.logger.info("[ midfly ] script<" + file + "> not yet execute");
this.logger.info('[ midfly ] script<' + file + '> not yet execute');
return false;
}
private async getFileHash(filepath: string) {
const content = fs.readFileSync(filepath).toString();
return crypto.createHash("md5").update(content.toString()).digest("hex");
return crypto.createHash('md5').update(content.toString()).digest('hex');
}
private async execSql(filepath: string, queryRunner: QueryRunner) {
this.logger.info("[ midfly ] exec ", filepath);
this.logger.info('[ midfly ] exec ', filepath);
const content = fs.readFileSync(filepath).toString().trim();
const arr = this.splitSql2Array(content);
for (const s of arr) {
@@ -260,11 +255,11 @@ export class Flyway {
}
private async execOnePart(sql: string, queryRunner: QueryRunner) {
this.logger.debug("exec sql index: ", sql);
this.logger.debug('exec sql index: ', sql);
try {
await queryRunner.query(sql);
} catch (err: any) {
this.logger.error("exec sql error ", err.message, err);
this.logger.error('exec sql error ', err.message, err);
throw err;
}
}
@@ -280,11 +275,11 @@ export class Flyway {
const temp = String(str).trim();
if (temp === "null") {
if (temp === 'null') {
return [];
}
const semicolon = ";";
const semicolon = ';';
const deepChars = ['"', "'"];
const splits = [];
@@ -294,7 +289,7 @@ export class Flyway {
if (deepChars.indexOf(charAt) >= 0) {
//如果是深度char
if (i !== 0 && temp.charAt(i - 1) === "\\") {
if (i !== 0 && temp.charAt(i - 1) === '\\') {
//如果前一个是转义字符,忽略它
} else {
//说明需要进出深度了
@@ -1,5 +1,5 @@
import { HttpClient, ILogger } from "@certd/basic";
import { IAccessService, PageRes, PageSearch, getRuntimeDepsService } from "@certd/pipeline";
import { IAccessService, IRuntimeDepsService, PageRes, PageSearch } from "@certd/pipeline";
import punycode from "punycode.js";
import { CreateRecordOptions, DnsProviderContext, DnsProviderDefine, DnsResolveRecord, DomainRecord, IDnsProvider, RemoveRecordOptions } from "./api.js";
import { dnsProviderRegistry } from "./registry.js";
@@ -7,9 +7,13 @@ export abstract class AbstractDnsProvider<T = any> implements IDnsProvider<T> {
ctx!: DnsProviderContext;
http!: HttpClient;
logger!: ILogger;
runtimeDepsService?: IRuntimeDepsService;
async importRuntime(specifier: string) {
return await getRuntimeDepsService().importRuntime(specifier, this.logger);
if (!this.runtimeDepsService) {
throw new Error("runtimeDepsService 未初始化");
}
return await this.runtimeDepsService.importRuntime(specifier, this.logger);
}
usePunyCode(): boolean {
@@ -38,6 +42,9 @@ export abstract class AbstractDnsProvider<T = any> implements IDnsProvider<T> {
this.ctx = ctx;
this.logger = ctx.logger;
this.http = ctx.http;
if (!this.runtimeDepsService && this.ctx.serviceGetter) {
this.runtimeDepsService = await this.ctx.serviceGetter.get("runtimeDepsService");
}
}
async parseDomain(fullDomain: string) {
+1
View File
@@ -59,6 +59,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"core-js": "^3.36.0",
"cos-js-sdk-v5": "^1.7.0",
"cron-parser": "^4.9.0",
"cropperjs": "^1.6.1",
"cssnano": "^7.0.6",
@@ -139,7 +139,7 @@ async function doActive() {
title: t("vip.successTitle"),
content: t("vip.successContent", {
vipLabel,
expireDate: dayjs(settingStore.plusInfo.expireTime).format("YYYY-MM-DD"),
expireDate: settingStore.plusInfo.expireTime === -1 ? t("vip.permanent") : dayjs(settingStore.plusInfo.expireTime).format("YYYY-MM-DD"),
}),
onOk() {
if (!(settingStore.installInfo.bindUserId > 0)) {
@@ -18,6 +18,7 @@ export default {
openKey: "Open API Key",
notification: "Notification Settings",
siteMonitorSetting: "Site Monitor Settings",
auditLog: "Audit Log",
userSecurity: "Security Settings",
userProfile: "Account Info",
userGrant: "Grant Delegation",
@@ -67,6 +68,7 @@ export default {
projectJoin: "Join Project",
currentProject: "Current Project",
projectMemberManager: "Project Member",
auditLog: "Audit Log",
domainMonitorSetting: "Domain Monitor Settings",
},
};
@@ -104,4 +104,5 @@ export default {
not_effective: "Not effective or duration not sync?",
learn_more: "More privileges",
question: "More VIP related questions",
permanent: "Permanent",
};
@@ -18,6 +18,7 @@ export default {
openKey: "开放接口密钥",
notification: "通知设置",
siteMonitorSetting: "站点监控设置",
auditLog: "操作日志",
userSecurity: "认证安全设置",
userProfile: "账号信息",
userGrant: "授权委托",
@@ -67,6 +68,7 @@ export default {
projectJoin: "加入项目",
currentProject: "当前项目",
projectMemberManager: "项目成员管理",
auditLog: "审计日志",
domainMonitorSetting: "域名监控设置",
jobHistory: "监控执行记录",
},
@@ -103,4 +103,5 @@ export default {
not_effective: "VIP没有生效/时长未同步?",
learn_more: "更多特权(加VIP群等)",
question: "更多VIP相关问题",
permanent: "永久",
};
@@ -287,6 +287,22 @@ 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,
isMenu: true,
show: () => {
const settingStore = useSettingStore();
return settingStore.isPlus;
},
},
},
{
title: "certd.userSecurity",
name: "UserSecurity",
@@ -410,6 +410,22 @@ export const sysResources = [
},
],
},
{
title: "certd.sysResources.auditLog",
name: "SysAuditLog",
path: "/sys/enterprise/audit",
component: "/sys/enterprise/audit/index.vue",
meta: {
icon: "ion:document-text-outline",
keepAlive: true,
auth: true,
isMenu: true,
show: () => {
const settingStore = useSettingStore();
return settingStore.isPlus;
},
},
},
{
title: "certd.sysResources.netTest",
name: "NetTest",
@@ -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",
});
},
};
}
@@ -0,0 +1,132 @@
import { ColumnProps, DataFormatterContext, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
import { useI18n } from "/src/locales";
import { useDicts } from "../dicts";
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 || [];
},
});
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const { t } = useI18n();
const { myProjectDict } = useDicts();
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
return {
crudOptions: {
request: { pageRequest, delRequest },
toolbar: {
buttons: {
export: { show: true },
},
export: {
dataFrom: "search",
columnFilter: (col: ColumnProps) => col.show === true,
dataFormatter: (opts: DataFormatterContext) => {
const { row, originalRow, col } = opts;
const key = col.key;
if (key === "createTime" && originalRow[key]) {
row[key] = new Date(originalRow[key]).toLocaleString();
}
},
},
},
actionbar: {
buttons: {
add: { show: false },
},
},
rowHandle: {
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
copy: { show: 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",
},
},
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: "text",
search: { show: true },
column: { width: 200, tooltip: true },
form: { show: false },
},
success: {
title: "结果",
type: "dict-switch",
dict: dict({
data: [
{ value: true, label: "成功", color: "success" },
{ value: false, label: "失败", color: "error" },
],
}),
column: { width: 100, align: "center" },
form: { show: false },
search: { show: true },
},
content: {
title: "备注",
type: "text",
search: { show: true },
column: { width: 700, tooltip: true },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
projectId: {
title: t("certd.fields.projectName"),
type: "dict-select",
dict: myProjectDict,
form: {
show: false,
},
},
},
},
};
}
@@ -0,0 +1,24 @@
<template>
<fs-page>
<template #header>
<div class="title">
操作日志
<span class="sub">查看您的操作记录</span>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding" />
</fs-page>
</template>
<script lang="ts" setup>
import { useFs } from "@fast-crud/fast-crud";
import createCrudOptions from "./crud";
import { createAuditApi } from "./api";
import { useMounted } from "/@/use/use-mounted";
defineOptions({ name: "AuditLog" });
const api = createAuditApi();
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { api } });
useMounted(() => crudExpose.doRefresh());
</script>
@@ -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",
});
},
};
}
@@ -0,0 +1,180 @@
import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
import { Modal } from "ant-design-vue";
import { useI18n } from "/src/locales";
import { useDicts } from "/@/views/certd/dicts";
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 { t } = useI18n();
const { myProjectDict } = useDicts();
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
const cleanExpired = async () => {
Modal.confirm({
title: "确认清理",
content: "确定要清理90天前的审计日志吗?此操作不可撤销。",
okText: "确认清理",
okType: "danger",
cancelText: "取消",
async onOk() {
await api.Clean(90);
crudExpose.doRefresh();
},
});
};
return {
crudOptions: {
request: { pageRequest, delRequest },
tabs: {
name: "scope",
show: true,
dict: {
data: [
{ value: "system", label: "系统级", color: "red" },
{ value: "user", label: "用户级", color: "blue" },
],
},
},
actionbar: {
buttons: {
add: { show: false },
clean: {
text: "清理过期日志(90天)",
type: "primary",
danger: true,
click: cleanExpired,
},
},
},
rowHandle: {
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
copy: { show: false },
},
},
search: {
initialForm: { scope: "system" },
},
columns: {
id: {
title: "ID",
type: "number",
column: { width: 80 },
form: { show: false },
},
createTime: {
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
},
},
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: "text",
search: { show: true },
column: { width: 200, tooltip: true },
form: { show: false },
},
success: {
title: "结果",
type: "dict-switch",
dict: dict({
data: [
{ value: true, label: "成功", color: "success" },
{ value: false, label: "失败", color: "error" },
],
}),
column: { width: 100, align: "center" },
form: { show: false },
search: { show: true },
},
content: {
title: "备注",
type: "text",
search: { show: true },
column: { width: 500, tooltip: true },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
projectId: {
title: t("certd.fields.projectName"),
type: "dict-select",
dict: myProjectDict,
form: {
show: false,
},
},
scope: {
title: "范围",
type: "dict-select",
dict: dict({
data: [
{ value: "system", label: "系统级", color: "blue" },
{ value: "user", label: "用户级", color: "green" },
],
}),
search: { show: true },
column: { width: 100 },
form: { show: false },
},
},
},
};
}
@@ -0,0 +1,24 @@
<template>
<fs-page>
<template #header>
<div class="title">
操作日志
<span class="sub">查看所有用户的操作记录</span>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding" />
</fs-page>
</template>
<script lang="ts" setup>
import { useFs } from "@fast-crud/fast-crud";
import createCrudOptions from "./crud";
import { createSysAuditApi } from "./api";
import { useMounted } from "/@/use/use-mounted";
defineOptions({ name: "SysAuditLog" });
const api = createSysAuditApi();
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { api } });
useMounted(() => crudExpose.doRefresh());
</script>
@@ -1,75 +1,35 @@
import { request } from "/src/api/service";
const apiPrefix = "/sys/project/provider";
const apiPrefix = "/sys/audit";
export async function GetList(query: any) {
return await request({
url: apiPrefix + "/page",
method: "post",
data: query,
});
}
export async function AddObj(obj: any) {
return await request({
url: apiPrefix + "/add",
method: "post",
data: obj,
});
}
export async function UpdateObj(obj: any) {
return await request({
url: apiPrefix + "/update",
method: "post",
data: obj,
});
}
export async function DelObj(id: any) {
return await request({
url: apiPrefix + "/delete",
method: "post",
params: { id },
});
}
export async function GetObj(id: any) {
return await request({
url: apiPrefix + "/info",
method: "post",
params: { id },
});
}
export async function GetDetail(id: any) {
return await request({
url: apiPrefix + "/detail",
method: "post",
params: { id },
});
}
export async function DeleteBatch(ids: any[]) {
return await request({
url: apiPrefix + "/deleteByIds",
method: "post",
data: { ids },
});
}
export async function SetDefault(id: any) {
return await request({
url: apiPrefix + "/setDefault",
method: "post",
data: { id },
});
}
export async function SetDisabled(id: any, disabled: boolean) {
return await request({
url: apiPrefix + "/setDisabled",
method: "post",
data: { id, disabled },
});
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",
});
},
};
}
@@ -1,252 +1,194 @@
import * as api from "./api";
import { useI18n } from "/src/locales";
import { computed, Ref, ref } from "vue";
import { useRouter } from "vue-router";
import { AddReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, dict, EditReq, UserPageQuery, UserPageRes, utils } from "@fast-crud/fast-crud";
import { useUserStore } from "/@/store/user";
import { useSettingStore } from "/@/store/settings";
import { ColumnProps, DataFormatterContext, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
import { Modal } from "ant-design-vue";
import { useI18n } from "/src/locales";
import { useDicts } from "/@/views/certd/dicts";
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 router = useRouter();
const { t } = useI18n();
const { myProjectDict } = useDicts();
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const editRequest = async ({ form, row }: EditReq) => {
form.id = row.id;
const res = await api.UpdateObj(form);
return res;
};
const delRequest = async ({ row }: DelReq) => {
return await api.DelObj(row.id);
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
const addRequest = async ({ form }: AddReq) => {
const res = await api.AddObj(form);
return res;
const cleanExpired = async () => {
Modal.confirm({
title: "确认清理",
content: "确定要清理90天前的审计日志吗?此操作不可撤销。",
okText: "确认清理",
okType: "danger",
cancelText: "取消",
async onOk() {
await api.Clean(90);
crudExpose.doRefresh();
},
});
};
const userStore = useUserStore();
const settingStore = useSettingStore();
const selectedRowKeys: Ref<any[]> = ref([]);
context.selectedRowKeys = selectedRowKeys;
return {
crudOptions: {
settings: {
plugins: {
//这里使用行选择插件,生成行选择crudOptions配置,最终会与crudOptions合并
rowSelection: {
enabled: true,
order: -2,
before: true,
// handle: (pluginProps,useCrudProps)=>CrudOptions,
props: {
multiple: true,
crossPage: true,
selectedRowKeys,
},
request: { pageRequest, delRequest },
tabs: {
name: "scope",
show: true,
dict: {
data: [
{ value: "system", label: "系统级", color: "red" },
{ value: "user", label: "用户级", color: "blue" },
],
},
},
toolbar: {
buttons: {
export: { show: true },
},
export: {
dataFrom: "search",
columnFilter: (col: ColumnProps) => col.show === true,
dataFormatter: (opts: DataFormatterContext) => {
const { row, originalRow, col } = opts;
const key = col.key;
if (key === "createTime" && originalRow[key]) {
row[key] = new Date(originalRow[key]).toLocaleString();
}
},
},
},
request: {
pageRequest,
addRequest,
editRequest,
delRequest,
actionbar: {
buttons: {
add: { show: false },
clean: {
text: "清理过期日志(90天)",
type: "primary",
danger: true,
click: cleanExpired,
},
},
},
rowHandle: {
minWidth: 200,
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
copy: { show: false },
},
},
search: {
initialForm: { scope: "system" },
},
columns: {
id: {
title: "ID",
key: "id",
type: "number",
column: {
width: 100,
},
form: {
show: false,
},
},
domain: {
title: t("certd.cnameDomain"),
type: "text",
editForm: {
component: {
disabled: true,
},
},
search: {
show: true,
},
form: {
component: {
placeholder: t("certd.cnameDomainPlaceholder"),
},
helper: t("certd.cnameDomainHelper"),
rules: [
{ required: true, message: t("certd.requiredField") },
{ pattern: /^[^*]+$/, message: t("certd.cnameDomainPattern") },
],
},
column: {
width: 200,
},
},
dnsProviderType: {
title: t("certd.dnsProvider"),
type: "dict-select",
search: {
show: true,
},
dict: dict({
url: "pi/dnsProvider/list",
value: "key",
label: "title",
}),
form: {
rules: [{ required: true, message: t("certd.requiredField") }],
},
column: {
width: 150,
component: {
color: "auto",
},
},
},
accessId: {
title: t("certd.dnsProviderAuthorization"),
type: "dict-select",
dict: dict({
url: "/pi/access/list",
value: "id",
label: "name",
}),
form: {
component: {
name: "access-selector",
vModel: "modelValue",
type: compute(({ form }) => {
return form.dnsProviderType;
}),
},
rules: [{ required: true, message: t("certd.requiredField") }],
},
column: {
width: 150,
component: {
color: "auto",
},
},
},
isDefault: {
title: t("certd.isDefault"),
type: "dict-switch",
dict: dict({
data: [
{ label: t("certd.yes"), value: true, color: "success" },
{ label: t("certd.no"), value: false, color: "default" },
],
}),
form: {
value: false,
rules: [{ required: true, message: t("certd.selectIsDefault") }],
},
column: {
align: "center",
width: 100,
},
},
setDefault: {
title: t("certd.setDefault"),
type: "text",
form: {
show: false,
},
column: {
width: 100,
align: "center",
conditionalRenderDisabled: true,
cellRender: ({ row }) => {
if (row.isDefault) {
return;
}
const onClick = async () => {
Modal.confirm({
title: t("certd.prompt"),
content: t("certd.confirmSetDefault"),
onOk: async () => {
await api.SetDefault(row.id);
await crudExpose.doRefresh();
},
});
};
return (
<a-button type={"link"} size={"small"} onClick={onClick}>
{t("certd.setAsDefault")}
</a-button>
);
},
},
},
disabled: {
title: t("certd.disabled"),
type: "dict-switch",
dict: dict({
data: [
{ label: t("certd.enabled"), value: false, color: "success" },
{ label: t("certd.disabledLabel"), value: true, color: "error" },
],
}),
form: {
value: false,
},
column: {
width: 100,
component: {
title: t("certd.clickToToggle"),
on: {
async click({ value, row }) {
Modal.confirm({
title: t("certd.prompt"),
content: t("certd.confirmToggleStatus", { action: !value ? t("certd.disable") : t("certd.enable") }),
onOk: async () => {
await api.SetDisabled(row.id, !value);
await crudExpose.doRefresh();
},
});
},
},
},
},
column: { width: 80 },
form: { show: false },
},
createTime: {
title: t("certd.createTime"),
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
},
},
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: "text",
search: { show: true },
column: { width: 200, tooltip: true },
form: { show: false },
},
success: {
title: "结果",
type: "dict-switch",
dict: dict({
data: [
{ value: true, label: "成功", color: "success" },
{ value: false, label: "失败", color: "error" },
],
}),
column: { width: 100, align: "center" },
form: { show: false },
search: { show: true },
},
content: {
title: "备注",
type: "text",
search: { show: true },
column: { width: 500, tooltip: true },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
projectId: {
title: t("certd.fields.projectName"),
type: "dict-select",
dict: myProjectDict,
form: {
show: false,
},
column: {
sorter: true,
width: 160,
align: "center",
},
},
updateTime: {
title: t("certd.updateTime"),
type: "datetime",
form: {
show: false,
},
column: {
show: true,
width: 160,
},
scope: {
title: "范围",
type: "dict-select",
dict: dict({
data: [
{ value: "system", label: "系统级", color: "blue" },
{ value: "user", label: "用户级", color: "green" },
],
}),
search: { show: true },
column: { width: 100 },
form: { show: false },
},
},
},
@@ -1,63 +1,24 @@
<template>
<fs-page class="page-cert">
<fs-page>
<template #header>
<div class="title">
{{ t("certd.cnameTitle") }}
<span class="sub">
{{ t("certd.cnameDescription") }}
<a href="https://certd.docmirror.cn/guide/feature/cname/" target="_blank">
{{ t("certd.cnameLinkText") }}
</a>
</span>
操作日志
<span class="sub">查看所有用户的操作记录</span>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding">
<template #pagination-left>
<a-tooltip :title="t('certd.batchDelete')">
<fs-button icon="DeleteOutlined" @click="handleBatchDelete"></fs-button>
</a-tooltip>
</template>
</fs-crud>
<fs-crud ref="crudRef" v-bind="crudBinding" />
</fs-page>
</template>
<script lang="ts" setup>
import { useMounted } from "/@/use/use-mounted";
import { useFs } from "@fast-crud/fast-crud";
import createCrudOptions from "./crud";
import { message, Modal } from "ant-design-vue";
import { DeleteBatch } from "./api";
import { useI18n } from "/src/locales";
import { useCrudPermission } from "/@/plugin/permission";
import { createSysAuditApi } from "./api";
import { useMounted } from "/@/use/use-mounted";
const { t } = useI18n();
defineOptions({ name: "SysAuditLog" });
defineOptions({
name: "CnameProvider",
});
const { crudBinding, crudRef, crudExpose, context } = useFs({ createCrudOptions });
const selectedRowKeys = context.selectedRowKeys;
const handleBatchDelete = () => {
if (selectedRowKeys.value?.length > 0) {
Modal.confirm({
title: t("certd.confirmTitle"),
content: t("certd.confirmDeleteBatch", { count: selectedRowKeys.value.length }),
async onOk() {
await DeleteBatch(selectedRowKeys.value);
message.info(t("certd.deleteSuccess"));
crudExpose.doRefresh();
selectedRowKeys.value = [];
},
});
} else {
message.error(t("certd.selectRecordsFirst"));
}
};
// 页面打开后获取列表数据
useMounted(async () => {
await crudExpose.doRefresh();
});
const api = createSysAuditApi();
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { api } });
useMounted(() => crudExpose.doRefresh());
</script>
<style lang="less"></style>
+2 -1
View File
@@ -20,6 +20,7 @@
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-unsafe-assignment": "off"
// 允许any
"@typescript-eslint/no-unsafe-anyassignment": "off"
}
}
@@ -0,0 +1,8 @@
ALTER TABLE `cd_audit_log` ADD COLUMN `scope` varchar(32) NOT NULL DEFAULT 'user';
CREATE INDEX `index_audit_log_scope` ON `cd_audit_log` (`scope`);
ALTER TABLE `cd_audit_log` ADD COLUMN `success` tinyint(1) NOT NULL DEFAULT 1;
-- 审计日志表索引
CREATE INDEX `index_audit_log_type` ON `cd_audit_log` (`type`);
CREATE INDEX `index_audit_log_create_time` ON `cd_audit_log` (`create_time`);
@@ -0,0 +1,8 @@
ALTER TABLE "cd_audit_log" ADD COLUMN "scope" varchar(32) NOT NULL DEFAULT ('user');
CREATE INDEX "index_audit_log_scope" ON "cd_audit_log" ("scope");
ALTER TABLE "cd_audit_log" ADD COLUMN "success" boolean NOT NULL DEFAULT true;
-- 审计日志表索引
CREATE INDEX "index_audit_log_type" ON "cd_audit_log" ("type");
CREATE INDEX "index_audit_log_create_time" ON "cd_audit_log" ("create_time");
@@ -0,0 +1,8 @@
ALTER TABLE "cd_audit_log" ADD COLUMN "scope" varchar(32) NOT NULL DEFAULT ('user');
CREATE INDEX "index_audit_log_scope" ON "cd_audit_log" ("scope");
ALTER TABLE "cd_audit_log" ADD COLUMN "success" boolean NOT NULL DEFAULT (1);
-- 审计日志表索引
CREATE INDEX "index_audit_log_type" ON "cd_audit_log" ("type");
CREATE INDEX "index_audit_log_create_time" ON "cd_audit_log" ("create_time");
-2
View File
@@ -25,7 +25,6 @@
"format": "prettier --write src",
"lint": "mwts fix",
"ci": "pnpm run cov",
"lint2": "cross-env NODE_ENV=production mwtsc -p tsconfig.build.json",
"build-only": "cross-env NODE_ENV=production mwtsc -p tsconfig.build.json --cleanOutDir --skipLibCheck",
"build": "pnpm run build-only && pnpm run export-metadata",
"export-metadata": "node export-plugin-yaml.js",
@@ -134,7 +133,6 @@
"rimraf": "^5.0.5",
"ts-node": "^10.9.2",
"tslib": "^2.8.1",
"eslint":"^7.32.0",
"typescript": "^5.4.2",
"why-is-node-running": "^3.2.2"
},
@@ -12,6 +12,7 @@ import cors from "@koa/cors";
import { GlobalExceptionMiddleware } from "./middleware/global-exception.js";
import { PreviewMiddleware } from "./middleware/preview.js";
import { AuthorityMiddleware } from "./middleware/authority.js";
import { AuditLogMiddleware } from "./middleware/audit-log.js";
import { logger } from "@certd/basic";
import { ResetPasswdMiddleware } from "./middleware/reset-passwd/middleware.js";
import DefaultConfig from "./config/config.default.js";
@@ -113,6 +114,7 @@ export class MainConfiguration {
PreviewMiddleware,
//授权处理
AuthorityMiddleware,
AuditLogMiddleware,
//resetPasswd,重置密码模式下不提供服务
ResetPasswdMiddleware,
@@ -3,6 +3,7 @@ import { BaseController, CommonException, Constants, SysSettingsService } from "
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { LoginService } from "../../../modules/login/service/login-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -19,7 +20,11 @@ export class ForgotPasswordController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Post("/forgotPassword", { description: Constants.per.guest })
getAuditType(): string {
return AuditType.login.value;
}
@Post("/forgotPassword", { description: Constants.per.guest, summary: "找回密码" })
public async forgotPassword(
@Body(ALL)
body: any
@@ -28,15 +33,13 @@ export class ForgotPasswordController extends BaseController {
if (!sysSettings.selfServicePasswordRetrievalEnabled) {
throw new CommonException("暂未开启自助找回");
}
// 找回密码的验证码允许错误次数
const maxErrorCount = 5;
if (body.type === "email") {
this.codeService.checkEmailCode({
verificationType: "forgotPassword",
email: body.input,
validateCode: body.validateCode,
maxErrorCount: maxErrorCount,
maxErrorCount: 5,
throwError: true,
});
} else if (body.type === "mobile") {
@@ -45,14 +48,15 @@ export class ForgotPasswordController extends BaseController {
mobile: body.input,
phoneCode: body.phoneCode,
smsCode: body.validateCode,
maxErrorCount: maxErrorCount,
maxErrorCount: 5,
throwError: true,
});
} else {
throw new CommonException("暂不支持的找回类型,请联系管理员找回");
}
const username = await this.userService.forgotPassword(body);
const { id, username } = await this.userService.forgotPassword(body);
username && this.loginService.clearCacheOnSuccess(username);
this.auditLog({ userId: id, content: "用户请求找回密码" });
return this.ok();
}
}
@@ -5,9 +5,8 @@ import { CodeService } from "../../../modules/basic/service/code-service.js";
import { checkComm } from "@certd/plus-core";
import { CaptchaService } from "../../../modules/basic/service/captcha-service.js";
import { PasskeyService } from "../../../modules/login/service/passkey-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@Provide()
@Controller("/api/")
export class LoginController extends BaseController {
@@ -27,7 +26,11 @@ export class LoginController extends BaseController {
@Inject()
passkeyService: PasskeyService;
@Post("/login", { description: Constants.per.guest })
getAuditType(): string {
return AuditType.login.value;
}
@Post("/login", { description: Constants.per.guest, summary: "用户名密码登录" })
public async login(
@Body(ALL)
body: any,
@@ -38,16 +41,22 @@ export class LoginController extends BaseController {
if (settings.captchaEnabled === true) {
await this.captchaService.doValidate({ form: body.captcha, must: false, captchaAddonId: settings.captchaAddonId, req: { remoteIp } });
}
const token = await this.loginService.loginByPassword(body);
this.writeTokenCookie(token);
return this.ok(token);
try {
const token = await this.loginService.loginByPassword(body);
this.writeTokenCookie(token);
this.auditLog({ userId: token.userId, username: token.username, content: `用户「${body.username}」登录成功` });
return this.ok(token);
} catch (err: any) {
this.auditLog({ userId: err.userId, username: body.username, content: `用户「${body.username}」登录失败:${err.message}` });
throw err;
}
}
private writeTokenCookie(token: { expire: any; token: any }) {
// this.loginService.writeTokenCookie(this.ctx,token);
}
@Post("/loginBySms", { description: Constants.per.guest })
@Post("/loginBySms", { description: Constants.per.guest, summary: "短信验证码登录" })
public async loginBySms(
@Body(ALL)
body: any
@@ -58,31 +67,42 @@ export class LoginController extends BaseController {
}
checkComm();
const token = await this.loginService.loginBySmsCode({
phoneCode: body.phoneCode,
mobile: body.mobile,
smsCode: body.smsCode,
randomStr: body.randomStr,
inviteCode: body.inviteCode,
});
try {
const token = await this.loginService.loginBySmsCode({
phoneCode: body.phoneCode,
mobile: body.mobile,
smsCode: body.smsCode,
randomStr: body.randomStr,
inviteCode: body.inviteCode,
});
this.writeTokenCookie(token);
return this.ok(token);
this.writeTokenCookie(token);
this.auditLog({ userId: token.userId, username: token.username, content: `用户「${body.mobile}」短信登录成功` });
return this.ok(token);
} catch (err: any) {
this.auditLog({ userId: err.userId, username: body.mobile, content: `用户「${body.mobile}」短信登录失败:${err.message}` });
throw err;
}
}
@Post("/loginByTwoFactor", { description: Constants.per.guest })
@Post("/loginByTwoFactor", { description: Constants.per.guest, summary: "两步验证登录" })
public async loginByTwoFactor(
@Body(ALL)
body: any
) {
const token = await this.loginService.loginByTwoFactor({
loginId: body.loginId,
verifyCode: body.verifyCode,
});
try {
const token = await this.loginService.loginByTwoFactor({
loginId: body.loginId,
verifyCode: body.verifyCode,
});
this.writeTokenCookie(token);
return this.ok(token);
this.writeTokenCookie(token);
this.auditLog({ userId: token.userId, username: token.username, content: `用户「${body.loginId}」两步验证登录成功` });
return this.ok(token);
} catch (err: any) {
this.auditLog({ userId: err.userId, username: body.loginId, content: `用户「${body.loginId}」两步验证登录失败:${err.message}` });
throw err;
}
}
@Post("/passkey/generateAuthentication", { description: Constants.per.guest })
@@ -92,24 +112,30 @@ export class LoginController extends BaseController {
return this.ok(options);
}
@Post("/loginByPasskey", { description: Constants.per.guest })
@Post("/loginByPasskey", { description: Constants.per.guest, summary: "Passkey登录" })
public async loginByPasskey(
@Body(ALL)
body: any
) {
const credential = body.credential;
const challenge = body.challenge;
try {
const credential = body.credential;
const challenge = body.challenge;
const token = await this.loginService.loginByPasskey(
{
credential,
challenge,
},
this.ctx
);
const token = await this.loginService.loginByPasskey(
{
credential,
challenge,
},
this.ctx
);
// this.writeTokenCookie(token);
return this.ok(token);
this.writeTokenCookie(token);
this.auditLog({ userId: token.userId, username: token.username, content: "用户Passkey登录成功" });
return this.ok(token);
} catch (err: any) {
this.auditLog({ userId: err.userId, username: body.credential, content: `用户Passkey登录失败:${err.message}` });
throw err;
}
}
@Post("/logout", { description: Constants.per.authOnly })
@@ -8,6 +8,7 @@ import { LoginService } from "../../../modules/login/service/login-service.js";
import { OauthBoundService } from "../../../modules/login/service/oauth-bound-service.js";
import { AddonGetterService } from "../../../modules/pipeline/service/addon-getter-service.js";
import { UserEntity } from "../../../modules/sys/authority/entity/user.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
import { IOauthProvider } from "../../../plugins/plugin-oauth/api.js";
type OauthProviderSetting = {
@@ -48,6 +49,10 @@ export class ConnectController extends BaseController {
@Inject()
addonService: AddonService;
getAuditType(): string {
return AuditType.login.value;
}
private async getOauthProvider(type: string) {
const publicSettings = await this.sysSettingsService.getPublicSettings();
if (!publicSettings?.oauthEnabled) {
@@ -68,12 +73,11 @@ export class ConnectController extends BaseController {
};
}
@Post("/login", { description: Constants.per.guest })
@Post("/login", { description: Constants.per.guest, summary: "第三方登录" })
public async login(@Body(ALL) body: { type: string; subtype?: string; forType?: string; from?: string }) {
const oauthProvider = await this.getOauthProvider(body.type);
const installInfo = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo);
const bindUrl = installInfo?.bindUrl || "";
//构造登录url
const redirectUrl = `${bindUrl}api/oauth/callback/${body.type}`;
const stateObj = {
@@ -95,8 +99,6 @@ export class ConnectController extends BaseController {
});
this.ctx.cookies.set("oauth_ticket", ticket, {
httpOnly: true,
// secure: true,
// sameSite: "strict",
});
return this.ok({ loginUrl, ticket });
}
@@ -153,7 +155,7 @@ export class ConnectController extends BaseController {
}
}
@Post("/getLogoutUrl", { description: Constants.per.guest })
@Post("/getLogoutUrl", { description: Constants.per.guest, summary: "第三方登出" })
public async logout(@Body(ALL) body: any) {
checkPlus();
const oauthProvider = await this.getOauthProvider(body.type);
@@ -195,7 +197,7 @@ export class ConnectController extends BaseController {
// this.loginService.writeTokenCookie(this.ctx,token);
}
@Post("/autoRegister", { description: Constants.per.guest })
@Post("/autoRegister", { description: Constants.per.guest, summary: "第三方自动注册" })
public async autoRegister(@Body(ALL) body: { validationCode: string; type: string; inviteCode?: string }) {
const validationValue = this.codeService.getValidationValue(body.validationCode);
if (!validationValue) {
@@ -219,12 +221,12 @@ export class ConnectController extends BaseController {
const loginRes = await this.loginService.generateToken(newUser);
this.writeTokenCookie(loginRes);
this.auditLog({ userId: newUser.id, content: `第三方账号自动注册,类型: ${body.type}` });
return this.ok(loginRes);
}
@Post("/bind", { description: Constants.per.loginOnly })
@Post("/bind", { description: Constants.per.loginOnly, summary: "绑定第三方账号" })
public async bind(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
const validationValue = this.codeService.getValidationValue(body.validationCode);
if (!validationValue) {
@@ -238,17 +240,18 @@ export class ConnectController extends BaseController {
type,
openId,
});
this.auditLog({ userId, content: `第三方账号绑定,类型: ${body.type}` });
return this.ok(1);
}
@Post("/unbind", { description: Constants.per.loginOnly })
@Post("/unbind", { description: Constants.per.loginOnly, summary: "解绑第三方账号" })
public async unbind(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
await this.oauthBoundService.unbind({
userId,
type: body.type,
});
this.auditLog({ userId, content: `第三方账号解绑,类型: ${body.type}` });
return this.ok(1);
}
@@ -4,6 +4,7 @@ import { RegisterType } from "../../../modules/sys/authority/service/user-servic
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { checkComm, checkPlus } from "@certd/plus-core";
import { LoginService } from "../../../modules/login/service/login-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
export type RegisterReq = {
type: RegisterType;
@@ -31,7 +32,11 @@ export class RegisterController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Post("/register", { description: Constants.per.guest })
getAuditType(): string {
return AuditType.login.value;
}
@Post("/register", { description: Constants.per.guest, summary: "用户注册" })
public async register(
@Body(ALL)
body: RegisterReq,
@@ -60,6 +65,7 @@ export class RegisterController extends BaseController {
password: body.password,
} as any;
const newUser = await this.loginService.register(body.type, registerUser, body.inviteCode);
this.auditLog({ userId: newUser.id, username: body.username, content: `用户「${body.username}」注册成功` });
return this.ok(newUser);
} else if (body.type === "mobile") {
if (sysPublicSettings.mobileRegisterEnabled === false) {
@@ -80,6 +86,7 @@ export class RegisterController extends BaseController {
password: body.password,
} as any;
const newUser = await this.loginService.register(body.type, registerUser, body.inviteCode);
this.auditLog({ userId: newUser.id, username: body.mobile, content: `用户「${body.mobile}」注册成功` });
return this.ok(newUser);
} else if (body.type === "email") {
if (sysPublicSettings.emailRegisterEnabled === false) {
@@ -97,6 +104,7 @@ export class RegisterController extends BaseController {
password: body.password,
} as any;
const newUser = await this.loginService.register(body.type, registerUser, body.inviteCode);
this.auditLog({ userId: newUser.id, username: body.email, content: `用户「${body.email}」注册成功` });
return this.ok(newUser);
}
}
@@ -1,5 +1,6 @@
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, PlusService, SysInstallInfo, SysSettingsService } from "@certd/lib-server";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
export type PreBindUserReq = {
userId: number;
@@ -18,17 +19,21 @@ export class BasicController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Post("/preBindUser", { description: "sys:settings:edit" })
getAuditType(): string {
return AuditType.account.value;
}
@Post("/preBindUser", { description: "sys:settings:edit", summary: "预绑定用户" })
public async preBindUser(@Body(ALL) body: PreBindUserReq) {
// 设置缓存内容
if (body.userId == null || body.userId <= 0) {
throw new Error("用户ID不能为空");
}
await this.plusService.userPreBind(body.userId);
await this.auditLog({ content: `预绑定了用户(ID:${body.userId})` });
return this.ok({});
}
@Post("/bindUser", { description: "sys:settings:edit" })
@Post("/bindUser", { description: "sys:settings:edit", summary: "绑定用户" })
public async bindUser(@Body(ALL) body: BindUserReq) {
if (body.userId == null || body.userId <= 0) {
throw new Error("用户ID不能为空");
@@ -36,20 +41,23 @@ export class BasicController extends BaseController {
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
installInfo.bindUserId = body.userId;
await this.sysSettingsService.saveSetting(installInfo);
await this.auditLog({ content: `绑定了用户(ID:${body.userId})` });
return this.ok({});
}
@Post("/unbindUser", { description: "sys:settings:edit" })
@Post("/unbindUser", { description: "sys:settings:edit", summary: "解绑用户" })
public async unbindUser() {
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
installInfo.bindUserId = null;
await this.sysSettingsService.saveSetting(installInfo);
await this.auditLog({ content: "解绑了用户" });
return this.ok({});
}
@Post("/updateLicense", { description: "sys:settings:edit" })
@Post("/updateLicense", { description: "sys:settings:edit", summary: "更新许可证" })
public async updateLicense(@Body(ALL) body: { license: string }) {
await this.plusService.updateLicense(body.license);
await this.auditLog({ content: "更新了许可证" });
return this.ok(true);
}
}
@@ -0,0 +1,42 @@
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) {
if (body.query?.scope) {
delete body.query.userId;
}
const pageRet = await this.auditService.page(body);
return this.ok(pageRet);
}
@Post("/delete", { description: Constants.per.authOnly, summary: "删除审计日志" })
async delete(@Query("id") id: number) {
await this.auditService.delete([id]);
return this.ok({});
}
@Post("/clean", { description: Constants.per.authOnly, summary: "清理过期审计日志" })
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(),
});
}
}
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 权限资源
@@ -14,8 +15,11 @@ export class PermissionController extends CrudController<PermissionService> {
getService() {
return this.service;
}
getAuditType(): string {
return AuditType.permission.value;
}
@Post("/page", { description: "sys:auth:per:view" })
@Post("/page", { description: "sys:auth:per:view", summary: "查询权限分页列表" })
async page(
@Body(ALL)
body
@@ -23,30 +27,42 @@ export class PermissionController extends CrudController<PermissionService> {
return await super.page(body);
}
@Post("/add", { description: "sys:auth:per:add" })
@Post("/add", { description: "sys:auth:per:add", summary: "添加权限" })
async add(
@Body(ALL)
bean
) {
return await super.add(bean);
const res = await super.add(bean);
await this.auditLog({
content: `新增了权限「${bean.name}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:auth:per:edit" })
@Post("/update", { description: "sys:auth:per:edit", summary: "更新权限" })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
const res = await super.update(bean);
await this.auditLog({
content: `修改了权限「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/delete", { description: "sys:auth:per:remove" })
@Post("/delete", { description: "sys:auth:per:remove", summary: "删除权限" })
async delete(
@Query("id")
id: number
) {
return await super.delete(id);
const res = await super.delete(id);
await this.auditLog({
content: `删除了权限(ID:${id})`,
});
return res;
}
@Post("/tree", { description: "sys:auth:per:view" })
@Post("/tree", { description: "sys:auth:per:view", summary: "查询权限树" })
async tree() {
const tree = await this.service.tree({});
return this.ok(tree);
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 系统用户
@@ -15,6 +16,10 @@ export class RoleController extends CrudController<RoleService> {
return this.service;
}
getAuditType(): string {
return AuditType.role.value;
}
@Post("/page", { description: "sys:auth:role:view" })
async page(
@Body(ALL)
@@ -29,22 +34,30 @@ export class RoleController extends CrudController<RoleService> {
return this.ok(ret);
}
@Post("/add", { description: "sys:auth:role:add" })
@Post("/add", { description: "sys:auth:role:add", summary: "新增角色" })
async add(
@Body(ALL)
bean
) {
return await super.add(bean);
const res = await super.add(bean);
await this.auditLog({
content: `新增了角色「${bean.name}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:auth:role:edit" })
@Post("/update", { description: "sys:auth:role:edit", summary: "修改角色" })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
const res = await super.update(bean);
await this.auditLog({
content: `修改了角色「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/delete", { description: "sys:auth:role:remove" })
@Post("/delete", { description: "sys:auth:role:remove", summary: "删除角色" })
async delete(
@Query("id")
id: number
@@ -52,7 +65,11 @@ export class RoleController extends CrudController<RoleService> {
if (id === 1) {
throw new Error("不能删除默认的管理员角色");
}
return await super.delete(id);
const res = await super.delete(id);
await this.auditLog({
content: `删除了角色(ID:${id})`,
});
return res;
}
@Post("/getPermissionTree", { description: "sys:auth:role:view" })
@@ -78,9 +95,10 @@ export class RoleController extends CrudController<RoleService> {
* @param roleId
* @param permissionIds
*/
@Post("/authz", { description: "sys:auth:role:edit" })
@Post("/authz", { description: "sys:auth:role:edit", summary: "角色授权" })
async authz(@Body("roleId") roleId, @Body("permissionIds") permissionIds) {
await this.service.authz(roleId, permissionIds);
await this.auditLog({ content: `为角色(ID:${roleId})进行了授权` });
return this.ok(null);
}
}
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 系统用户
@@ -24,6 +25,10 @@ export class UserController extends CrudController<UserService> {
@Inject()
loginService: LoginService;
getAuditType(): string {
return AuditType.user.value;
}
getService() {
return this.service;
}
@@ -92,23 +97,31 @@ export class UserController extends CrudController<UserService> {
return ret;
}
@Post("/add", { description: "sys:auth:user:add" })
@Post("/add", { description: "sys:auth:user:add", summary: "新增用户" })
async add(
@Body(ALL)
bean
) {
return await super.add(bean);
const res = await super.add(bean);
await this.auditLog({
content: `新增了用户「${bean.username}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:auth:user:edit" })
@Post("/update", { description: "sys:auth:user:edit", summary: "修改用户" })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
const res = await super.update(bean);
await this.auditLog({
content: `修改了用户「${bean.username}」(ID:${bean.id})`,
});
return res;
}
@Post("/delete", { description: "sys:auth:user:remove" })
@Post("/delete", { description: "sys:auth:user:remove", summary: "删除用户" })
async delete(
@Query("id")
id: number
@@ -119,19 +132,24 @@ export class UserController extends CrudController<UserService> {
if (id === 3) {
throw new Error("不能删除默认的普通用户角色");
}
return await super.delete(id);
const res = await super.delete(id);
await this.auditLog({
content: `删除了用户(ID:${id})`,
});
return res;
}
/**
* 解除登录锁定
*/
@Post("/unlockBlock", { description: "sys:auth:user:edit" })
@Post("/unlockBlock", { description: "sys:auth:user:edit", summary: "解锁登录锁定" })
public async unlockBlock(@Body("id") id: number) {
const info = await this.service.info(id, ["password"]);
this.loginService.clearCacheOnSuccess(info.username);
if (info.mobile) {
this.loginService.clearCacheOnSuccess(info.mobile);
}
await this.auditLog({ content: `解锁了用户登录锁定(ID:${id})` });
return this.ok(info);
}
@@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { CrudController } from "@certd/lib-server";
import { merge } from "lodash-es";
import { CnameProviderService } from "../../../modules/cname/service/cname-provider-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 授权
@@ -16,6 +17,10 @@ export class CnameRecordController extends CrudController<CnameProviderService>
return this.service;
}
getAuditType(): string {
return AuditType.cname.value;
}
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
@@ -27,7 +32,7 @@ export class CnameRecordController extends CrudController<CnameProviderService>
return super.list(body);
}
@Post("/add", { description: "sys:settings:edit" })
@Post("/add", { description: "sys:settings:edit", summary: "添加CNAME服务" })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
@@ -35,13 +40,17 @@ export class CnameRecordController extends CrudController<CnameProviderService>
};
merge(bean, def);
bean.userId = this.getUserId();
return super.add(bean);
const res = await super.add(bean);
await this.auditLog({ content: `添加了CNAME服务(ID:${res.data})` });
return res;
}
@Post("/update", { description: "sys:settings:edit" })
@Post("/update", { description: "sys:settings:edit", summary: "更新CNAME服务" })
async update(@Body(ALL) bean: any) {
bean.userId = this.getUserId();
return super.update(bean);
const res = await super.update(bean);
await this.auditLog({ content: `更新了CNAME服务(ID:${bean.id})` });
return res;
}
@Post("/info", { description: "sys:settings:view" })
@@ -49,26 +58,31 @@ export class CnameRecordController extends CrudController<CnameProviderService>
return super.info(id);
}
@Post("/delete", { description: "sys:settings:edit" })
@Post("/delete", { description: "sys:settings:edit", summary: "删除CNAME服务" })
async delete(@Query("id") id: number) {
return super.delete(id);
const res = await super.delete(id);
await this.auditLog({ content: `删除了CNAME服务(ID:${id})` });
return res;
}
@Post("/deleteByIds", { description: "sys:settings:edit" })
@Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除CNAME服务" })
async deleteByIds(@Body("ids") ids: number[]) {
const res = await this.service.delete(ids);
await this.auditLog({ content: `批量删除了${ids.length}条CNAME服务` });
return this.ok(res);
}
@Post("/setDefault", { description: "sys:settings:edit" })
@Post("/setDefault", { description: "sys:settings:edit", summary: "设置默认CNAME服务" })
async setDefault(@Body("id") id: number) {
await this.service.setDefault(id);
await this.auditLog({ content: `设置了默认CNAME服务(ID:${id})` });
return this.ok();
}
@Post("/setDisabled", { description: "sys:settings:edit" })
@Post("/setDisabled", { description: "sys:settings:edit", summary: "禁用/启用CNAME服务" })
async setDisabled(@Body("id") id: number, @Body("disabled") disabled: boolean) {
await this.service.setDisabled(id, disabled);
await this.auditLog({ content: `${disabled ? "禁用" : "启用"}了CNAME服务(ID:${id})` });
return this.ok();
}
}
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -15,22 +16,26 @@ export class SysProjectController extends CrudController<ProjectEntity> {
@Inject()
sysSettingsService: SysSettingsService;
getAuditType(): string {
return AuditType.project.value;
}
getService<T>() {
return this.service;
}
@Post("/page", { description: "sys:settings:view" })
@Post("/page", { description: "sys:settings:view", summary: "查询项目分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
return await super.page(body);
}
@Post("/list", { description: "sys:settings:view" })
@Post("/list", { description: "sys:settings:view", summary: "查询项目列表" })
async list(@Body(ALL) body: any) {
return super.list(body);
}
@Post("/add", { description: "sys:settings:edit" })
@Post("/add", { description: "sys:settings:edit", summary: "添加项目" })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
@@ -38,37 +43,57 @@ export class SysProjectController extends CrudController<ProjectEntity> {
};
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({
content: `新增了项目「${bean.name}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:settings:edit" })
@Post("/update", { description: "sys:settings:edit", summary: "更新项目" })
async update(@Body(ALL) bean: any) {
bean.userId = this.getUserId();
return super.update(bean);
const res = await super.update(bean);
await this.auditLog({
content: `修改了项目「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/info", { description: "sys:settings:view" })
@Post("/info", { description: "sys:settings:view", summary: "查询项目详情" })
async info(@Query("id") id: number) {
return super.info(id);
}
@Post("/delete", { description: "sys:settings:edit" })
@Post("/delete", { description: "sys:settings:edit", summary: "删除项目" })
async delete(@Query("id") id: number) {
return super.delete(id);
const res = await super.delete(id);
await this.auditLog({
content: `删除了项目(ID:${id})`,
});
return res;
}
@Post("/deleteByIds", { description: "sys:settings:edit" })
@Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除项目" })
async deleteByIds(@Body("ids") ids: number[]) {
const res = await this.service.delete(ids);
await this.auditLog({
content: `批量删除了${ids.length}个项目`,
});
return this.ok(res);
}
@Post("/setDisabled", { description: "sys:settings:edit" })
@Post("/setDisabled", { description: "sys:settings:edit", summary: "禁用/启用项目" })
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({
content: `${actionText}项目「${project.name}」(ID:${id})`,
});
return this.ok();
}
}
@@ -4,6 +4,7 @@ import { ProjectMemberEntity } from "../../../modules/sys/enterprise/entity/proj
import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js";
import { merge } from "lodash-es";
import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -15,7 +16,6 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
projectService: ProjectService;
@@ -23,18 +23,22 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
return this.service;
}
@Post("/page", { description: "sys:settings:view" })
getAuditType(): string {
return AuditType.enterprise.value;
}
@Post("/page", { description: "sys:settings:view", summary: "查询项目成员分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
return await super.page(body);
}
@Post("/list", { description: "sys:settings:view" })
@Post("/list", { description: "sys:settings:view", summary: "查询项目成员列表" })
async list(@Body(ALL) body: any) {
return super.list(body);
}
@Post("/add", { description: "sys:settings:edit" })
@Post("/add", { description: "sys:settings:edit", summary: "添加项目成员" })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
@@ -47,10 +51,12 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
projectId: bean.projectId,
});
return super.add(bean);
const res = await super.add(bean);
await this.auditLog({ content: `添加了项目成员(ID:${res.data})` });
return res;
}
@Post("/update", { description: "sys:settings:edit" })
@Post("/update", { description: "sys:settings:edit", summary: "更新项目成员" })
async update(@Body(ALL) bean: any) {
if (!bean.id) {
throw new Error("id is required");
@@ -65,10 +71,11 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
permission: bean.permission,
status: bean.status,
});
await this.auditLog({ content: `更新了项目成员(ID:${bean.id})` });
return this.ok(res);
}
@Post("/info", { description: "sys:settings:view" })
@Post("/info", { description: "sys:settings:view", summary: "查询项目成员详情" })
async info(@Query("id") id: number) {
if (!id) {
throw new Error("id is required");
@@ -81,7 +88,7 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
return super.info(id);
}
@Post("/delete", { description: "sys:settings:edit" })
@Post("/delete", { description: "sys:settings:edit", summary: "删除项目成员" })
async delete(@Query("id") id: number) {
if (!id) {
throw new Error("id is required");
@@ -91,10 +98,12 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
userId: this.getUserId(),
projectId: projectId,
});
return super.delete(id);
const res = await super.delete(id);
await this.auditLog({ content: `删除了项目成员(ID:${id})` });
return res;
}
@Post("/deleteByIds", { description: "sys:settings:edit" })
@Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除项目成员" })
async deleteByIds(@Body("ids") ids: number[]) {
for (const id of ids) {
if (!id) {
@@ -108,6 +117,7 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
await this.service.delete(id as any);
}
await this.auditLog({ content: `批量删除了${ids.length}个项目成员` });
return this.ok({});
}
}
@@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { CrudController } from "@certd/lib-server";
import { SiteInfoService } from "../../../modules/monitor/service/site-info-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@Controller("/api/sys/monitor/site")
@@ -14,6 +15,10 @@ export class SysSiteInfoController extends CrudController<SiteInfoService> {
return this.service;
}
getAuditType(): string {
return AuditType.monitor.value;
}
@Post("/page", { description: "sys:settings:view", summary: "管理员查询站点监控分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
@@ -44,12 +49,16 @@ export class SysSiteInfoController extends CrudController<SiteInfoService> {
@Post("/delete", { description: "sys:settings:edit", summary: "管理员删除站点监控" })
async delete(@Query("id") id: number) {
return await super.delete(id);
await super.delete(id);
await this.auditLog({ content: `管理员删除了站点监控(ID:${id})` });
return this.ok();
}
@Post("/batchDelete", { description: "sys:settings:edit", summary: "管理员批量删除站点监控" })
async batchDelete(@Body("ids") ids: number[]) {
const count = ids.length;
await this.service.delete(ids);
await this.auditLog({ content: `管理员批量删除了${count}条站点监控` });
return this.ok();
}
}
@@ -3,6 +3,7 @@ import { CrudController } from "@certd/lib-server";
import { ApiTags } from "@midwayjs/swagger";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { checkPlus } from "@certd/plus-core";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@Controller("/api/sys/pipeline")
@@ -15,6 +16,10 @@ export class SysPipelineController extends CrudController<PipelineService> {
return this.service;
}
getAuditType(): string {
return AuditType.pipeline.value;
}
@Post("/page", { description: "sys:settings:view", summary: "管理员查询用户流水线分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
@@ -41,13 +46,16 @@ export class SysPipelineController extends CrudController<PipelineService> {
@Post("/delete", { description: "sys:settings:edit", summary: "管理员删除用户流水线" })
async delete(@Query("id") id: number) {
await this.service.delete(id);
await this.auditLog({ content: `管理员删除了用户流水线(ID:${id})` });
return this.ok();
}
@Post("/batchDelete", { description: "sys:settings:edit", summary: "管理员批量删除用户流水线" })
async batchDelete(@Body("ids") ids: number[]) {
checkPlus();
const count = ids.length;
await this.service.batchDelete(ids);
await this.auditLog({ content: `管理员批量删除了${count}条用户流水线` });
return this.ok();
}
}
@@ -3,6 +3,7 @@ import { merge } from "lodash-es";
import { CrudController } from "@certd/lib-server";
import { PluginImportReq, PluginService } from "../../../modules/plugin/service/plugin-service.js";
import { CommPluginConfig, PluginConfig, PluginConfigService } from "../../../modules/plugin/service/plugin-config-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 插件
*/
@@ -19,6 +20,10 @@ export class PluginController extends CrudController<PluginService> {
return this.service;
}
getAuditType(): string {
return AuditType.plugin.value;
}
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
@@ -30,19 +35,22 @@ export class PluginController extends CrudController<PluginService> {
return super.list(body);
}
@Post("/add", { description: "sys:settings:edit" })
@Post("/add", { description: "sys:settings:edit", summary: "添加插件" })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
disabled: false,
};
merge(bean, def);
return super.add(bean);
const res = await super.add(bean);
await this.auditLog({ content: `新增了插件「${bean.name}」(ID:${res.data}, 类型:${bean.type})` });
return res;
}
@Post("/update", { description: "sys:settings:edit" })
@Post("/update", { description: "sys:settings:edit", summary: "更新插件" })
async update(@Body(ALL) bean: any) {
const res = await super.update(bean);
await this.auditLog({ content: `修改了插件「${bean.name}」(ID:${bean.id})` });
return res;
}
@@ -51,21 +59,25 @@ export class PluginController extends CrudController<PluginService> {
return super.info(id);
}
@Post("/delete", { description: "sys:settings:edit" })
@Post("/delete", { description: "sys:settings:edit", summary: "删除插件" })
async delete(@Query("id") id: number) {
const res = await this.service.deleteByIds([id]);
await this.auditLog({ content: `删除了插件(ID:${id})` });
return this.ok(res);
}
@Post("/deleteByIds", { description: "sys:settings:edit" })
@Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除插件" })
async deleteByIds(@Body("ids") ids: number[]) {
const res = await this.service.deleteByIds(ids);
await this.auditLog({ content: `批量删除了${ids.length}条插件` });
return this.ok(res);
}
@Post("/setDisabled", { description: "sys:settings:edit" })
@Post("/setDisabled", { description: "sys:settings:edit", summary: "禁用/启用插件" })
async setDisabled(@Body(ALL) body: { id: number; name: string; type: string; disabled: boolean }) {
await this.service.setDisabled(body);
const { id, disabled } = body;
await this.auditLog({ content: `${disabled ? "禁用" : "启用"}了插件(ID:${id})` });
return this.ok();
}
@Post("/getCommPluginConfigs", { description: "sys:settings:view" })
@@ -74,9 +86,10 @@ export class PluginController extends CrudController<PluginService> {
return this.ok(res);
}
@Post("/saveCommPluginConfigs", { description: "sys:settings:edit" })
@Post("/saveCommPluginConfigs", { description: "sys:settings:edit", summary: "保存公共插件配置" })
async saveCommPluginConfigs(@Body(ALL) body: CommPluginConfig) {
const res = await this.pluginConfigService.saveCommPluginConfig(body);
await this.auditLog({ content: "保存了公共插件配置" });
return this.ok(res);
}
@Post("/getPluginByName", { description: "sys:settings:view" })
@@ -88,19 +101,21 @@ export class PluginController extends CrudController<PluginService> {
return this.ok(res);
}
@Post("/saveSetting", { description: "sys:settings:edit" })
@Post("/saveSetting", { description: "sys:settings:edit", summary: "保存插件设置" })
async saveSetting(@Body(ALL) body: PluginConfig) {
const res = await this.pluginConfigService.savePluginConfig(body);
await this.auditLog({ content: "保存了插件设置" });
return this.ok(res);
}
@Post("/import", { description: "sys:settings:edit" })
@Post("/import", { description: "sys:settings:edit", summary: "导入插件" })
async import(@Body(ALL) body: PluginImportReq) {
const res = await this.service.importPlugin(body);
await this.auditLog({ content: "导入了插件配置" });
return this.ok(res);
}
@Post("/export", { description: "sys:settings:edit" })
@Post("/export", { description: "sys:settings:edit", summary: "导出插件" })
async export(@Body("id") id: number) {
const res = await this.service.exportPlugin(id);
return this.ok(res);
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -11,6 +12,10 @@ export class SysSettingsController extends BaseController {
@Inject()
safeService: SafeService;
getAuditType(): string {
return AuditType.settings.value;
}
@Post("/get", { description: "sys:settings:view" })
async safeGet() {
const res = await this.safeService.getSafeSetting();
@@ -22,15 +27,19 @@ 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({
content: "修改了安全设置",
});
return this.ok({});
}
/**
* 立即隐藏
*/
@Post("/hidden", { description: "sys:settings:edit" })
@Post("/hidden", { description: "sys:settings:edit", summary: "立刻隐藏系统" })
async hiddenImmediate() {
await this.safeService.hiddenImmediately();
await this.auditLog({ content: "立刻隐藏了系统" });
return this.ok({});
}
}
@@ -1,4 +1,3 @@
import { getRuntimeDepsService } from "@certd/pipeline";
import { ALL, Body, Controller, Inject, Post, Provide, Query, RequestIP } from "@midwayjs/core";
import { addonRegistry, AddonService, CrudController, SysPrivateSettings, SysPublicSettings, SysSafeSetting, SysSettingsEntity, SysSettingsService } from "@certd/lib-server";
import { cloneDeep, merge } from "lodash-es";
@@ -8,6 +7,8 @@ import { getEmailSettings } from "../../../modules/sys/settings/fix.js";
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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -24,62 +25,78 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
codeService: CodeService;
@Inject()
addonService: AddonService;
@Inject()
runtimeDepsService: RuntimeDepsService;
getService() {
return this.service;
}
@Post("/page", { description: "sys:settings:view" })
getAuditType(): string {
return AuditType.settings.value;
}
@Post("/page", { description: "sys:settings:view", summary: "查询系统设置分页列表" })
async page(@Body(ALL) body) {
return super.page(body);
}
@Post("/list", { description: "sys:settings:view" })
@Post("/list", { description: "sys:settings:view", summary: "查询系统设置列表" })
async list(@Body(ALL) body) {
return super.list(body);
}
@Post("/add", { description: "sys:settings:edit" })
@Post("/add", { description: "sys:settings:edit", summary: "添加系统设置" })
async add(@Body(ALL) bean) {
return super.add(bean);
const res = await super.add(bean);
await this.auditLog({ content: "添加了系统设置" });
return res;
}
@Post("/update", { description: "sys:settings:edit" })
@Post("/update", { description: "sys:settings:edit", summary: "更新系统设置" })
async update(@Body(ALL) bean) {
await this.service.checkUserId(bean.id, this.getUserId());
return super.update(bean);
const res = await super.update(bean);
await this.auditLog({ content: "更新了系统设置" });
return res;
}
@Post("/info", { description: "sys:settings:view" })
@Post("/info", { description: "sys:settings:view", summary: "查询系统设置详情" })
async info(@Query("id") id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.info(id);
}
@Post("/delete", { description: "sys:settings:edit" })
@Post("/delete", { description: "sys:settings:edit", summary: "删除系统设置" })
async delete(@Query("id") id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.delete(id);
const res = await super.delete(id);
await this.auditLog({ content: "删除了系统设置" });
return res;
}
@Post("/save", { description: "sys:settings:edit" })
@Post("/save", { description: "sys:settings:edit", summary: "保存系统设置" })
async save(@Body(ALL) bean: SysSettingsEntity) {
await this.service.save(bean);
await this.auditLog({
content: "修改了系统设置",
});
return this.ok({});
}
@Post("/get", { description: "sys:settings:view" })
@Post("/get", { description: "sys:settings:view", summary: "查询系统设置" })
async get(@Query("key") key: string) {
const entity = await this.service.getByKey(key);
return this.ok(entity);
}
// savePublicSettings
@Post("/getEmailSettings", { description: "sys:settings:view" })
@Post("/getEmailSettings", { description: "sys:settings:view", summary: "查询邮件服务器设置" })
async getEmailSettings(@Body(ALL) body) {
const conf = await getEmailSettings(this.service, this.userSettingsService);
return this.ok(conf);
}
@Post("/getEmailTemplates", { description: "sys:settings:view" })
@Post("/getEmailTemplates", { description: "sys:settings:view", summary: "查询邮件模板列表" })
async getEmailTemplates(@Body(ALL) body) {
const conf = await getEmailSettings(this.service, this.userSettingsService);
const templates = conf.templates || {};
@@ -98,15 +115,16 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
return this.ok(proviers);
}
@Post("/saveEmailSettings", { description: "sys:settings:edit" })
@Post("/saveEmailSettings", { description: "sys:settings:edit", summary: "保存邮件服务器设置" })
async saveEmailSettings(@Body(ALL) body) {
const conf = await getEmailSettings(this.service, this.userSettingsService);
merge(conf, body);
await this.service.saveSetting(conf);
await this.auditLog({ content: "保存了邮件服务器设置" });
return this.ok(conf);
}
@Post("/getSysSettings", { description: "sys:settings:view" })
@Post("/getSysSettings", { description: "sys:settings:view", summary: "查询系统配置" })
async getSysSettings() {
const publicSettings = await this.service.getPublicSettings();
let privateSettings = await this.service.getPrivateSettings();
@@ -115,7 +133,7 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
}
// savePublicSettings
@Post("/saveSysSettings", { description: "sys:settings:edit" })
@Post("/saveSysSettings", { description: "sys:settings:edit", summary: "保存系统设置" })
async saveSysSettings(@Body(ALL) body: { public: SysPublicSettings; private: SysPrivateSettings }) {
const publicSettings = await this.service.getPublicSettings();
const privateSettings = await this.service.getPrivateSettings();
@@ -123,16 +141,18 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
merge(privateSettings, body.private);
await this.service.savePublicSettings(publicSettings);
await this.service.savePrivateSettings(privateSettings);
await this.auditLog({ content: "保存了系统设置" });
return this.ok({});
}
@Post("/stopOtherUserTimer", { description: "sys:settings:edit" })
@Post("/stopOtherUserTimer", { description: "sys:settings:edit", summary: "停止其他用户定时任务" })
async stopOtherUserTimer(@Body(ALL) body) {
await this.pipelineService.stopOtherUserPipeline(1);
await this.auditLog({ content: "停止了其他用户定时任务" });
return this.ok({});
}
@Post("/testProxy", { description: "sys:settings:edit" })
@Post("/testProxy", { description: "sys:settings:edit", summary: "测试代理" })
async testProxy(@Body(ALL) body) {
const google = "https://www.google.com/";
const baidu = "https://www.baidu.com/";
@@ -170,19 +190,19 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
});
}
@Post("/testSms", { description: "sys:settings:edit" })
@Post("/testSms", { description: "sys:settings:edit", summary: "测试短信" })
async testSms(@Body(ALL) body) {
await this.codeService.sendSmsCode(body.phoneCode, body.mobile);
return this.ok({});
}
@Post("/getSmsTypeDefine", { description: "sys:settings:view" })
@Post("/getSmsTypeDefine", { description: "sys:settings:view", summary: "查询短信类型定义" })
async getSmsTypeDefine(@Body("type") type: string) {
const define = await SmsServiceFactory.getDefine(type);
return this.ok(define);
}
@Post("/safe/get", { description: "sys:settings:view" })
@Post("/safe/get", { description: "sys:settings:view", summary: "查询安全设置" })
async safeGet() {
const res = await this.service.getSetting<SysSafeSetting>(SysSafeSetting);
const clone: SysSafeSetting = cloneDeep(res);
@@ -190,7 +210,7 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
return this.ok(clone);
}
@Post("/safe/save", { description: "sys:settings:edit" })
@Post("/safe/save", { description: "sys:settings:edit", summary: "保存安全设置" })
async safeSave(@Body(ALL) body: any) {
if (body.hidden.openPassword) {
body.hidden.openPassword = utils.hash.md5(body.hidden.openPassword);
@@ -202,24 +222,26 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
throw new Error("首次设置需要填写解锁密码");
}
await this.service.saveSetting(blankSetting);
await this.auditLog({ content: "保存了安全设置" });
return this.ok({});
}
@Post("/captchaTest", { description: "sys:settings:edit" })
@Post("/captchaTest", { description: "sys:settings:edit", summary: "测试验证码" })
async captchaTest(@Body(ALL) body: any, @RequestIP() remoteIp: string) {
await this.codeService.checkCaptcha(body, { remoteIp });
return this.ok({});
}
@Post("/oauth/providers", { description: "sys:settings:view" })
@Post("/oauth/providers", { description: "sys:settings:view", summary: "查询OAuth提供商列表" })
async oauthProviders() {
const list = await addonRegistry.getDefineList("oauth");
return this.ok(list);
}
@Post("/clearRuntimeDeps", { description: "sys:settings:edit" })
@Post("/clearRuntimeDeps", { description: "sys:settings:edit", summary: "清除运行时依赖" })
async clearRuntimeDeps() {
await getRuntimeDepsService().clearRuntimeDeps();
await this.runtimeDepsService.clearRuntimeDeps();
await this.auditLog({ content: "清除了运行时依赖" });
return this.ok(true);
}
}
@@ -5,6 +5,7 @@ import { checkPlus } from "@certd/plus-core";
import { http, logger, utils } from "@certd/basic";
import { TaskServiceBuilder } from "../../../modules/pipeline/service/getter/task-service-getter.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* Addon
@@ -24,6 +25,10 @@ export class AddonController extends CrudController<AddonService> {
return this.service;
}
getAuditType(): string {
return AuditType.addon.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询Addon分页列表" })
async page(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -68,7 +73,9 @@ export class AddonController extends CrudController<AddonService> {
if (define.needPlus) {
checkPlus();
}
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了Addon「${bean.name}」(ID:${res.data}, 类型:${bean.type})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新Addon" })
@@ -91,7 +98,9 @@ export class AddonController extends CrudController<AddonService> {
}
delete bean.userId;
delete bean.projectId;
return super.update(bean);
const res = await super.update(bean);
this.auditLog({ content: `修改了Addon「${bean.name}」(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询Addon详情" })
@@ -103,7 +112,9 @@ export class AddonController extends CrudController<AddonService> {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除Addon" })
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({ content: `删除了Addon(ID:${id})` });
return res;
}
@Post("/define", { description: Constants.per.authOnly, summary: "查询Addon插件定义" })
@@ -158,6 +169,7 @@ export class AddonController extends CrudController<AddonService> {
async setDefault(@Query("addonType") addonType: string, @Query("id") id: number) {
const { projectId, userId } = await this.checkOwner(this.getService(), id, "write", true);
const res = await this.service.setDefault(id, userId, addonType, projectId);
this.auditLog({ content: `设置了默认Addon(ID:${id})` });
return this.ok(res);
}
@@ -0,0 +1,41 @@
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 { projectId, userId } = await this.getProjectUserIdRead();
const query: any = {};
if (projectId) {
//如果是项目级别,排除userId参数,因为日志这里userId不是-1 ,而是实际的用户
query.projectId = projectId;
} else {
query.userId = userId;
}
body.query = {
...(body.query || {}),
...query,
scope: "user",
};
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(),
});
}
}
@@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { GroupService } from "../../../modules/basic/service/group-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -20,6 +21,10 @@ export class GroupController extends CrudController<GroupService> {
return this.service;
}
getAuditType(): string {
return AuditType.pipelineGroup.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询分组分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -52,7 +57,9 @@ export class GroupController extends CrudController<GroupService> {
const { projectId, userId } = await this.getProjectUserIdRead();
bean.projectId = projectId;
bean.userId = userId;
return await super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了分组「${bean.name}」(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新分组" })
@@ -60,7 +67,9 @@ export class GroupController extends CrudController<GroupService> {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
delete bean.projectId;
return await super.update(bean);
const res = await super.update(bean);
this.auditLog({ content: `修改了分组「${bean.name}」(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询分组详情" })
async info(@Query("id") id: number) {
@@ -71,7 +80,9 @@ export class GroupController extends CrudController<GroupService> {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除分组" })
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({ content: `删除了分组(ID:${id})` });
return res;
}
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有分组" })
@@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { Constants, CrudController } from "@certd/lib-server";
import { ApiTags } from "@midwayjs/swagger";
import { CertApplyTemplateService } from "../../../modules/cert/service/cert-apply-template-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@Controller("/api/cert/apply-template")
@@ -14,6 +15,10 @@ export class CertApplyTemplateController extends CrudController<CertApplyTemplat
return this.service;
}
getAuditType(): string {
return AuditType.certTemplate.value;
}
private removeContent(data: any) {
const records = Array.isArray(data) ? data : data?.records;
if (!records) {
@@ -53,7 +58,9 @@ export class CertApplyTemplateController extends CrudController<CertApplyTemplat
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.projectId = projectId;
bean.userId = userId;
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了证书参数模版「${bean.name}」(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新证书申请参数模版" })
@@ -61,7 +68,9 @@ export class CertApplyTemplateController extends CrudController<CertApplyTemplat
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({ content: `修改了证书参数模版「${bean.name}」(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询证书申请参数模版详情" })
@@ -73,13 +82,17 @@ export class CertApplyTemplateController extends CrudController<CertApplyTemplat
@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({ content: `删除了证书参数模版(ID:${id})` });
return res;
}
@Post("/setDefault", { description: Constants.per.authOnly, summary: "设置默认证书申请参数模版" })
async setDefault(@Body("id") id: number) {
const { projectId, userId } = await this.getProjectUserIdWrite();
return this.ok(await this.service.setDefault(id, userId, projectId));
const defaultId = await this.service.setDefault(id, userId, projectId);
this.auditLog({ content: `设置了默认证书参数模版(ID:${id})` });
return this.ok(defaultId);
}
@Post("/default", { description: Constants.per.authOnly, summary: "查询默认证书申请参数模版" })
@@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { Constants, CrudController } from "@certd/lib-server";
import { ApiTags } from "@midwayjs/swagger";
import { DnsPersistRecordService } from "../../../modules/cert/service/dns-persist-record-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@Controller("/api/cert/dns-persist")
@@ -14,6 +15,10 @@ export class DnsPersistRecordController extends CrudController<DnsPersistRecordS
return this.service;
}
getAuditType(): string {
return AuditType.dnsPersist.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询DNS持久验证记录分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -28,7 +33,9 @@ export class DnsPersistRecordController extends CrudController<DnsPersistRecordS
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.projectId = projectId;
bean.userId = userId;
return super.add(bean);
const res = await this.getService().add(bean);
this.auditLog({ content: `新增了DNS持久验证记录「${bean.domain}」(ID:${res.id})` });
return this.ok(res);
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新DNS持久验证记录" })
@@ -36,7 +43,9 @@ export class DnsPersistRecordController extends CrudController<DnsPersistRecordS
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({ content: `修改了DNS持久验证记录(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询DNS持久验证记录详情" })
@@ -49,6 +58,7 @@ export class DnsPersistRecordController extends CrudController<DnsPersistRecordS
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
await this.service.delete(id as any);
this.auditLog({ content: `删除了DNS持久验证记录(ID:${id})` });
return this.ok({
message: this.service.lastDeleteMessage,
});
@@ -80,12 +90,16 @@ export class DnsPersistRecordController extends CrudController<DnsPersistRecordS
@Post("/triggerVerify", { description: Constants.per.authOnly, summary: "后台验证DNS持久验证记录" })
async triggerVerify(@Body(ALL) body: { id: number }) {
await this.checkOwner(this.getService(), body.id, "write");
return this.ok(await this.service.triggerVerify(body.id));
const res = await this.service.triggerVerify(body.id);
this.auditLog({ content: `触发了DNS持久验证(ID:${body.id})` });
return this.ok(res);
}
@Post("/createTxt", { description: Constants.per.authOnly, summary: "一键创建DNS持久验证TXT记录" })
async createTxt(@Body(ALL) body: { id: number; dnsProviderType?: string; dnsProviderAccess?: number }) {
await this.checkOwner(this.getService(), body.id, "write");
return this.ok(await this.service.createDnsTxt(body));
const res = await this.service.createDnsTxt(body);
this.auditLog({ content: `一键创建了DNS持久验证TXT记录(ID:${body.id})` });
return this.ok(res);
}
}
@@ -4,6 +4,7 @@ import { DomainService } from "../../../modules/cert/service/domain-service.js";
import { checkPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
import { parseDomainByPsl } from "@certd/plugin-lib";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -19,6 +20,10 @@ export class DomainController extends CrudController<DomainService> {
return this.service;
}
getAuditType(): string {
return AuditType.domain.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询域名分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -58,7 +63,9 @@ export class DomainController extends CrudController<DomainService> {
const { projectId, userId } = await this.getProjectUserIdRead();
bean.projectId = projectId;
bean.userId = userId;
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了域名「${bean.domain}` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新域名" })
@@ -66,7 +73,9 @@ export class DomainController extends CrudController<DomainService> {
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({ content: `修改了域名「${bean.domain}` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询域名详情" })
@@ -78,13 +87,16 @@ export class DomainController extends CrudController<DomainService> {
@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({ content: `删除了域名(ID:${id})` });
return res;
}
@Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除域名" })
async deleteByIds(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
await this.service.batchDelete(body.ids, userId, projectId);
this.auditLog({ content: `批量删除了${body.ids.length}条域名` });
return this.ok();
}
@@ -99,6 +111,7 @@ export class DomainController extends CrudController<DomainService> {
projectId: projectId,
};
await this.service.startDomainImportTask(req);
this.auditLog({ content: "开始了域名导入任务" });
return this.ok();
}
@@ -123,6 +136,7 @@ export class DomainController extends CrudController<DomainService> {
key,
};
await this.service.deleteDomainImportTask(req);
this.auditLog({ content: "删除了域名导入任务" });
return this.ok();
}
@@ -139,6 +153,7 @@ export class DomainController extends CrudController<DomainService> {
key,
};
const item = await this.service.saveDomainImportTask(req);
this.auditLog({ content: "保存了域名导入任务" });
return this.ok(item);
}
@@ -149,6 +164,7 @@ export class DomainController extends CrudController<DomainService> {
userId: userId,
projectId: projectId,
});
this.auditLog({ content: "开始了同步域名过期时间任务" });
return this.ok();
}
@Post("/sync/expiration/status", { description: Constants.per.authOnly, summary: "查询同步域名过期时间任务状态" })
@@ -169,6 +185,7 @@ export class DomainController extends CrudController<DomainService> {
projectId: projectId,
setting: { ...body },
});
this.auditLog({ content: "保存了域名监控设置" });
return this.ok();
}
@@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { Constants, CrudController } from "@certd/lib-server";
import { CnameRecordService } from "../../../modules/cname/service/cname-record-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -17,6 +18,10 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
return this.service;
}
getAuditType(): string {
return AuditType.cname.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询CNAME记录分页列表" })
async page(@Body(ALL) body: any) {
const { userId, projectId } = await this.getProjectUserIdRead();
@@ -56,7 +61,9 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
const { userId, projectId } = await this.getProjectUserIdWrite();
bean.userId = userId;
bean.projectId = projectId;
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了CNAME记录「${bean.domain}` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新CNAME记录" })
@@ -64,7 +71,9 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
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({ content: `修改了CNAME记录(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询CNAME记录详情" })
@@ -76,13 +85,16 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除CNAME记录" })
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({ content: `删除了CNAME记录(ID:${id})` });
return res;
}
@Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除CNAME记录" })
async deleteByIds(@Body(ALL) body: any) {
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(body.ids, userId, projectId);
this.auditLog({ content: `批量删除了${body.ids.length}条CNAME记录` });
return this.ok();
}
@Post("/getByDomain", { description: Constants.per.authOnly, summary: "根据域名获取CNAME记录" })
@@ -103,6 +115,7 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
async resetStatus(@Body(ALL) body: { id: number }) {
await this.checkOwner(this.getService(), body.id, "read");
const res = await this.service.resetStatus(body.id);
this.auditLog({ content: `重置了CNAME记录状态(ID:${body.id})` });
return this.ok(res);
}
@Post("/import", { description: Constants.per.authOnly, summary: "导入CNAME记录" })
@@ -114,6 +127,7 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
domainList: body.domainList,
cnameProviderId: body.cnameProviderId,
});
this.auditLog({ append: `提交${res.count}` });
return this.ok(res);
}
}
@@ -4,6 +4,7 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service
import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js";
import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -24,6 +25,10 @@ export class UserProjectController extends BaseController {
return this.service;
}
getAuditType(): string {
return AuditType.enterprise.value;
}
/**
* @param body
* @returns
@@ -63,6 +68,7 @@ export class UserProjectController extends BaseController {
async applyJoin(@Body(ALL) body: any) {
const userId = this.getUserId();
const res = await this.service.applyJoin({ userId, projectId: body.projectId });
this.auditLog({ content: "申请了加入项目" });
return this.ok(res);
}
@@ -84,6 +90,7 @@ export class UserProjectController extends BaseController {
status,
permission,
});
this.auditLog({ content: "更新了项目成员" });
return this.ok(res);
}
@@ -92,6 +99,7 @@ export class UserProjectController extends BaseController {
const { projectId } = await this.getProjectUserIdAdmin();
const { status, permission, userId } = body;
const res = await this.service.approveJoin({ userId, projectId: projectId, status, permission });
this.auditLog({ content: "审批了加入项目申请" });
return this.ok(res);
}
@@ -100,8 +108,9 @@ export class UserProjectController extends BaseController {
const { projectId } = await this.getProjectUserIdAdmin();
await this.projectMemberService.deleteWhere({
projectId,
userId: this.getUserId(),
userId: body.userId,
});
this.auditLog({ content: "删除了项目成员" });
return this.ok();
}
@@ -113,6 +122,7 @@ export class UserProjectController extends BaseController {
projectId,
userId,
});
this.auditLog({ content: "离开了项目" });
return this.ok();
}
}
@@ -5,6 +5,7 @@ import { ProjectMemberService } from "../../../modules/sys/enterprise/service/pr
import { merge } from "lodash-es";
import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@Provide()
@@ -24,6 +25,10 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
return this.service;
}
getAuditType(): string {
return AuditType.enterprise.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询项目成员分页列表" })
async page(@Body(ALL) body: any) {
const { projectId } = await this.getProjectUserIdRead();
@@ -53,7 +58,9 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
projectId: bean.projectId,
});
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了项目成员(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新项目成员" })
@@ -71,7 +78,7 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
permission: bean.permission,
status: bean.status,
});
this.auditLog({ content: `修改了项目成员(ID:${bean.id})` });
return this.ok(res);
}
@@ -98,7 +105,9 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
userId: this.getUserId(),
projectId: projectId,
});
return super.delete(id);
const res = await super.delete(id);
this.auditLog({ content: `删除了项目成员(ID:${id})` });
return res;
}
@Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除项目成员" })
@@ -115,6 +124,7 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
await this.service.delete(id as any);
}
this.auditLog({ content: `批量删除了${ids.length}条项目成员` });
return this.ok({});
}
}
@@ -2,6 +2,7 @@ import { BaseController, Constants } from "@certd/lib-server";
import { Controller, Inject, Post, Provide } from "@midwayjs/core";
import { TransferService } from "../../../modules/sys/enterprise/service/transfer-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -16,6 +17,10 @@ export class TransferController extends BaseController {
return this.service;
}
getAuditType(): string {
return AuditType.enterprise.value;
}
/**
*
* @param body
@@ -38,6 +43,7 @@ export class TransferController extends BaseController {
const { projectId } = await this.getProjectUserIdRead();
const userId = this.getUserId();
await this.service.transferAll(userId, projectId);
this.auditLog({ content: "迁移了项目资源" });
return this.ok();
}
}
@@ -3,6 +3,7 @@ import { BaseController } from "@certd/lib-server";
import { Constants } from "@certd/lib-server";
import { EmailService } from "../../../modules/basic/service/email-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -13,10 +14,15 @@ export class EmailController extends BaseController {
@Inject()
emailService: EmailService;
getAuditType(): string {
return AuditType.mine.value;
}
@Post("/test", { description: Constants.per.authOnly, summary: "测试邮件发送" })
public async test(@Body("receiver") receiver) {
const userId = super.getUserId();
await this.emailService.test(userId, receiver);
this.auditLog({ content: "测试了邮件发送" });
return this.ok({});
}
@@ -31,6 +37,7 @@ export class EmailController extends BaseController {
public async add(@Body("email") email) {
const userId = super.getUserId();
await this.emailService.add(userId, email);
this.auditLog({ content: "添加了邮件" });
return this.ok({});
}
@@ -38,6 +45,7 @@ export class EmailController extends BaseController {
public async delete(@Body("email") email) {
const userId = super.getUserId();
await this.emailService.delete(userId, email);
this.auditLog({ content: "删除了邮件" });
return this.ok({});
}
}
@@ -9,6 +9,7 @@ import { http, logger, utils } from "@certd/basic";
import { ApiTags } from "@midwayjs/swagger";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { EmailService } from "../../../modules/basic/service/email-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
import { TaskServiceBuilder } from "../../../modules/pipeline/service/getter/task-service-getter.js";
/**
@@ -41,6 +42,9 @@ export class MineController extends BaseController {
@Inject()
emailService: EmailService;
getAuditType(): string {
return AuditType.mine.value;
}
@Inject()
taskServiceBuilder: TaskServiceBuilder;
@@ -77,6 +81,7 @@ export class MineController extends BaseController {
public async changePassword(@Body(ALL) body: any) {
const userId = this.getUserId();
await this.userService.changePassword(userId, body);
this.auditLog({ content: "修改了密码" });
return this.ok({});
}
@@ -84,6 +89,7 @@ export class MineController extends BaseController {
public async initPassword(@Body(ALL) body: any) {
const userId = this.getUserId();
await this.userService.initPassword(userId, body);
this.auditLog({ content: "初始化了密码" });
return this.ok({});
}
@@ -95,6 +101,7 @@ export class MineController extends BaseController {
avatar: body.avatar,
nickName: body.nickName,
});
this.auditLog({ content: "更新了个人资料" });
return this.ok({});
}
@@ -133,6 +140,7 @@ export class MineController extends BaseController {
phoneCode: body.phoneCode,
mobile: body.mobile,
});
this.auditLog({ content: "修改了手机号" });
return this.ok({});
}
@@ -149,6 +157,7 @@ export class MineController extends BaseController {
await this.userService.updateEmail(userId, {
email: body.email,
});
this.auditLog({ content: "修改了邮箱" });
return this.ok({});
}
@@ -204,6 +213,7 @@ export class MineController extends BaseController {
}),
});
this.auditLog({ content: "初始化了Let's Encrypt ACME账号和邮件通知" });
return this.ok({ success: true });
}
}
@@ -3,6 +3,7 @@ import { PasskeyService } from "../../../modules/login/service/passkey-service.j
import { BaseController, Constants } from "@certd/lib-server";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@Controller("/api/mine/passkey")
@@ -14,6 +15,10 @@ export class MinePasskeyController extends BaseController {
@Inject()
userService: UserService;
getAuditType(): string {
return AuditType.mine.value;
}
@Post("/generateRegistration", { description: Constants.per.authOnly, summary: "生成Passkey注册选项" })
public async generateRegistration(
@Body(ALL)
@@ -46,7 +51,7 @@ export class MinePasskeyController extends BaseController {
const deviceName = body.deviceName;
const result = await this.passkeyService.registerPasskey(userId, response, challenge, deviceName, this.ctx);
this.auditLog({ content: "验证注册了Passkey" });
return this.ok(result);
}
@@ -62,6 +67,7 @@ export class MinePasskeyController extends BaseController {
const result = await this.passkeyService.registerPasskey(userId, response, challenge, deviceName, this.ctx);
this.auditLog({ content: "注册了Passkey" });
return this.ok(result);
}
@@ -90,6 +96,7 @@ export class MinePasskeyController extends BaseController {
}
await this.passkeyService.delete([passkey.id]);
this.auditLog({ content: "解绑了Passkey" });
return this.ok({});
}
}
@@ -6,6 +6,7 @@ import { merge } from "lodash-es";
import { TwoFactorService } from "../../../modules/mine/service/two-factor-service.js";
import { isPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -19,6 +20,10 @@ export class UserTwoFactorSettingController extends BaseController {
@Inject()
twoFactorService: TwoFactorService;
getAuditType(): string {
return AuditType.mine.value;
}
@Post("/get", { description: Constants.per.authOnly, summary: "获取双因子认证设置" })
async get() {
const userId = this.getUserId();
@@ -42,6 +47,7 @@ export class UserTwoFactorSettingController extends BaseController {
}
await this.service.saveSetting(userId, null, setting);
this.auditLog({ content: "保存了双因子认证设置" });
return this.ok({});
}
@@ -62,6 +68,7 @@ export class UserTwoFactorSettingController extends BaseController {
userId,
verifyCode: bean.verifyCode,
});
this.auditLog({ content: "保存了验证器设置" });
return this.ok();
}
@@ -69,6 +76,7 @@ export class UserTwoFactorSettingController extends BaseController {
async authenticatorOff() {
const userId = this.getUserId();
await this.twoFactorService.offAuthenticator(userId);
this.auditLog({ content: "关闭了验证器" });
return this.ok();
}
}
@@ -6,6 +6,7 @@ import { UserGrantSetting } from "../../../modules/mine/service/models.js";
import { isPlus } from "@certd/plus-core";
import { merge } from "lodash-es";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -20,6 +21,10 @@ export class UserSettingsController extends CrudController<UserSettingsService>
return this.service;
}
getAuditType(): string {
return AuditType.mine.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询用户设置分页列表" })
async page(@Body(ALL) body) {
body.query = body.query ?? {};
@@ -62,6 +67,7 @@ export class UserSettingsController extends CrudController<UserSettingsService>
async save(@Body(ALL) bean: UserSettingsEntity) {
bean.userId = this.getUserId();
await this.service.save(bean);
this.auditLog({ content: "保存了用户设置" });
return this.ok({});
}
@@ -88,6 +94,7 @@ export class UserSettingsController extends CrudController<UserSettingsService>
merge(setting, bean);
await this.service.saveSetting(userId, null, setting);
this.auditLog({ content: "保存了授权设置" });
return this.ok({});
}
}
@@ -8,6 +8,7 @@ import { logger } from "@certd/basic";
import dayjs from "dayjs";
import { ApiTags } from "@midwayjs/swagger";
import { CertReader } from "@certd/plugin-lib";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -29,6 +30,10 @@ export class CertInfoController extends CrudController<CertInfoService> {
return this.service;
}
getAuditType(): string {
return AuditType.monitor.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询证书分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
@@ -117,7 +122,9 @@ export class CertInfoController extends CrudController<CertInfoService> {
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.projectId = projectId;
bean.userId = userId;
return await super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了证书「${bean.domain}」(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新证书" })
@@ -125,7 +132,9 @@ export class CertInfoController extends CrudController<CertInfoService> {
await this.checkOwner(this.service, bean.id, "write");
delete bean.userId;
delete bean.projectId;
return await super.update(bean);
const res = await super.update(bean);
this.auditLog({ content: `修改了证书(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询证书详情" })
async info(@Query("id") id: number) {
@@ -136,7 +145,9 @@ export class CertInfoController extends CrudController<CertInfoService> {
@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({ content: `删除了证书(ID:${id})` });
return res;
}
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有证书" })
@@ -4,6 +4,7 @@ import { ApiTags } from "@midwayjs/swagger";
import { SiteInfoService } from "../../../modules/monitor/index.js";
import { JobHistoryService } from "../../../modules/monitor/service/job-history-service.js";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -22,6 +23,10 @@ export class JobHistoryController extends CrudController<JobHistoryService> {
return this.service;
}
getAuditType(): string {
return AuditType.jobHistory.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询监控运行历史分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -54,12 +59,15 @@ export class JobHistoryController extends CrudController<JobHistoryService> {
@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({ content: `删除了监控运行历史(ID:${id})` });
return res;
}
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除监控运行历史" })
async batchDelete(@Body("ids") ids: number[]) {
const { projectId, userId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(ids, userId, projectId);
this.auditLog({ content: `批量删除了${ids.length}条监控运行历史` });
return this.ok();
}
}
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -20,11 +21,14 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
authService: AuthService;
@Inject()
siteIpService: SiteIpService;
getService(): SiteInfoService {
return this.service;
}
getAuditType(): string {
return AuditType.monitor.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询站点监控分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
@@ -75,6 +79,9 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
if (entity.disabled) {
this.service.check(entity.id, true, 0);
}
this.auditLog({
content: `新增了站点监控「${bean.name}」(ID:${res.id}, 域名:${bean.domain})`,
});
return this.ok(res);
}
@@ -88,6 +95,9 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
if (entity.disabled) {
this.service.check(entity.id, true, 0);
}
this.auditLog({
content: `修改了站点监控「${bean.name}」(ID:${bean.id})`,
});
return this.ok();
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询站点监控详情" })
@@ -99,13 +109,20 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
@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({
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);
const count = await this.service.batchDelete(body.ids, userId, projectId);
this.auditLog({
content: `批量删除了${count}条站点监控`,
});
return this.ok();
}
@@ -133,6 +150,7 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
userId,
projectId,
});
this.auditLog({ content: "导入了站点监控" });
return this.ok();
}
@@ -170,6 +188,7 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
projectId: projectId,
key,
});
this.auditLog({ content: "删除了站点监控导入任务" });
return this.ok();
}
@@ -182,6 +201,7 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
userId: userId,
projectId: projectId,
});
this.auditLog({ content: "开始了站点监控导入任务" });
return this.ok();
}
@@ -4,6 +4,7 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service
import { SiteIpService } from "../../../modules/monitor/service/site-ip-service.js";
import { SiteInfoService } from "../../../modules/monitor/index.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -22,6 +23,10 @@ export class SiteInfoController extends CrudController<SiteIpService> {
return this.service;
}
getAuditType(): string {
return AuditType.siteIp.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询站点IP分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -57,6 +62,7 @@ export class SiteInfoController extends CrudController<SiteIpService> {
const { domain, httpsPort } = siteEntity;
this.service.check(res.id, domain, httpsPort);
}
this.auditLog({ content: `新增了站点IP「${bean.ipAddress}」(ID:${res.id})` });
return this.ok(res);
}
@@ -71,6 +77,7 @@ export class SiteInfoController extends CrudController<SiteIpService> {
const { domain, httpsPort } = siteEntity;
this.service.check(siteEntity.id, domain, httpsPort);
}
this.auditLog({ content: `修改了站点IP(ID:${bean.id})` });
return this.ok();
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询站点IP详情" })
@@ -85,6 +92,7 @@ export class SiteInfoController extends CrudController<SiteIpService> {
const entity = await this.service.info(id);
const res = await super.delete(id);
await this.service.updateIpCount(entity.siteId);
this.auditLog({ content: `删除了站点IP「${entity.ipAddress}」(ID:${id})` });
return res;
}
@@ -124,6 +132,7 @@ export class SiteInfoController extends CrudController<SiteIpService> {
siteId: body.siteId,
projectId,
});
this.auditLog({ content: "导入了站点IP" });
return this.ok();
}
}
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -14,11 +15,14 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
service: OpenKeyService;
@Inject()
authService: AuthService;
getService(): OpenKeyService {
return this.service;
}
getAuditType(): string {
return AuditType.openKey.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询开放API密钥分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -57,6 +61,9 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
body.projectId = projectId;
body.userId = userId;
const res = await this.service.add(body);
this.auditLog({
content: `新增了API密钥(ID:${res.id}, scope:${body.scope})`,
});
return this.ok(res);
}
@@ -66,6 +73,9 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
delete bean.userId;
delete bean.projectId;
await this.service.update(bean);
this.auditLog({
content: `修改了API密钥(ID:${bean.id})`,
});
return this.ok();
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询开放API密钥详情" })
@@ -90,7 +100,11 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
@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({
content: `删除了API密钥(ID:${id})`,
});
return res;
}
@Post("/getApiToken", { description: Constants.per.authOnly, summary: "获取API测试令牌" })
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -16,11 +17,14 @@ export class AccessController extends CrudController<AccessService> {
service: AccessService;
@Inject()
authService: AuthService;
getService(): AccessService {
return this.service;
}
getAuditType(): string {
return AuditType.access.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询授权配置分页列表" })
async page(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -58,7 +62,11 @@ export class AccessController extends CrudController<AccessService> {
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.userId = userId;
bean.projectId = projectId;
return super.add(bean);
const res = await super.add(bean);
this.auditLog({
content: `新增了授权「${bean.name}」(ID:${res.data}, 类型:${bean.type})`,
});
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新授权配置" })
@@ -66,7 +74,11 @@ export class AccessController extends CrudController<AccessService> {
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({
content: `修改了授权「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询授权配置详情" })
async info(@Query("id") id: number) {
@@ -77,7 +89,11 @@ export class AccessController extends CrudController<AccessService> {
@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({
content: `删除了授权(ID:${id})`,
});
return res;
}
@Post("/define", { description: Constants.per.authOnly, summary: "查询授权插件定义" })
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -17,11 +18,14 @@ export class NotificationController extends CrudController<NotificationService>
service: NotificationService;
@Inject()
authService: AuthService;
getService(): NotificationService {
return this.service;
}
getAuditType(): string {
return AuditType.notification.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询通知配置分页列表" })
async page(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -62,7 +66,11 @@ export class NotificationController extends CrudController<NotificationService>
if (define.needPlus) {
checkPlus();
}
return super.add(bean);
const res = await super.add(bean);
this.auditLog({
content: `新增了通知配置「${bean.name}」(ID:${res.data}, 类型:${bean.type})`,
});
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新通知配置" })
@@ -84,7 +92,11 @@ export class NotificationController extends CrudController<NotificationService>
}
delete bean.userId;
delete bean.projectId;
return super.update(bean);
const res = await super.update(bean);
this.auditLog({
content: `修改了通知配置「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询通知配置详情" })
async info(@Query("id") id: number) {
@@ -95,7 +107,11 @@ export class NotificationController extends CrudController<NotificationService>
@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({
content: `删除了通知配置(ID:${id})`,
});
return res;
}
@Post("/define", { description: Constants.per.authOnly, summary: "查询通知插件定义" })
@@ -154,6 +170,7 @@ export class NotificationController extends CrudController<NotificationService>
const { projectId, userId } = await this.getProjectUserIdRead();
await this.checkOwner(this.getService(), id, "write");
const res = await this.service.setDefault(id, userId, projectId);
this.auditLog({ content: `设置了默认通知配置(ID:${id})` });
return this.ok(res);
}
@@ -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 } from "../../../modules/sys/enterprise/service/audit-constants.js";
const pipelineExample = `
// 流水线配置示例,实际传送时要去掉注释
@@ -127,6 +128,10 @@ export class PipelineController extends CrudController<PipelineService> {
return this.service;
}
getAuditType(): string {
return AuditType.pipeline.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线分页列表" })
async page(@Body(ALL) body) {
const isAdmin = await this.authService.isAdmin(this.ctx);
@@ -196,7 +201,8 @@ export class PipelineController extends CrudController<PipelineService> {
@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 +212,20 @@ export class PipelineController extends CrudController<PipelineService> {
}
if (!this.isAdmin()) {
// 非管理员用户 不允许设置流水线有效期
delete bean.validTime;
}
const { version } = await this.service.save(bean as any);
//是否增加证书监控
const title = bean.title;
this.auditLog({
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 +240,9 @@ export class PipelineController extends CrudController<PipelineService> {
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
await this.service.delete(id);
this.auditLog({
content: `删除了流水线(ID:${id})`,
});
return this.ok({});
}
@@ -239,6 +252,7 @@ export class PipelineController extends CrudController<PipelineService> {
delete bean.userId;
delete bean.projectId;
await this.service.disabled(bean.id, bean.disabled);
this.auditLog({ content: `${bean.disabled ? "禁用" : "启用"}了流水线(ID:${bean.id})` });
return this.ok({});
}
@@ -253,6 +267,9 @@ export class PipelineController extends CrudController<PipelineService> {
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({
content: `手动执行了流水线(ID:${id})`,
});
return this.ok({});
}
@@ -260,6 +277,9 @@ export class PipelineController extends CrudController<PipelineService> {
async cancel(@Query("historyId") historyId: number) {
await this.checkOwner(this.historyService, historyId, "write", true);
await this.service.cancel(historyId);
this.auditLog({
content: `取消了流水线执行(historyId:${historyId})`,
});
return this.ok({});
}
@@ -283,86 +303,77 @@ export class PipelineController extends CrudController<PipelineService> {
@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);
const count = await this.checkPermissionCall(async ({ userId, projectId }) => {
return await this.service.batchDelete(ids, userId, projectId);
});
this.auditLog({
content: `批量删除了${count}条流水线`,
});
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);
const count = await this.checkPermissionCall(async ({ userId, projectId }) => {
return await this.service.batchUpdateGroup(ids, groupId, userId, projectId);
});
this.auditLog({
content: `批量修改了${count}条流水线分组`,
});
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);
const count = await this.checkPermissionCall(async ({ userId, projectId }) => {
return await this.service.batchUpdateTrigger(ids, trigger, userId, projectId);
});
this.auditLog({
content: `批量修改了${count}条流水线触发器`,
});
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);
const count = await this.checkPermissionCall(async ({ userId, projectId }) => {
return await this.service.batchUpdateNotifications(ids, notification, userId, projectId);
});
this.auditLog({
content: `批量修改了${count}条流水线通知`,
});
return this.ok({});
}
@Post("/batchUpdateCertApplyOptions", { description: Constants.per.authOnly, summary: "批量更新证书申请任务配置" })
async batchUpdateCertApplyOptions(@Body("ids") ids: number[], @Body("options") options: any) {
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId);
const count = await this.checkPermissionCall(async ({ userId, projectId }) => {
return await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId);
});
this.auditLog({
content: `批量修改了${count}条流水线证书申请配置`,
});
return this.ok({});
}
@Post("/batchRerun", { description: Constants.per.authOnly, summary: "批量重新运行流水线" })
async batchRerun(@Body("ids") ids: number[], @Body("force") force: boolean) {
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchRerun(ids, force, userId, projectId);
const count = await this.checkPermissionCall(async ({ userId, projectId }) => {
return await this.service.batchRerun(ids, force, userId, projectId);
});
this.auditLog({
content: `批量重新执行了${count}条流水线`,
});
return this.ok({});
}
@Post("/batchTransfer", { description: Constants.per.authOnly, summary: "批量迁移流水线" })
async batchTransfer(@Body("ids") ids: number[], @Body("toProjectId") toProjectId: number) {
await this.checkPermissionCall(async ({}) => {
await this.service.batchTransfer(ids, toProjectId);
const count = await this.checkPermissionCall(async ({}) => {
return await this.service.batchTransfer(ids, toProjectId);
});
this.auditLog({
content: `批量迁移了${count}条流水线`,
});
return this.ok({});
}
@@ -371,6 +382,9 @@ export class PipelineController extends CrudController<PipelineService> {
async refreshWebhookKey(@Body("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
const res = await this.service.refreshWebhookKey(id);
this.auditLog({
content: `刷新了流水线(ID:${id})的Webhook密钥`,
});
return this.ok({
webhookKey: res,
});
@@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { PipelineGroupService } from "../../../modules/pipeline/service/pipeline-group-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -20,6 +21,10 @@ export class PipelineGroupController extends CrudController<PipelineGroupService
return this.service;
}
getAuditType(): string {
return AuditType.pipelineGroup.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线分组分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -52,7 +57,9 @@ export class PipelineGroupController extends CrudController<PipelineGroupService
const { projectId, userId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId;
return await super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了流水线分组「${bean.name}」(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新流水线分组" })
@@ -60,7 +67,9 @@ export class PipelineGroupController extends CrudController<PipelineGroupService
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
delete bean.projectId;
return await super.update(bean);
const res = await super.update(bean);
this.auditLog({ content: `修改了流水线分组「${bean.name}」(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询流水线分组详情" })
async info(@Query("id") id: number) {
@@ -71,7 +80,9 @@ export class PipelineGroupController extends CrudController<PipelineGroupService
@Post("/delete", { description: Constants.per.authOnly, summary: "删除流水线分组" })
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({ content: `删除了流水线分组(ID:${id})` });
return res;
}
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有流水线分组" })
@@ -4,6 +4,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { SubDomainService } from "../../../modules/pipeline/service/sub-domain-service.js";
import { TaskServiceBuilder } from "../../../modules/pipeline/service/getter/task-service-getter.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*
@@ -22,6 +23,10 @@ export class SubDomainController extends CrudController<SubDomainService> {
return this.service;
}
getAuditType(): string {
return AuditType.subDomain.value;
}
@Post("/parseDomain", { description: Constants.per.authOnly, summary: "解析域名" })
async parseDomain(@Body("fullDomain") fullDomain: string) {
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -64,7 +69,9 @@ export class SubDomainController extends CrudController<SubDomainService> {
const { userId, projectId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId;
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了子域名「${bean.domain}」(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新子域名" })
@@ -72,7 +79,9 @@ export class SubDomainController extends CrudController<SubDomainService> {
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({ content: `修改了子域名(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询子域名详情" })
async info(@Query("id") id: number) {
@@ -83,7 +92,9 @@ export class SubDomainController extends CrudController<SubDomainService> {
@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({ content: `删除了子域名(ID:${id})` });
return res;
}
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除子域名" })
@@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server";
import { TemplateService } from "../../../modules/pipeline/service/template-service.js";
import { checkPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 线
@@ -18,6 +19,10 @@ export class TemplateController extends CrudController<TemplateService> {
return this.service;
}
getAuditType(): string {
return AuditType.template.value;
}
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线模版分页列表" })
async page(@Body(ALL) body) {
body.query = body.query ?? {};
@@ -52,7 +57,9 @@ export class TemplateController extends CrudController<TemplateService> {
bean.userId = userId;
bean.projectId = projectId;
checkPlus();
return super.add(bean);
const res = await super.add(bean);
this.auditLog({ content: `新增了流水线模版「${bean.title}」(ID:${res.data})` });
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新流水线模版" })
@@ -60,7 +67,9 @@ export class TemplateController extends CrudController<TemplateService> {
await this.checkOwner(this.service, bean.id, "write");
delete bean.userId;
delete bean.projectId;
return super.update(bean);
const res = await super.update(bean);
this.auditLog({ content: `修改了流水线模版「${bean.title}」(ID:${bean.id})` });
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询流水线模版详情" })
async info(@Query("id") id: number) {
@@ -72,6 +81,7 @@ export class TemplateController extends CrudController<TemplateService> {
async delete(@Query("id") id: number) {
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.batchDelete([id], userId, projectId);
this.auditLog({ content: `删除了流水线模版(ID:${id})` });
return this.ok({});
}
@@ -79,6 +89,7 @@ export class TemplateController extends CrudController<TemplateService> {
async batchDelete(@Body("ids") ids: number[]) {
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(ids, userId, projectId);
this.auditLog({ content: `批量删除了${ids.length}条流水线模版` });
return this.ok({});
}
@@ -95,6 +106,7 @@ export class TemplateController extends CrudController<TemplateService> {
body.projectId = projectId;
checkPlus();
const res = await this.service.createPipelineByTemplate(body);
this.auditLog({ content: `根据模版创建了流水线(ID:${res.id})` });
return this.ok(res);
}
}
@@ -0,0 +1,117 @@
/// <reference types="mocha" />
import assert from "node:assert/strict";
import { Constants } from "@certd/lib-server";
import { AuditLogMiddleware } from "./audit-log.js";
class TestController {
import() {}
noAudit() {}
getAuditType(): string {
return "pipeline";
}
}
function createMiddleware() {
const middleware = new AuditLogMiddleware();
const records: any[] = [];
middleware.auditService = {
async log(record: any) {
records.push(record);
},
} as any;
(middleware as any).isPlusFn = async () => true;
return { middleware, records };
}
function createCtx(method = "import") {
return {
path: "/api/pi/cname/record/import",
status: 200,
body: Constants.res.success,
ip: "127.0.0.1",
user: { id: 1, username: "admin" },
projectId: 3,
request: {
query: { id: "5" },
body: { name: "test" },
},
requestContext: {
async getAsync() {
return new TestController();
},
},
auditRouteInfo: {
controllerClz: TestController,
method,
summary: "导入CNAME记录",
},
auditLog: {
enabled: true,
append: ["提交2条"],
},
} as any;
}
describe("AuditLogMiddleware", () => {
it("writes audit log after successful response", async () => {
const { middleware, records } = createMiddleware();
await middleware.resolve()(createCtx(), async () => {});
assert.equal(records.length, 1);
assert.equal(records[0].userId, 1);
assert.equal(records[0].type, "pipeline");
assert.equal(records[0].action, "导入CNAME记录");
assert.equal(records[0].content, "提交2条");
assert.equal(records[0].username, "admin");
assert.equal(records[0].projectId, 3);
assert.equal(records[0].ipAddress, "127.0.0.1");
assert.equal(records[0].scope, "user");
});
it("uses bean type and action overrides", async () => {
const { middleware, records } = createMiddleware();
const ctx = createCtx();
ctx.auditLog = { enabled: true, type: "settings", action: "修改设置", append: ["修改了安全设置"] };
await middleware.resolve()(ctx, async () => {});
assert.equal(records[0].type, "settings");
assert.equal(records[0].action, "修改设置");
assert.equal(records[0].content, "修改了安全设置");
});
it("skips when auditLog not enabled", async () => {
const { middleware, records } = createMiddleware();
const ctx = createCtx("noAudit");
ctx.auditLog = {};
await middleware.resolve()(ctx, async () => {});
assert.equal(records.length, 0);
});
it("writes audit log with success=false on failed response", async () => {
const { middleware, records } = createMiddleware();
const ctx = createCtx();
ctx.body = Constants.res.error;
await middleware.resolve()(ctx, async () => {});
assert.equal(records.length, 1);
assert.equal(records[0].success, false);
});
it("skips anonymous request", async () => {
const { middleware, records } = createMiddleware();
const ctx = createCtx();
ctx.user = undefined;
await middleware.resolve()(ctx, async () => {});
assert.equal(records.length, 0);
});
});
@@ -0,0 +1,94 @@
import { Inject, Provide } from "@midwayjs/core";
import { IMidwayKoaContext, IWebMiddleware, NextFunction } from "@midwayjs/koa";
import { Constants } from "@certd/lib-server";
import { AuditService } from "../modules/sys/enterprise/service/audit-service.js";
import { isPlus } from "@certd/plus-core";
@Provide()
export class AuditLogMiddleware implements IWebMiddleware {
@Inject()
auditService: AuditService;
resolve() {
return async (ctx: IMidwayKoaContext, next: NextFunction) => {
try {
await next();
await this.writeAuditLog(ctx);
} catch (err) {
await this.writeAuditLog(ctx, err);
throw err;
}
};
}
private async writeAuditLog(ctx: IMidwayKoaContext, err?: any) {
const routeInfo = ctx.auditRouteInfo;
if (!routeInfo) {
return;
}
const auditLog = ctx.auditLog;
if (!auditLog?.enabled) {
return;
}
if (!isPlus()) {
return;
}
let isSuccess = this.isSuccessResponse(ctx);
if (err) {
isSuccess = false;
if (err?.userId != null && auditLog?.userId == null) {
auditLog.userId = err.userId;
}
}
const type = auditLog.type || (await this.resolveControllerType(routeInfo.controllerClz, ctx as any));
const action = auditLog.action || routeInfo.summary || "";
const append = auditLog.append;
const appendList = Array.isArray(append) ? append : append ? [append] : [];
const content = auditLog.content || appendList.filter(item => item && String(item).trim()).join(" ") || action;
if (!content) {
return;
}
const projectId = auditLog.projectId ?? ctx.projectId ?? 0;
const scope = auditLog.scope || (ctx.path.startsWith("/api/sys/") ? "system" : "user");
const ipAddress = ctx.ip || "";
await this.auditService.log({
userId: auditLog.userId ?? ctx.user?.id ?? 0,
type: type || "unknown",
action,
content,
username: auditLog.username || ctx.user?.username,
projectId,
ipAddress,
scope,
success: isSuccess,
});
}
private async resolveControllerType(controllerClz: any, ctx: any): Promise<string | undefined> {
if (!controllerClz || !ctx.requestContext) {
return undefined;
}
try {
const controller = await ctx.requestContext.getAsync(controllerClz);
return controller?.getAuditType?.();
} catch {
return undefined;
}
}
private isSuccessResponse(ctx: IMidwayKoaContext) {
if (ctx.status >= 400) {
return false;
}
const body = ctx.body as any;
if (body?.code == null) {
return true;
}
return body.code === Constants.res.success.code;
}
}
@@ -11,7 +11,7 @@ function createMiddleware(permission: string) {
middleware.secret = "test-secret";
middleware.webRouterService = {
async getMatchedRouterInfo() {
return { description: permission };
return { description: permission, summary: "测试路由" };
},
} as any;
return middleware;
@@ -41,6 +41,7 @@ describe("AuthorityMiddleware guestOptionalAuth", () => {
assert.equal(called, true);
assert.equal(ctx.user, undefined);
assert.equal(ctx.auditRouteInfo.summary, "测试路由");
});
it("sets user when token is provided", async () => {
@@ -40,6 +40,8 @@ export class AuthorityMiddleware implements IWebMiddleware {
await next();
return;
}
ctx.auditRouteInfo = routeInfo;
this.extractProjectId(ctx);
let permission = routeInfo.description || "";
permission = permission.trim().split(" ")[0];
if (permission == null || permission === "") {
@@ -109,6 +111,16 @@ export class AuthorityMiddleware implements IWebMiddleware {
return;
}
private extractProjectId(ctx: IMidwayKoaContext) {
const headerVal = ctx.headers["project-id"] as string;
const queryVal = (ctx.request as any)?.query?.projectId;
const bodyVal = (ctx.request as any)?.body?.projectId;
const raw = headerVal || queryVal || bodyVal;
if (raw != null && raw !== "") {
ctx.projectId = parseInt(String(raw), 10) || 0;
}
}
private getTokenFromRequest(ctx: IMidwayKoaContext) {
let token = ctx.get("Authorization") || "";
token = token.replace("Bearer ", "").trim();
@@ -1,11 +1,11 @@
import { Autoload, Init, Inject, Scope, ScopeEnum } from "@midwayjs/core";
import { AutoCron } from "./auto-cron.js";
import { Autoload, Init, Inject, Scope, ScopeEnum } from "@midwayjs/core";
import { AutoInitSite } from "./auto-init-site.js";
import { AutoLoadPlugins } from "./auto-load-plugins.js";
import { AutoCron } from "./auto-cron.js";
import { AutoMitterRegister } from "./auto-mitter-register.js";
import { AutoPipelineEmitterRegister } from "./auto-pipeline-emitter-register.js";
import { AutoPrint } from "./auto-print.js";
import { AutoFix } from "./fix/auto-fix.js";
import { AutoPrint } from "./auto-print.js";
@Autoload()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
@@ -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("注册审计日志清理定时任务完成");
}
}
@@ -1,11 +1,8 @@
import { Config, Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { logger } from "@certd/basic";
import { PluginService } from "../plugin/service/plugin-service.js";
import { registerPaymentProviders } from "../suite/payments/index.js";
import { getRuntimeDepsService, initRuntimeDepsService } from "@certd/pipeline";
import { pluginRegistry, accessRegistry, notificationRegistry } from "@certd/pipeline";
import { dnsProviderRegistry } from "@certd/plugin-lib";
import { addonRegistry } from "@certd/lib-server";
import { RuntimeDepsService } from "../runtime-deps/runtime-deps-service.js";
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
@@ -13,8 +10,8 @@ export class AutoLoadPlugins {
@Inject()
pluginService: PluginService;
@Config("runtimeDeps")
runtimeDepsConfig: any;
@Inject()
runtimeDepsService: RuntimeDepsService;
async init() {
logger.info(`加载插件开始,加载模式:${process.env.certd_plugin_loadmode}`);
@@ -38,16 +35,7 @@ export class AutoLoadPlugins {
await registerPaymentProviders();
logger.info(`加载插件完成,加载模式:${process.env.certd_plugin_loadmode}`);
//初始化第三方依赖服务
initRuntimeDepsService(this.runtimeDepsConfig, {
pluginRegistry,
accessRegistry,
notificationRegistry,
dnsProviderRegistry,
addonRegistry,
});
// 收集插件 dependPackages 并安装
const service = getRuntimeDepsService();
service.refreshPluginDeps();
await this.runtimeDepsService.refreshPluginDeps();
}
}
@@ -1,4 +1,4 @@
import { cache, isDev, randomNumber, simpleNanoId } from "@certd/basic";
import { cache, isDev, randomNumber, simpleNanoId } from "@certd/basic";
import { AccessService, AccessSysGetter, CodeErrorException, SysSettingsService } from "@certd/lib-server";
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { ISmsService } from "../sms/api.js";
@@ -6,6 +6,7 @@ import { SmsServiceFactory } from "../sms/factory.js";
import { CaptchaService } from "./captcha-service.js";
import { EmailService } from "./email-service.js";
import { CaptchaRequest } from "../../../plugins/plugin-captcha/api.js";
import { RuntimeDepsService } from "../../runtime-deps/runtime-deps-service.js";
// {data: '<svg.../svg>', text: 'abcd'}
/**
@@ -24,6 +25,9 @@ export class CodeService {
@Inject()
captchaService: CaptchaService;
@Inject()
runtimeDepsService: RuntimeDepsService;
async checkCaptcha(body: any, req: CaptchaRequest) {
return await this.captchaService.doValidate({ form: body, req });
}
@@ -56,6 +60,7 @@ export class CodeService {
await sender.setCtx({
accessService: accessGetter,
config: smsConfig,
runtimeDepsService: this.runtimeDepsService,
});
const smsCode = randomNumber(verificationCodeLength);
await sender.sendSmsCode({
@@ -1,8 +1,9 @@
import { FormItemProps, IAccessService } from "@certd/pipeline";
import { FormItemProps, IAccessService } from "@certd/pipeline";
import type { RuntimeDepsService } from "../../runtime-deps/runtime-deps-service.js";
export interface ISmsService {
sendSmsCode(opts: { mobile: string; code: string; phoneCode: string }): Promise<void>;
setCtx(ctx: { accessService: IAccessService; config: { [key: string]: any } }): Promise<void>;
setCtx(ctx: { accessService: IAccessService; config: { [key: string]: any }; runtimeDepsService?: RuntimeDepsService }): Promise<void>;
}
export type PluginInputs<T = any> = {
@@ -12,4 +13,5 @@ export type PluginInputs<T = any> = {
export type SmsPluginCtx<T = any> = {
accessService: IAccessService;
config: T;
runtimeDepsService?: RuntimeDepsService;
};
@@ -1,6 +1,5 @@
import { TencentAccess } from "../../../plugins/plugin-lib/tencent/access.js";
import { importRuntime } from "@certd/pipeline";
import { ISmsService, PluginInputs } from "./api.js";
import { TencentAccess } from "../../../plugins/plugin-lib/tencent/access.js";
import { ISmsService, PluginInputs, SmsPluginCtx } from "./api.js";
export type TencentSmsConfig = {
accessId: string;
@@ -67,16 +66,26 @@ export class TencentSmsService implements ISmsService {
};
}
ctx: { accessService: any; config: TencentSmsConfig };
ctx: SmsPluginCtx<TencentSmsConfig>;
async setCtx(ctx: any) {
this.ctx = ctx;
if (this.ctx.runtimeDepsService) {
await this.ctx.runtimeDepsService.ensureDependencies({
dependencies: {
"tencentcloud-sdk-nodejs": "^4.1.112",
},
});
}
}
async getClient() {
const sdk = await importRuntime("tencentcloud-sdk-nodejs/tencentcloud/services/sms/v20210111/index.js");
if (!this.ctx.runtimeDepsService) {
throw new Error("动态依赖服务未初始化,无法加载腾讯云短信SDK");
}
const sdk = await this.ctx.runtimeDepsService.importRuntime("tencentcloud-sdk-nodejs/tencentcloud/services/sms/v20210111/index.js");
const client = sdk.v20210111.Client;
const access: TencentAccess = await this.ctx.accessService.getById(this.ctx.config.accessId);
const access = await this.ctx.accessService.getById<TencentAccess>(this.ctx.config.accessId);
// const region = this.region;
const clientConfig = {
@@ -503,6 +503,7 @@ export class CnameRecordService extends BaseService<CnameRecordEntity> {
},
})
);
return { count: domains.length };
}
async _import(req: { userId: number; projectId: number; domains: string[]; cnameProviderId: any }, task: BackTask) {

Some files were not shown because too many files have changed in this diff Show More