feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsInt, IsOptional, IsString } from 'class-validator';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class QueryOperationLogDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '账号 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
userId?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '模块' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
module?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '操作' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
action?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '结果 SUCCESS / FAILED' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '关键词(账号/路径/消息/目标 ID)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '开始时间' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
startTime?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '结束时间' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
endTime?: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
|
||||
@Injectable()
|
||||
export class OperationLogRetentionService {
|
||||
private readonly logger = new Logger(OperationLogRetentionService.name);
|
||||
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
private readonly logs: OperationLogService,
|
||||
) {}
|
||||
|
||||
@Cron(CronExpression.EVERY_DAY_AT_4AM)
|
||||
async cleanup(): Promise<void> {
|
||||
const raw = await this.settings.get('operationLogRetentionDays');
|
||||
const days = Number(raw ?? 365);
|
||||
if (!days || days <= 0) return;
|
||||
const count = await this.logs.cleanup(days);
|
||||
this.logger.log(`操作日志清理完成:${count} 条,保留 ${days} 天`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
import { QueryOperationLogDto } from './dto/query-operation-log.dto';
|
||||
|
||||
@ApiTags('操作日志')
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Controller('operation-logs')
|
||||
export class OperationLogController {
|
||||
constructor(private readonly logs: OperationLogService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '操作日志列表' })
|
||||
list(@Query() query: QueryOperationLogDto) {
|
||||
return this.logs.list(query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { Observable, throwError } from 'rxjs';
|
||||
import { catchError, tap } from 'rxjs/operators';
|
||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
|
||||
const SENSITIVE_KEYS = new Set(['password', 'oldPassword', 'newPassword', 'token', 'authorization']);
|
||||
|
||||
function sanitize(value: unknown, depth = 0): unknown {
|
||||
if (depth > 3) return '[Truncated]';
|
||||
if (value === null || value === undefined) return value;
|
||||
if (typeof value !== 'object') return value;
|
||||
if (Array.isArray(value)) return value.slice(0, 20).map((item) => sanitize(item, depth + 1));
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (SENSITIVE_KEYS.has(key)) {
|
||||
out[key] = '[Redacted]';
|
||||
} else if (typeof val === 'string' && val.length > 300) {
|
||||
out[key] = `${val.slice(0, 300)}...`;
|
||||
} else {
|
||||
out[key] = sanitize(val, depth + 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function moduleOf(path: string): string {
|
||||
const p = path.replace(/^\/api\/?/, '');
|
||||
const first = p.split('/').filter(Boolean)[0] || 'root';
|
||||
if (p.includes('/export')) return 'export';
|
||||
if (p.includes('/download')) return 'download';
|
||||
return first;
|
||||
}
|
||||
|
||||
function actionOf(method: string, path: string): string {
|
||||
if (path.includes('/login')) return 'login';
|
||||
if (path.includes('/export')) return 'export';
|
||||
if (path.includes('/download')) return 'download';
|
||||
if (path.includes('/upload')) return 'upload';
|
||||
if (path.includes('/audit')) return 'audit';
|
||||
if (path.includes('/onchain')) return 'onchain';
|
||||
if (path.includes('/backup')) return 'backup';
|
||||
if (path.includes('/restore')) return 'restore';
|
||||
if (method === 'POST') return 'create';
|
||||
if (method === 'PUT' || method === 'PATCH') return 'update';
|
||||
if (method === 'DELETE') return 'delete';
|
||||
return method.toLowerCase();
|
||||
}
|
||||
|
||||
function shouldLog(method: string, path: string): boolean {
|
||||
if (path.includes('/operation-logs')) return false;
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) return true;
|
||||
return path.includes('/export') || path.includes('/download');
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OperationLogInterceptor implements NestInterceptor {
|
||||
constructor(private readonly logs: OperationLogService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const req = context.switchToHttp().getRequest<Request & { user?: AuthUser }>();
|
||||
const method = req.method.toUpperCase();
|
||||
const path = req.originalUrl || req.url;
|
||||
if (!shouldLog(method, path)) return next.handle();
|
||||
|
||||
const started = Date.now();
|
||||
const user = req.user;
|
||||
const base = {
|
||||
userId: user?.id ?? null,
|
||||
username: user?.username ?? (req.body as any)?.username ?? null,
|
||||
role: user?.role ?? null,
|
||||
module: moduleOf(path),
|
||||
action: actionOf(method, path),
|
||||
method,
|
||||
path,
|
||||
targetId: String(req.params?.id ?? req.params?.shortCode ?? ''),
|
||||
ip: (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() || req.ip,
|
||||
userAgent: req.headers['user-agent'] || null,
|
||||
requestSummary: sanitize({ params: req.params, query: req.query, body: req.body }) as any,
|
||||
};
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
void this.logs.create({
|
||||
...base,
|
||||
status: 'SUCCESS',
|
||||
durationMs: Date.now() - started,
|
||||
});
|
||||
}),
|
||||
catchError((err) => {
|
||||
void this.logs.create({
|
||||
...base,
|
||||
status: 'FAILED',
|
||||
message: (err as Error)?.message || String(err),
|
||||
durationMs: Date.now() - started,
|
||||
});
|
||||
return throwError(() => err);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { OperationLogController } from './operation-log.controller';
|
||||
import { OperationLogInterceptor } from './operation-log.interceptor';
|
||||
import { OperationLogRetentionService } from './operation-log-retention.service';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
|
||||
@Module({
|
||||
controllers: [OperationLogController],
|
||||
providers: [OperationLogService, OperationLogInterceptor, OperationLogRetentionService],
|
||||
exports: [OperationLogService, OperationLogInterceptor],
|
||||
})
|
||||
export class OperationLogModule {}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { QueryOperationLogDto } from './dto/query-operation-log.dto';
|
||||
|
||||
export interface OperationLogInput {
|
||||
userId?: number | null;
|
||||
username?: string | null;
|
||||
role?: string | null;
|
||||
module: string;
|
||||
action: string;
|
||||
method: string;
|
||||
path: string;
|
||||
targetId?: string | null;
|
||||
status: string;
|
||||
message?: string | null;
|
||||
ip?: string | null;
|
||||
userAgent?: string | null;
|
||||
durationMs?: number | null;
|
||||
requestSummary?: Prisma.InputJsonValue | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OperationLogService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async create(input: OperationLogInput): Promise<void> {
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
userId: input.userId ?? null,
|
||||
username: input.username ?? null,
|
||||
role: (input.role as any) ?? null,
|
||||
module: input.module,
|
||||
action: input.action,
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
targetId: input.targetId ?? null,
|
||||
status: input.status,
|
||||
message: input.message ?? null,
|
||||
ip: input.ip ?? null,
|
||||
userAgent: input.userAgent ?? null,
|
||||
durationMs: input.durationMs ?? null,
|
||||
requestSummary: input.requestSummary ?? undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async list(query: QueryOperationLogDto) {
|
||||
const where: Prisma.OperationLogWhereInput = {};
|
||||
if (query.userId) where.userId = query.userId;
|
||||
if (query.module) where.module = query.module;
|
||||
if (query.action) where.action = query.action;
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.keyword) {
|
||||
where.OR = [
|
||||
{ username: { contains: query.keyword } },
|
||||
{ path: { contains: query.keyword } },
|
||||
{ message: { contains: query.keyword } },
|
||||
{ targetId: { contains: query.keyword } },
|
||||
];
|
||||
}
|
||||
if (query.startTime || query.endTime) {
|
||||
where.createdAt = {};
|
||||
if (query.startTime) where.createdAt.gte = new Date(query.startTime);
|
||||
if (query.endTime) where.createdAt.lte = new Date(query.endTime);
|
||||
}
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.operationLog.findMany({
|
||||
where,
|
||||
orderBy: { id: 'desc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.operationLog.count({ where }),
|
||||
]);
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async cleanup(days: number): Promise<number> {
|
||||
if (!days || days <= 0) return 0;
|
||||
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
const res = await this.prisma.operationLog.deleteMany({ where: { createdAt: { lt: cutoff } } });
|
||||
return res.count;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user