Skip to content

Commit

Permalink
Audit improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
aritchie committed May 14, 2024
1 parent 5dc93c6 commit 200b758
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,13 @@ protected virtual List<AuditEntry> GetAuditEntries(SaveChangesCompletedEventData
// Dot not audit entities that are not tracked, not changed, or not of type IAuditable
if (entry.State != EntityState.Detached &&
entry.State != EntityState.Unchanged &&
entry.Entity is IAuditable)
entry.Entity is IAuditable auditable)
{
auditable.LastEditUserIdentifier = auditInfo.UserIdentifier;
if (auditable.DateCreated == DateTimeOffset.MinValue)
auditable.DateCreated = DateTimeOffset.UtcNow;

entry.DetectChanges();
var auditEntry = new AuditEntry
{
Operation = ToOperation(entry.State),
Expand All @@ -65,11 +70,33 @@ protected virtual Dictionary<string, object> CalculateChangeSet(EntityEntry entr
var dict = new Dictionary<string, object>();
foreach (var property in entry.Properties)
{
if (property.IsModified && property.CurrentValue is not byte[])
if (this.IsAuditedProperty(property))
{
dict.Add(property.Metadata.Name, property.OriginalValue ?? "NULL");
}
}
return dict;
}


protected virtual bool IsAuditedProperty(PropertyEntry entry)
{
if (!entry.IsModified)
return false;

if (entry.OriginalValue is byte[])
return false;

if (this.IsPropertyIgnored(entry.Metadata.Name))
return false;

return true;
}

protected virtual bool IsPropertyIgnored(string propertyName) => propertyName switch
{
nameof(IAuditable.LastEditUserIdentifier) => false,
nameof(IAuditable.DateCreated) => false,
_ => true
};
}
3 changes: 2 additions & 1 deletion src/Shiny.Extensions.EntityFramework/Auditing/IAuditable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ namespace Shiny.Auditing;

public interface IAuditable
{
AuditInfo Audit { get; set; }
string? LastEditUserIdentifier { get; set; }
DateTimeOffset DateCreated { get; set; }
}

[Owned]
Expand Down

0 comments on commit 200b758

Please sign in to comment.