mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 03:11:10 +00:00
Centralizes audit column ownership in the auditing interceptor
Removes explicit audit assignments from mappings, handlers, repositories, seeding, and background jobs, leaving the auditing interceptor as the only writer of the audit columns for ordinary saves. Adds a one-time initialization save so setup can attribute the original admin account and seeded rows to the SYSTEM audit identity, while ordinary anonymous writes remain unattributed with Guid.Empty.
This commit is contained in:
1 parent
b56fabf5df
commit
7253f1507c
98 files changed
+731
-516
No files matched your search
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
@@ -64,6 +65,9 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
||||
{
|
||||
if (context is null)
|
||||
return;
|
||||
// Initialization is the one save whose audit identity is provided explicitly, because no user account exists yet.
|
||||
if (context is LuminaDbContext luminaDbContext && luminaDbContext.IsInitializationSave)
|
||||
return;
|
||||
|
||||
Guid? userId = _currentUserService.UserId;
|
||||
DateTime utcNow = _dateTimeProvider.UtcNow;
|
||||
@@ -106,6 +110,6 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
||||
|
||||
// Set modification properties.
|
||||
entry.Entity.UpdatedOnUtc = utcNow;
|
||||
entry.Entity.UpdatedBy = userId ?? Guid.Parse("11111111-1111-1111-1111-111111111111"); // "SYSTEM" user Id.
|
||||
entry.Entity.UpdatedBy = userId ?? default;
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -89,10 +89,7 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
DisplayName = displayName,
|
||||
LegalName = legalName,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
LegalName = legalName
|
||||
};
|
||||
_luminaDbContext.MediaContributors.Add(contributor);
|
||||
return contributor;
|
||||
|
||||
@@ -173,12 +173,7 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository
|
||||
ArtworkType = ArtworkType.Cover,
|
||||
Ordinal = 0,
|
||||
FileName = fileName,
|
||||
Status = ArtworkStatus.Enriched,
|
||||
CreatedOnUtc = now,
|
||||
CreatedBy = Guid.Empty,
|
||||
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
Status = ArtworkStatus.Enriched
|
||||
});
|
||||
}
|
||||
else
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
@@ -41,18 +42,17 @@ public class DataSeedService : IDataSeedService
|
||||
/// <summary>
|
||||
/// Sets up default authorization permissions in the system.
|
||||
/// </summary>
|
||||
/// <param name="adminId">The unique identifier of the admin admin user who will own these permissions.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken)
|
||||
public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Create the default authorization permissions and add them to the repository.
|
||||
PermissionEntity[] defaultPermissions =
|
||||
[
|
||||
new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow },
|
||||
new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow },
|
||||
new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow },
|
||||
new() { PermissionName = AuthorizationPermission.CanCreateLibraries, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }
|
||||
new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
|
||||
new() { PermissionName = AuthorizationPermission.CanDeleteUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
|
||||
new() { PermissionName = AuthorizationPermission.CanRegisterUsers, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId },
|
||||
new() { PermissionName = AuthorizationPermission.CanCreateLibraries, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId }
|
||||
];
|
||||
foreach (PermissionEntity permission in defaultPermissions)
|
||||
{
|
||||
@@ -60,7 +60,7 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertPermissionResult.IsFailure)
|
||||
return insertPermissionResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -69,15 +69,14 @@ public class DataSeedService : IDataSeedService
|
||||
/// <summary>
|
||||
/// Sets up default authorization roles in the system.
|
||||
/// </summary>
|
||||
/// <param name="userId">The unique identifier of the admin user for whom roles will be set.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken)
|
||||
public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Create the default authorization roles and add them to the repository.
|
||||
RoleEntity[] defaultRoles =
|
||||
[
|
||||
new() { RoleName = AuthorizationRoles.ADMIN, CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow }
|
||||
new() { RoleName = AuthorizationRoles.ADMIN, CreatedOnUtc = _dateTimeProvider.UtcNow, CreatedBy = AuditIdentities.s_systemUserId }
|
||||
];
|
||||
foreach (RoleEntity role in defaultRoles)
|
||||
{
|
||||
@@ -85,7 +84,7 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertRoleResult.IsFailure)
|
||||
return insertRoleResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -94,10 +93,9 @@ public class DataSeedService : IDataSeedService
|
||||
/// <summary>
|
||||
/// Assigns admin role permissions to the admin user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The unique identifier of the admin user to receive admin role permissions.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
|
||||
public async Task<Result<Created>> SetAdminRolePermissionsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Get the admin role.
|
||||
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
|
||||
@@ -121,14 +119,14 @@ public class DataSeedService : IDataSeedService
|
||||
PermissionId = permission.Id,
|
||||
Role = getAdminRoleResult.Value,
|
||||
RoleId = getAdminRoleResult.Value.Id,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
CreatedBy = AuditIdentities.s_systemUserId
|
||||
};
|
||||
Result<Created> insertRolePermissionResult = await _unitOfWork.RolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
|
||||
if (insertRolePermissionResult.IsFailure)
|
||||
return insertRolePermissionResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -161,18 +159,18 @@ public class DataSeedService : IDataSeedService
|
||||
// Add the admin role to the admin user.
|
||||
UserRoleEntity userRole = new()
|
||||
{
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
Role = getAdminRoleResult.Value,
|
||||
RoleId = getAdminRoleResult.Value.Id,
|
||||
User = getUserResult.Value,
|
||||
UserId = getUserResult.Value.Id
|
||||
UserId = getUserResult.Value.Id,
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
CreatedBy = AuditIdentities.s_systemUserId
|
||||
};
|
||||
Result<Created> insertUserRoleResult = await _unitOfWork.UserRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
|
||||
if (insertUserRoleResult.IsFailure)
|
||||
return insertUserRoleResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -208,7 +206,7 @@ public class DataSeedService : IDataSeedService
|
||||
if (insertScheduledJobResult.IsFailure)
|
||||
return insertScheduledJobResult.Errors;
|
||||
}
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsInitializationAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Created;
|
||||
@@ -241,9 +239,7 @@ public class DataSeedService : IDataSeedService
|
||||
LastStartedOnUtc = null,
|
||||
LastCompletedOnUtc = null,
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
CreatedBy = adminUserId,
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
CreatedBy = AuditIdentities.s_systemUserId
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,12 @@ public class LuminaDbContext : DbContext
|
||||
/// </summary>
|
||||
public virtual DbSet<MediaResumePointEntity> MediaResumePoints { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the changes are being saved by the one-time application initialization, whose audit values are provided explicitly instead of
|
||||
/// being stamped by the auditing interceptor.
|
||||
/// </summary>
|
||||
internal bool IsInitializationSave { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -467,6 +467,35 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await SaveChangesCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made during the one-time application initialization, whose audit values are provided explicitly by the bootstrap code instead of
|
||||
/// being stamped by the auditing interceptor.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> SaveChangesAsInitializationAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_luminaDbContext.IsInitializationSave = true;
|
||||
try
|
||||
{
|
||||
return await SaveChangesCoreAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_luminaDbContext.IsInitializationSave = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database, reporting expected persistence conflicts as failure results.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> SaveChangesCoreAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user