chore: audit log first

This commit is contained in:
xiaojunnuo
2026-07-10 19:24:42 +08:00
parent edda1b57f3
commit 4250d0e266
33 changed files with 1396 additions and 77 deletions
@@ -19,6 +19,7 @@ import sysauthority from "./certd/sys-authority";
import syscname from "./certd/sys-cname";
import tutorial from "./certd/tutorial";
import cron from "./certd/cron";
import audit from "./certd/audit";
// Note: @ is reserved in locale messages; use {'@'} when needed.
export default {
@@ -43,4 +44,5 @@ export default {
...syscname,
...tutorial,
...cron,
...audit,
};
@@ -0,0 +1,4 @@
export default {
"certd.auditLog": "Audit Log",
"certd.sysResources.auditLog": "Audit Log",
};
@@ -19,6 +19,7 @@ import sysauthority from "./certd/sys-authority";
import syscname from "./certd/sys-cname";
import tutorial from "./certd/tutorial";
import cron from "./certd/cron";
import audit from "./certd/audit";
// Note: @ is reserved in locale messages; use {'@'} when needed.
export default {
@@ -43,4 +44,5 @@ export default {
...syscname,
...tutorial,
...cron,
...audit,
};
@@ -0,0 +1,4 @@
export default {
"certd.auditLog": "操作日志",
"certd.sysResources.auditLog": "操作日志",
};
@@ -287,6 +287,17 @@ export const certdResources = [
isMenu: true,
},
},
{
title: "certd.auditLog",
name: "AuditLog",
path: "/certd/audit",
component: "/certd/audit/index.vue",
meta: {
icon: "ion:document-text-outline",
auth: true,
keepAlive: true,
},
},
{
title: "certd.userSecurity",
name: "UserSecurity",
@@ -410,6 +410,18 @@ export const sysResources = [
},
],
},
{
title: "certd.sysResources.auditLog",
name: "SysAuditLog",
path: "/sys/audit",
component: "/sys/audit/index.vue",
meta: {
icon: "ion:document-text-outline",
permission: "sys:settings:view",
keepAlive: true,
auth: true,
},
},
{
title: "certd.sysResources.netTest",
name: "NetTest",
@@ -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,102 @@
import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
const typeDict = dict({
url: "/pi/audit/dict",
getData: async () => {
const { createAuditApi } = await import("./api");
const api = createAuditApi();
const res = await api.GetDict();
return res.types || [];
},
});
const actionDict = dict({
url: "/pi/audit/dict",
getData: async () => {
const { createAuditApi } = await import("./api");
const api = createAuditApi();
const res = await api.GetDict();
return res.actions || [];
},
});
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
return {
crudOptions: {
request: { pageRequest, delRequest },
actionbar: {
buttons: {
add: { show: false },
},
},
rowHandle: {
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
},
},
columns: {
id: {
title: "ID",
type: "number",
column: { width: 80 },
form: { show: false },
},
createTime: {
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
vModel: ["createTime_start", "createTime_end"],
},
},
column: { width: 170, sorter: true },
form: { show: false },
},
type: {
title: "操作类型",
type: "dict-select",
dict: typeDict,
search: { show: true },
column: { width: 120 },
form: { show: false },
},
action: {
title: "操作动作",
type: "dict-select",
dict: actionDict,
search: { show: true },
column: { width: 100 },
form: { show: false },
},
content: {
title: "内容",
type: "text",
search: { show: true },
column: { minWidth: 300 },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
},
},
};
}
@@ -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,124 @@
import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud";
const typeDict = dict({
url: "/sys/audit/dict",
getData: async () => {
const { createSysAuditApi } = await import("./api");
const api = createSysAuditApi();
const res = await api.GetDict();
return res.types || [];
},
});
const actionDict = dict({
url: "/sys/audit/dict",
getData: async () => {
const { createSysAuditApi } = await import("./api");
const api = createSysAuditApi();
const res = await api.GetDict();
return res.actions || [];
},
});
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const api = context.api;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const delRequest = async (req: DelReq) => {
return await api.DelObj(req.row.id);
};
const cleanExpired = async () => {
await api.Clean(90);
crudExpose.doRefresh();
};
return {
crudOptions: {
request: { pageRequest, delRequest },
actionbar: {
buttons: {
add: { show: false },
clean: {
text: "清理过期日志(90天)",
type: "default",
click: cleanExpired,
},
},
},
rowHandle: {
width: 120,
fixed: "right",
buttons: {
view: { show: false },
edit: { show: false },
remove: { show: true },
},
},
search: {
initialForm: {
sort: { prop: "id", asc: false },
},
},
columns: {
id: {
title: "ID",
type: "number",
column: { width: 80 },
form: { show: false },
},
createTime: {
title: "操作时间",
type: "datetime",
search: {
show: true,
component: {
name: "a-range-picker",
vModel: ["createTime_start", "createTime_end"],
},
},
column: { width: 170, sorter: true },
form: { show: false },
},
userName: {
title: "操作人",
type: "text",
search: { show: true },
column: { width: 120 },
form: { show: false },
},
type: {
title: "操作类型",
type: "dict-select",
dict: typeDict,
search: { show: true },
column: { width: 120 },
form: { show: false },
},
action: {
title: "操作动作",
type: "dict-select",
dict: actionDict,
search: { show: true },
column: { width: 100 },
form: { show: false },
},
content: {
title: "内容",
type: "text",
search: { show: true },
column: { minWidth: 300 },
form: { show: false },
},
ipAddress: {
title: "IP地址",
type: "text",
column: { width: 140 },
form: { show: false },
},
},
},
};
}
@@ -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>
@@ -0,0 +1,39 @@
import { BaseController, Constants } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { ApiTags } from "@midwayjs/swagger";
import { AuditService } from "../../../modules/sys/enterprise/service/audit-service.js";
import { buildAuditTypeDict, buildAuditActionDict } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@ApiTags(["audit"])
@Controller("/api/sys/audit")
export class SysAuditLogController extends BaseController {
@Inject()
auditService: AuditService;
@Post("/page", { description: Constants.per.authOnly, summary: "分页查询审计日志" })
async page(@Body(ALL) body: any) {
const pageRet = await this.auditService.page(body);
return this.ok(pageRet);
}
@Post("/delete", { description: Constants.per.authOnly })
async delete(@Query("id") id: number) {
await this.auditService.delete(id);
return this.ok({});
}
@Post("/clean", { description: Constants.per.authOnly })
async clean(@Body("retentionDays") retentionDays: number) {
const count = await this.auditService.cleanExpired(retentionDays || 90);
return this.ok({ deletedCount: count });
}
@Post("/dict", { description: Constants.per.authOnly, summary: "获取审计类型和动作字典" })
async getDict() {
return this.ok({
types: buildAuditTypeDict(),
actions: buildAuditActionDict(),
});
}
}
@@ -1,6 +1,7 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { CrudController } from "@certd/lib-server";
import { PermissionService } from "../../../modules/sys/authority/service/permission-service.js";
import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js";
/**
* 权限资源
@@ -28,7 +29,13 @@ export class PermissionController extends CrudController<PermissionService> {
@Body(ALL)
bean
) {
return await super.add(bean);
const res = await super.add(bean);
await this.auditLog({
type: AuditType.permission,
action: AuditAction.add,
content: `新增了权限「${bean.name}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:auth:per:edit" })
@@ -36,14 +43,26 @@ export class PermissionController extends CrudController<PermissionService> {
@Body(ALL)
bean
) {
return await super.update(bean);
const res = await super.update(bean);
await this.auditLog({
type: AuditType.permission,
action: AuditAction.update,
content: `修改了权限「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/delete", { description: "sys:auth:per:remove" })
async delete(
@Query("id")
id: number
) {
return await super.delete(id);
const res = await super.delete(id);
await this.auditLog({
type: AuditType.permission,
action: AuditAction.delete,
content: `删除了权限(ID:${id})`,
});
return res;
}
@Post("/tree", { description: "sys:auth:per:view" })
@@ -1,6 +1,7 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { CrudController } from "@certd/lib-server";
import { RoleService } from "../../../modules/sys/authority/service/role-service.js";
import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js";
/**
* 系统用户
@@ -34,7 +35,13 @@ export class RoleController extends CrudController<RoleService> {
@Body(ALL)
bean
) {
return await super.add(bean);
const res = await super.add(bean);
await this.auditLog({
type: AuditType.role,
action: AuditAction.add,
content: `新增了角色「${bean.name}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:auth:role:edit" })
@@ -42,7 +49,13 @@ export class RoleController extends CrudController<RoleService> {
@Body(ALL)
bean
) {
return await super.update(bean);
const res = await super.update(bean);
await this.auditLog({
type: AuditType.role,
action: AuditAction.update,
content: `修改了角色「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/delete", { description: "sys:auth:role:remove" })
async delete(
@@ -52,7 +65,13 @@ export class RoleController extends CrudController<RoleService> {
if (id === 1) {
throw new Error("不能删除默认的管理员角色");
}
return await super.delete(id);
const res = await super.delete(id);
await this.auditLog({
type: AuditType.role,
action: AuditAction.delete,
content: `删除了角色(ID:${id})`,
});
return res;
}
@Post("/getPermissionTree", { description: "sys:auth:role:view" })
@@ -6,6 +6,7 @@ import { PermissionService } from "../../../modules/sys/authority/service/permis
import { Constants } from "@certd/lib-server";
import { In } from "typeorm";
import { LoginService } from "../../../modules/login/service/login-service.js";
import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js";
/**
* 系统用户
@@ -97,7 +98,13 @@ export class UserController extends CrudController<UserService> {
@Body(ALL)
bean
) {
return await super.add(bean);
const res = await super.add(bean);
await this.auditLog({
type: AuditType.user,
action: AuditAction.add,
content: `新增了用户「${bean.username}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:auth:user:edit" })
@@ -105,7 +112,13 @@ export class UserController extends CrudController<UserService> {
@Body(ALL)
bean
) {
return await super.update(bean);
const res = await super.update(bean);
await this.auditLog({
type: AuditType.user,
action: AuditAction.update,
content: `修改了用户「${bean.username}」(ID:${bean.id})`,
});
return res;
}
@Post("/delete", { description: "sys:auth:user:remove" })
@@ -119,7 +132,13 @@ export class UserController extends CrudController<UserService> {
if (id === 3) {
throw new Error("不能删除默认的普通用户角色");
}
return await super.delete(id);
const res = await super.delete(id);
await this.auditLog({
type: AuditType.user,
action: AuditAction.delete,
content: `删除了用户(ID:${id})`,
});
return res;
}
/**
@@ -3,6 +3,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js";
import { ProjectEntity } from "../../../modules/sys/enterprise/entity/project.js";
import { merge } from "lodash-es";
import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -38,17 +39,29 @@ export class SysProjectController extends CrudController<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({
type: AuditType.project,
action: AuditAction.add,
content: `新增了项目「${bean.name}」(ID:${res.data})`,
});
return res;
}
@Post("/update", { description: "sys:settings:edit" })
async update(@Body(ALL) bean: any) {
bean.userId = this.getUserId();
return super.update(bean);
const res = await super.update(bean);
await this.auditLog({
type: AuditType.project,
action: AuditAction.update,
content: `修改了项目「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/info", { description: "sys:settings:view" })
@@ -58,7 +71,13 @@ export class SysProjectController extends CrudController<ProjectEntity> {
@Post("/delete", { description: "sys:settings:edit" })
async delete(@Query("id") id: number) {
return super.delete(id);
const res = await super.delete(id);
await this.auditLog({
type: AuditType.project,
action: AuditAction.delete,
content: `删除了项目(ID:${id})`,
});
return res;
}
@Post("/deleteByIds", { description: "sys:settings:edit" })
@@ -69,6 +88,13 @@ export class SysProjectController extends CrudController<ProjectEntity> {
@Post("/setDisabled", { description: "sys:settings:edit" })
async setDisabled(@Body("id") id: number, @Body("disabled") disabled: boolean) {
await this.service.setDisabled(id, disabled);
const project = await this.service.info(id);
const actionText = disabled ? "禁用了" : "启用了";
await this.auditLog({
type: AuditType.project,
action: AuditAction.disable,
content: `${actionText}项目「${project.name}」(ID:${id})`,
});
return this.ok();
}
}
@@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, SysSafeSetting } from "@certd/lib-server";
import { cloneDeep } from "lodash-es";
import { SafeService } from "../../../modules/sys/settings/safe-service.js";
import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -22,6 +23,11 @@ export class SysSettingsController extends BaseController {
@Post("/save", { description: "sys:settings:edit" })
async safeSave(@Body(ALL) body: any) {
await this.safeService.saveSafeSetting(body);
await this.auditLog({
type: AuditType.settings,
action: AuditAction.update,
content: "修改了安全设置",
});
return this.ok({});
}
@@ -8,6 +8,7 @@ import { http, logger, utils } from "@certd/basic";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { SmsServiceFactory } from "../../../modules/basic/sms/factory.js";
import { RuntimeDepsService } from "../../../modules/runtime-deps/runtime-deps-service.js";
import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -66,6 +67,11 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
@Post("/save", { description: "sys:settings:edit" })
async save(@Body(ALL) bean: SysSettingsEntity) {
await this.service.save(bean);
await this.auditLog({
type: AuditType.settings,
action: AuditAction.update,
content: "修改了系统设置",
});
return this.ok({});
}
@@ -0,0 +1,32 @@
import { BaseController, Constants } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { ApiTags } from "@midwayjs/swagger";
import { AuditService } from "../../../modules/sys/enterprise/service/audit-service.js";
import { buildAuditTypeDict, buildAuditActionDict } from "../../../modules/sys/enterprise/service/audit-constants.js";
@Provide()
@ApiTags(["audit"])
@Controller("/api/pi/audit")
export class AuditLogController extends BaseController {
@Inject()
auditService: AuditService;
@Post("/page", { description: Constants.per.authOnly, summary: "分页查询当前用户操作日志" })
async page(@Body(ALL) body: any) {
const userId = this.getUserId();
if (!body.query) {
body.query = {};
}
body.query.userId = userId;
const pageRet = await this.auditService.page(body);
return this.ok(pageRet);
}
@Post("/dict", { description: Constants.per.authOnly, summary: "获取审计类型和动作字典" })
async getDict() {
return this.ok({
types: buildAuditTypeDict(),
actions: buildAuditActionDict(),
});
}
}
@@ -7,6 +7,7 @@ import { merge } from "lodash-es";
import { SiteIpService } from "../../../modules/monitor/service/site-ip-service.js";
import { utils } from "@certd/basic";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -20,7 +21,6 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
authService: AuthService;
@Inject()
siteIpService: SiteIpService;
getService(): SiteInfoService {
return this.service;
}
@@ -75,6 +75,11 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
if (entity.disabled) {
this.service.check(entity.id, true, 0);
}
this.auditLog({
type: AuditType.monitor,
action: AuditAction.add,
content: `新增了站点监控「${bean.name}」(ID:${res.id}, 域名:${bean.domain})`,
});
return this.ok(res);
}
@@ -88,6 +93,11 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
if (entity.disabled) {
this.service.check(entity.id, true, 0);
}
this.auditLog({
type: AuditType.monitor,
action: AuditAction.update,
content: `修改了站点监控「${bean.name}」(ID:${bean.id})`,
});
return this.ok();
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询站点监控详情" })
@@ -99,13 +109,24 @@ export class SiteInfoController extends CrudController<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({
type: AuditType.monitor,
action: AuditAction.delete,
content: `删除了站点监控(ID:${id})`,
});
return res;
}
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除站点监控" })
async batchDelete(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(body.ids, userId, projectId);
this.auditLog({
type: AuditType.monitor,
action: AuditAction.batchDelete,
content: `批量删除了${body.ids.length}条站点监控`,
});
return this.ok();
}
@@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { OpenKeyService } from "../../../modules/open/service/open-key-service.js";
import { ApiTags } from "@midwayjs/swagger";
import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
*/
@@ -14,7 +15,6 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
service: OpenKeyService;
@Inject()
authService: AuthService;
getService(): OpenKeyService {
return this.service;
}
@@ -57,6 +57,11 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
body.projectId = projectId;
body.userId = userId;
const res = await this.service.add(body);
this.auditLog({
type: AuditType.openKey,
action: AuditAction.add,
content: `新增了API密钥(ID:${res.id}, scope:${body.scope})`,
});
return this.ok(res);
}
@@ -66,6 +71,11 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
delete bean.userId;
delete bean.projectId;
await this.service.update(bean);
this.auditLog({
type: AuditType.openKey,
action: AuditAction.update,
content: `修改了API密钥(ID:${bean.id})`,
});
return this.ok();
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询开放API密钥详情" })
@@ -90,7 +100,13 @@ export class OpenKeyController extends CrudController<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({
type: AuditType.openKey,
action: AuditAction.delete,
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, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 授权
@@ -16,7 +17,6 @@ export class AccessController extends CrudController<AccessService> {
service: AccessService;
@Inject()
authService: AuthService;
getService(): AccessService {
return this.service;
}
@@ -58,7 +58,13 @@ 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({
type: AuditType.access,
action: AuditAction.add,
content: `新增了授权「${bean.name}」(ID:${res.data}, 类型:${bean.type})`,
});
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新授权配置" })
@@ -66,7 +72,13 @@ export class AccessController extends CrudController<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({
type: AuditType.access,
action: AuditAction.update,
content: `修改了授权「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询授权配置详情" })
async info(@Query("id") id: number) {
@@ -77,7 +89,13 @@ export class AccessController extends CrudController<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({
type: AuditType.access,
action: AuditAction.delete,
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, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js";
/**
* 通知
@@ -17,7 +18,6 @@ export class NotificationController extends CrudController<NotificationService>
service: NotificationService;
@Inject()
authService: AuthService;
getService(): NotificationService {
return this.service;
}
@@ -62,7 +62,13 @@ export class NotificationController extends CrudController<NotificationService>
if (define.needPlus) {
checkPlus();
}
return super.add(bean);
const res = await super.add(bean);
this.auditLog({
type: AuditType.notification,
action: AuditAction.add,
content: `新增了通知配置「${bean.name}」(ID:${res.data}, 类型:${bean.type})`,
});
return res;
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新通知配置" })
@@ -84,7 +90,13 @@ export class NotificationController extends CrudController<NotificationService>
}
delete bean.userId;
delete bean.projectId;
return super.update(bean);
const res = await super.update(bean);
this.auditLog({
type: AuditType.notification,
action: AuditAction.update,
content: `修改了通知配置「${bean.name}」(ID:${bean.id})`,
});
return res;
}
@Post("/info", { description: Constants.per.authOnly, summary: "查询通知配置详情" })
async info(@Query("id") id: number) {
@@ -95,7 +107,13 @@ export class NotificationController extends CrudController<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({
type: AuditType.notification,
action: AuditAction.delete,
content: `删除了通知配置(ID:${id})`,
});
return res;
}
@Post("/define", { description: Constants.per.authOnly, summary: "查询通知插件定义" })
@@ -7,6 +7,7 @@ import { HistoryService } from "../../../modules/pipeline/service/history-servic
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { PipelineEntity } from "../../../modules/pipeline/entity/pipeline.js";
import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js";
const pipelineExample = `
// 流水线配置示例,实际传送时要去掉注释
@@ -123,6 +124,7 @@ export class PipelineController extends CrudController<PipelineService> {
@Inject()
siteInfoService: SiteInfoService;
getService() {
return this.service;
}
@@ -196,7 +198,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 +209,22 @@ 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({
type: AuditType.pipeline,
action: isNew ? AuditAction.add : AuditAction.update,
content: isNew ? `创建了流水线「${title}」(ID:${bean.id})` : `修改了流水线「${title}」(ID:${bean.id})`,
projectId,
});
if (bean.addToMonitorEnabled && bean.addToMonitorDomains) {
const sysPublicSettings = await this.sysSettingsService.getPublicSettings();
if (isPlus() && sysPublicSettings.certDomainAddToMonitorEnabled) {
//增加证书监控
await this.siteInfoService.doImport({
text: bean.addToMonitorDomains,
userId: userId,
@@ -230,6 +239,11 @@ export class PipelineController extends CrudController<PipelineService> {
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
await this.service.delete(id);
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.delete,
content: `删除了流水线(ID:${id})`,
});
return this.ok({});
}
@@ -253,6 +267,11 @@ export class PipelineController extends CrudController<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({
type: AuditType.pipeline,
action: AuditAction.execute,
content: `手动执行了流水线(ID:${id})`,
});
return this.ok({});
}
@@ -260,6 +279,11 @@ 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({
type: AuditType.pipeline,
action: AuditAction.cancel,
content: `取消了流水线执行(historyId:${historyId})`,
});
return this.ok({});
}
@@ -283,63 +307,53 @@ 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);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.batchDelete,
content: `批量删除了${ids.length}条流水线`,
});
return this.ok({});
}
@Post("/batchUpdateGroup", { description: Constants.per.authOnly, summary: "批量更新流水线分组" })
async batchUpdateGroup(@Body("ids") ids: number[], @Body("groupId") groupId: number) {
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchUpdateGroup(ids, groupId, null,projectId);
// return this.ok({});
// }
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateGroup(ids, groupId, userId);
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateGroup(ids, groupId, userId, projectId);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.batchUpdate,
content: `批量修改了${ids.length}条流水线分组`,
});
return this.ok({});
}
@Post("/batchUpdateTrigger", { description: Constants.per.authOnly, summary: "批量更新流水线触发器" })
async batchUpdateTrigger(@Body("ids") ids: number[], @Body("trigger") trigger: any) {
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchUpdateTrigger(ids, trigger, null,projectId);
// return this.ok({});
// }
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateTrigger(ids, trigger, userId);
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateTrigger(ids, trigger, userId, projectId);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.batchUpdate,
content: `批量修改了${ids.length}条流水线触发器`,
});
return this.ok({});
}
@Post("/batchUpdateNotification", { description: Constants.per.authOnly, summary: "批量更新流水线通知" })
async batchUpdateNotification(@Body("ids") ids: number[], @Body("notification") notification: any) {
// const isAdmin = await this.authService.isAdmin(this.ctx);
// const userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateNotifications(ids, notification, userId);
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateNotifications(ids, notification, userId, projectId);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.batchUpdate,
content: `批量修改了${ids.length}条流水线通知`,
});
return this.ok({});
}
@@ -348,6 +362,11 @@ export class PipelineController extends CrudController<PipelineService> {
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.batchUpdate,
content: `批量修改了${ids.length}条流水线证书申请配置`,
});
return this.ok({});
}
@@ -356,6 +375,11 @@ export class PipelineController extends CrudController<PipelineService> {
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchRerun(ids, force, userId, projectId);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.execute,
content: `批量重新执行了${ids.length}条流水线`,
});
return this.ok({});
}
@@ -364,6 +388,11 @@ export class PipelineController extends CrudController<PipelineService> {
await this.checkPermissionCall(async ({}) => {
await this.service.batchTransfer(ids, toProjectId);
});
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.batchUpdate,
content: `批量迁移了${ids.length}条流水线`,
});
return this.ok({});
}
@@ -371,6 +400,11 @@ export class PipelineController extends CrudController<PipelineService> {
async refreshWebhookKey(@Body("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
const res = await this.service.refreshWebhookKey(id);
this.auditLog({
type: AuditType.pipeline,
action: AuditAction.update,
content: `刷新了流水线(ID:${id})的Webhook密钥`,
});
return this.ok({
webhookKey: res,
});
@@ -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("注册审计日志清理定时任务完成");
}
}
@@ -10,7 +10,7 @@ export class AuditLogEntity {
@Column({ name: "user_id", comment: "UserId" })
userId: number;
@Column({ name: "user_name", comment: "用户名" })
@Column({ name: "username", comment: "用户名" })
userName: string;
@Column({ name: "project_id", comment: "ProjectId" })
@@ -0,0 +1,87 @@
export const AuditType = {
pipeline: "pipeline",
access: "access",
monitor: "monitor",
notification: "notification",
openKey: "openKey",
user: "user",
role: "role",
permission: "permission",
project: "project",
settings: "settings",
} as const;
export const AuditTypeMap = {
pipeline: "流水线",
access: "授权管理",
monitor: "站点监控",
notification: "通知设置",
openKey: "API密钥",
user: "用户管理",
role: "角色管理",
permission: "权限管理",
project: "项目管理",
settings: "系统设置",
} as const;
export const AuditAction = {
add: "add",
update: "update",
delete: "delete",
execute: "execute",
cancel: "cancel",
batchDelete: "batchDelete",
batchUpdate: "batchUpdate",
disable: "disable",
} as const;
export const AuditActionMap = {
add: "新增",
update: "修改",
delete: "删除",
execute: "执行",
cancel: "取消",
batchDelete: "批量删除",
batchUpdate: "批量修改",
disable: "禁用",
} as const;
export const AuditTypeColorMap: Record<string, string> = {
pipeline: "blue",
access: "orange",
monitor: "green",
notification: "purple",
openKey: "red",
user: "cyan",
role: "geekblue",
permission: "lime",
project: "gold",
settings: "magenta",
};
export const AuditActionColorMap: Record<string, string> = {
add: "green",
update: "blue",
delete: "red",
execute: "orange",
cancel: "default",
batchDelete: "volcano",
batchUpdate: "purple",
disable: "default",
};
export function buildAuditTypeDict() {
return Object.entries(AuditTypeMap).map(([value, label]) => ({
value,
label,
color: AuditTypeColorMap[value],
}));
}
export function buildAuditActionDict() {
return Object.entries(AuditActionMap).map(([value, label]) => ({
value,
label,
color: AuditActionColorMap[value],
}));
}
@@ -0,0 +1,129 @@
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { TypeORMDataSourceManager } from "@midwayjs/typeorm";
import { LessThan, Repository } from "typeorm";
import { AuditLogEntity } from "../entity/audit-log.js";
import { logger } from "@certd/basic";
import { Cron } from "../../../cron/cron.js";
export type AuditPageReq = {
page?: { offset: number; limit: number };
query?: {
userId?: number;
type?: string;
action?: string;
createTime_start?: string;
createTime_end?: string;
};
sort?: { prop: string; asc: boolean };
};
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class AuditService {
@Inject()
dataSourceManager: TypeORMDataSourceManager;
@Inject()
cron: Cron;
getRepository(): Repository<AuditLogEntity> {
return this.dataSourceManager.getDataSource("default").getRepository(AuditLogEntity);
}
async log(params: { userId: number; type: string; action: string; content: string; username?: string; projectId?: number; projectName?: string; ipAddress?: string }): Promise<void> {
try {
let { username } = params;
if (!username && params.userId != null) {
const userRepo = this.dataSourceManager.getDataSource("default").getRepository("sys_user" as any);
const user = await userRepo.findOne({ where: { id: params.userId } });
username = user?.username || "";
}
const repo = this.getRepository();
const entity = new AuditLogEntity();
entity.userId = params.userId;
entity.userName = username || "";
entity.type = params.type;
entity.action = params.action;
entity.content = params.content;
entity.projectId = params.projectId || 0;
entity.projectName = params.projectName || "";
entity.ipAddress = params.ipAddress || "";
await repo.save(entity);
} catch (e) {
logger.error("写入审计日志失败:", e);
}
}
async page(pageReq: AuditPageReq) {
const repo = this.getRepository();
const { page, query, sort } = pageReq;
const offset = page?.offset ?? 0;
const limit = page?.limit ?? 20;
const qb = repo.createQueryBuilder("main");
if (query?.userId != null) {
qb.andWhere("main.userId = :userId", { userId: query.userId });
}
if (query?.type) {
qb.andWhere("main.type = :type", { type: query.type });
}
if (query?.action) {
qb.andWhere("main.action = :action", { action: query.action });
}
if (query?.createTime_start) {
qb.andWhere("main.createTime >= :start", { start: query.createTime_start });
}
if (query?.createTime_end) {
qb.andWhere("main.createTime <= :end", { end: query.createTime_end });
}
if (sort?.prop) {
qb.orderBy("main." + sort.prop, sort.asc ? "ASC" : "DESC");
} else {
qb.orderBy("main.id", "DESC");
}
qb.skip(offset).take(limit);
const list = await qb.getMany();
const total = await qb.getCount();
return {
records: list,
total,
offset,
limit,
};
}
async cleanExpired(retentionDays: number): Promise<number> {
const repo = this.getRepository();
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - retentionDays);
const result = await repo.delete({
createTime: LessThan(cutoff),
} as any);
const deletedCount = result.affected || 0;
if (deletedCount > 0) {
logger.info(`审计日志清理完成,删除 ${deletedCount} 条超过 ${retentionDays} 天的记录`);
}
return deletedCount;
}
async delete(id: number): Promise<void> {
const repo = this.getRepository();
await repo.delete({ id });
}
registerCleanCron() {
this.cron.register({
name: "audit.cleanExpired",
cron: "0 3 * * *",
job: async () => {
await this.cleanExpired(90);
},
});
}
}
@@ -243,7 +243,7 @@ export class VolcengineDeployToVOD extends AbstractTaskPlugin {
return {
value: item.Domain,
label: item.Domain,
domain : item.Domain,
domain: item.Domain,
};
});
return this.ctx.utils.options.buildGroupOptions(list, this.certDomains);