| | | 1 | | using Microsoft.AspNetCore.Http; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using OzonDomains.Models.Authorization; |
| | | 4 | | using OzonRepositories.Context; |
| | | 5 | | |
| | | 6 | | namespace Services.Authorization.Services; |
| | | 7 | | |
| | | 8 | | public sealed class AuditService : IAuditService |
| | | 9 | | { |
| | | 10 | | private readonly ApplicationDbContext _db; |
| | | 11 | | private readonly IHttpContextAccessor _http; |
| | | 12 | | private readonly ILogger<AuditService> _logger; |
| | | 13 | | |
| | 0 | 14 | | public AuditService(ApplicationDbContext db, IHttpContextAccessor http, ILogger<AuditService> logger) |
| | | 15 | | { |
| | 0 | 16 | | _db = db; |
| | 0 | 17 | | _http = http; |
| | 0 | 18 | | _logger = logger; |
| | 0 | 19 | | } |
| | | 20 | | |
| | | 21 | | public async Task LogAsync( |
| | | 22 | | string action, |
| | | 23 | | string entityType, |
| | | 24 | | string? entityId = null, |
| | | 25 | | string? oldValue = null, |
| | | 26 | | string? newValue = null, |
| | | 27 | | string? comment = null, |
| | | 28 | | CancellationToken ct = default) |
| | | 29 | | { |
| | | 30 | | try |
| | | 31 | | { |
| | 0 | 32 | | var ctx = _http.HttpContext; |
| | 0 | 33 | | var entry = new AuditLogEntry |
| | 0 | 34 | | { |
| | 0 | 35 | | Action = action, |
| | 0 | 36 | | EntityType = entityType, |
| | 0 | 37 | | EntityId = entityId, |
| | 0 | 38 | | OldValue = oldValue, |
| | 0 | 39 | | NewValue = newValue, |
| | 0 | 40 | | Comment = comment, |
| | 0 | 41 | | ActorUserId = ctx?.User?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, |
| | 0 | 42 | | ActorUserName = ctx?.User?.Identity?.Name, |
| | 0 | 43 | | IpAddress = ctx?.Connection?.RemoteIpAddress?.ToString() |
| | 0 | 44 | | }; |
| | 0 | 45 | | _db.AuditLogEntries.Add(entry); |
| | 0 | 46 | | await _db.SaveChangesAsync(ct); |
| | 0 | 47 | | } |
| | 0 | 48 | | catch (Exception ex) |
| | | 49 | | { |
| | 0 | 50 | | _logger.LogError(ex, "Не удалось записать аудит {Action} {EntityType} {EntityId}", action, entityType, entit |
| | 0 | 51 | | } |
| | 0 | 52 | | } |
| | | 53 | | } |