feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -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);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user