Files
esg/src/audit/audit.service.ts
2026-06-09 14:07:37 +03:30

38 lines
1.1 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { AuditEvent } from '../common/enums/audit-event.enum';
import { AuditLog, AuditLogDocument } from './schemas/audit-log.schema';
export interface AuditContext {
userId?: string;
actorId?: string;
username?: string;
ip?: string;
userAgent?: string;
metadata?: Record<string, unknown>;
}
/**
* Central audit writer — all security-sensitive actions flow through here.
*/
@Injectable()
export class AuditService {
constructor(
@InjectModel(AuditLog.name)
private readonly auditModel: Model<AuditLogDocument>,
) {}
async log(event: AuditEvent, context: AuditContext = {}): Promise<void> {
await this.auditModel.create({
event,
userId: context.userId ? new Types.ObjectId(context.userId) : undefined,
actorId: context.actorId ? new Types.ObjectId(context.actorId) : undefined,
username: context.username,
ip: context.ip,
userAgent: context.userAgent,
metadata: context.metadata ?? {},
});
}
}