forked from Shared/esg
41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { AuditEvent } from '../common/enums/audit-event.enum';
|
|
import { isUuid } from '../database/postgres.helpers';
|
|
import { AuditLog } 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(
|
|
@InjectRepository(AuditLog)
|
|
private readonly auditLogs: Repository<AuditLog>,
|
|
) {}
|
|
|
|
async log(event: AuditEvent, context: AuditContext = {}): Promise<void> {
|
|
await this.auditLogs.save(
|
|
this.auditLogs.create({
|
|
event,
|
|
userId: isUuid(context.userId) ? context.userId : null,
|
|
actorId: isUuid(context.actorId) ? context.actorId : null,
|
|
username: context.username,
|
|
ip: context.ip,
|
|
userAgent: context.userAgent,
|
|
metadata: context.metadata ?? {},
|
|
}),
|
|
);
|
|
}
|
|
}
|