forked from Shared/esg
initial commit
This commit is contained in:
37
src/audit/audit.service.ts
Normal file
37
src/audit/audit.service.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
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 ?? {},
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user