83 lines
2.5 KiB
C#
83 lines
2.5 KiB
C#
|
|
using Microsoft.AspNetCore.Mvc;
|
||
|
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
using LingAdmin.API.Data;
|
||
|
|
using LingAdmin.API.Models;
|
||
|
|
using LingAdmin.API.DTOs;
|
||
|
|
using Dapr.Client;
|
||
|
|
|
||
|
|
namespace LingAdmin.API.Controllers;
|
||
|
|
|
||
|
|
[ApiController]
|
||
|
|
[Route("api/[controller]")]
|
||
|
|
public class AuditController : ControllerBase
|
||
|
|
{
|
||
|
|
private readonly AppDbContext _context;
|
||
|
|
private readonly DaprClient _daprClient;
|
||
|
|
private readonly ILogger<AuditController> _logger;
|
||
|
|
|
||
|
|
public AuditController(AppDbContext context, DaprClient daprClient, ILogger<AuditController> logger)
|
||
|
|
{
|
||
|
|
_context = context;
|
||
|
|
_daprClient = daprClient;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
[HttpGet]
|
||
|
|
public async Task<ActionResult<ApiResponse<List<AuditLog>>>> GetAuditLogs()
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var logs = await _context.AuditLogs
|
||
|
|
.OrderByDescending(a => a.Timestamp)
|
||
|
|
.ToListAsync();
|
||
|
|
return Ok(ApiResponse<List<AuditLog>>.Success(logs));
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error retrieving audit logs");
|
||
|
|
return StatusCode(500, ApiResponse<List<AuditLog>>.Error("Internal server error", 500));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
[HttpGet("{id}")]
|
||
|
|
public async Task<ActionResult<ApiResponse<AuditLog>>> GetAuditLog(int id)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var log = await _context.AuditLogs.FindAsync(id);
|
||
|
|
if (log == null)
|
||
|
|
{
|
||
|
|
return NotFound(ApiResponse<AuditLog>.Error("Audit log not found", 404));
|
||
|
|
}
|
||
|
|
return Ok(ApiResponse<AuditLog>.Success(log));
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error retrieving audit log {Id}", id);
|
||
|
|
return StatusCode(500, ApiResponse<AuditLog>.Error("Internal server error", 500));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
[HttpPost]
|
||
|
|
public async Task<ActionResult<ApiResponse<AuditLog>>> CreateAuditLog(AuditLog log)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
if (log.Timestamp == default)
|
||
|
|
{
|
||
|
|
log.Timestamp = DateTime.UtcNow;
|
||
|
|
}
|
||
|
|
|
||
|
|
_context.AuditLogs.Add(log);
|
||
|
|
await _context.SaveChangesAsync();
|
||
|
|
|
||
|
|
return CreatedAtAction(nameof(GetAuditLog), new { id = log.Id }, ApiResponse<AuditLog>.Success(log));
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error creating audit log");
|
||
|
|
return StatusCode(500, ApiResponse<AuditLog>.Error("Internal server error", 500));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|