refactor(identity): isolate ASP.NET Identity in Infrastructure
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and tests (pull_request) Failing after 4m5s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 1s

This commit is contained in:
arnaud.dartois committed 2026-11-04 11:37:53 +01:00
1 parent 2bf3dbc95b
commit 622add46ad
109 files changed
+4076 -1197

No files matched your search

+2 -2
View File
@@ -1,5 +1,5 @@
# Server/PWA: restore the complete project graph from locked dependencies.
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa AS build
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
WORKDIR /src
ARG VERSION=0.0.0-local
COPY global.json Directory.Build.props Directory.Build.targets ./
@@ -8,7 +8,7 @@ COPY install/ ./install/
RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj --locked-mode
RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:d5633778c754e89a386882eddf8dbee6942447a8a4b8267c19cf1e1158d0b0ac
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
WORKDIR /app
RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata && rm -rf /var/lib/apt/lists/*
ENV ASPNETCORE_URLS=http://+:8080
+2 -2
View File
@@ -1,6 +1,6 @@
# CPU agent: use glibc for ONNX native dependencies. GPU variants need a
# separately validated .NET/native-library runtime and are not published here.
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa AS build
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
WORKDIR /src
ARG VERSION=0.0.0-local
ARG TARGET_RUNTIME=cpu
@@ -10,7 +10,7 @@ COPY src/ ./src/
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:d5633778c754e89a386882eddf8dbee6942447a8a4b8267c19cf1e1158d0b0ac
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
WORKDIR /app
RUN apt-get update -qq && apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata && rm -rf /var/lib/apt/lists/*
RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
+3
View File
@@ -8,6 +8,9 @@ description: Implement and review Heimdall account, password, session, email con
Read `AGENTS.md`, the `AUTH-BOOTSTRAP` entry in `todo.md`, and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
- Keep ASP.NET Core Identity packages and types inside Infrastructure. Domain must not reference Identity; Application uses `IIdentityAccountService` and `IdentityAccount` only. Put Identity EF entities (`IdentityAppUser`, `IdentityAppRole`) and `UserManager`/`RoleManager` adapters in Infrastructure. Keep user-related Domain relationships keyed by `Guid UserId`; configure their foreign keys to the Infrastructure user entity.
- When creating an Identity user, copy the generated `SecurityStamp` back into the application account before building the first session/JWT. Cover bootstrap and regular user creation with a relational session validation test.
- Moving Identity model classes without changing tables should produce an explicit empty EF migration and a snapshot containing the Infrastructure entity types. Verify migration compatibility against PostgreSQL before release.
- Keep bootstrap one-time and PostgreSQL-serializable. Anonymous registration stays disabled after bootstrap; role and account creation failures must not be reported as success.
- Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed.
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
@@ -4,6 +4,7 @@ using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Heimdall.Application.Services;
namespace Heimdall.Application.Assignments.Commands.CreateUserCameraAccess;
@@ -16,16 +17,14 @@ public record CreateUserCameraAccessCommand(
public class CreateUserCameraAccessHandler : IRequestHandler<CreateUserCameraAccessCommand, ServiceResult<UserCameraAccessResponse>>
{
private readonly IApplicationDbContext _db;
private readonly IIdentityAccountService _identity;
public CreateUserCameraAccessHandler(IApplicationDbContext db) => _db = db;
public CreateUserCameraAccessHandler(IApplicationDbContext db, IIdentityAccountService identity) => (_db, _identity) = (db, identity);
public async Task<ServiceResult<UserCameraAccessResponse>> Handle(CreateUserCameraAccessCommand request, CancellationToken ct)
{
// Verify user exists
var user = await _db.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Id == request.UserId, ct)
.ConfigureAwait(false);
var user = await _identity.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult<UserCameraAccessResponse>.NotFound("User not found");
@@ -4,6 +4,7 @@ using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using Heimdall.Application.Services;
namespace Heimdall.Application.Assignments.Commands.ReplaceUserCameraAccess;
@@ -12,15 +13,14 @@ public sealed class ReplaceUserCameraAccessCommandHandler
{
private const int MaximumGrantCount = 500;
private readonly IApplicationDbContext _db;
private readonly IIdentityAccountService _identity;
public ReplaceUserCameraAccessCommandHandler(IApplicationDbContext db) => _db = db;
public ReplaceUserCameraAccessCommandHandler(IApplicationDbContext db, IIdentityAccountService identity) => (_db, _identity) = (db, identity);
public async Task<ServiceResult<IReadOnlyList<UserCameraAccessResponse>>> Handle(
ReplaceUserCameraAccessCommand request, CancellationToken ct)
{
var userExists = await _db.Users.AsNoTracking().AnyAsync(u => u.Id == request.UserId, ct)
.ConfigureAwait(false);
if (!userExists)
if (await _identity.FindByIdAsync(request.UserId, ct).ConfigureAwait(false) is null)
return ServiceResult<IReadOnlyList<UserCameraAccessResponse>>.NotFound("User not found");
if (request.Grants.Count > MaximumGrantCount)
@@ -1,4 +1,5 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
@@ -19,7 +20,8 @@ public class GetAuditLogsQueryHandler
: IRequestHandler<GetAuditLogsQuery, ServiceResult<PagedResult<AuditLogResponse>>>
{
private readonly IApplicationDbContext _db;
public GetAuditLogsQueryHandler(IApplicationDbContext db) => _db = db;
private readonly IUserRepository _users;
public GetAuditLogsQueryHandler(IApplicationDbContext db, IUserRepository users) => (_db, _users) = (db, users);
public async Task<ServiceResult<PagedResult<AuditLogResponse>>> Handle(
GetAuditLogsQuery request, CancellationToken ct)
{
@@ -49,11 +51,19 @@ public class GetAuditLogsQueryHandler
.Take(request.PageSize)
.Select(al => new AuditLogResponse(
al.Id, al.UserId,
al.User != null ? al.User.Email : null,
(string?)null,
al.Action, al.ResourceType, al.ResourceId,
al.OldValue, al.NewValue, al.IpAddress, al.Timestamp))
.ToListAsync(ct);
var userIds = items.Where(item => item.UserId.HasValue).Select(item => item.UserId!.Value).Distinct().ToArray();
var emails = userIds.Length == 0
? new Dictionary<Guid, string?>()
: await _users.GetEmailsAsync(userIds, ct).ConfigureAwait(false);
items = items.Select(item => item.UserId.HasValue && emails.TryGetValue(item.UserId.Value, out var email)
? item with { UserEmail = email }
: item).ToList();
// Batch-resolve resource names
var siteIds = items.Where(i => i.ResourceType == "Site" && i.ResourceId != null)
.Select(i => Guid.Parse(i.ResourceId!)).Distinct().ToList();
+5 -6
View File
@@ -2,21 +2,20 @@ using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Application.Auth;
internal static class AuthHelper
{
internal static async Task<ServiceResult<AuthResponse>> CreateAuthResponseAsync(
AppUser user,
IdentityAccount user,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
UserManager<AppUser> userManager,
IIdentityAccountService userManager,
DateTime? sessionStarted = null,
CancellationToken ct = default)
{
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
var roles = await userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
var (accessToken, expiresAt) = sessionStarted is null
@@ -34,10 +33,10 @@ internal static class AuthHelper
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions])));
}
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager,
internal static async Task<UserInfo> MapUserInfoAsync(IdentityAccount user, IIdentityAccountService userManager,
IRolePermissionService rolePermissionService, CancellationToken ct)
{
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
var roles = await userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions]);
}
@@ -3,7 +3,6 @@ using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
@@ -11,13 +10,13 @@ namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminCommand, ServiceResult<AuthResponse>>
{
private readonly IAuthDataService _authData;
private readonly UserManager<AppUser> _users;
private readonly IIdentityAccountService _users;
private readonly IJwtService _jwt;
private readonly IRolePermissionService _permissions;
private readonly IPasswordBreachChecker _breachChecker;
private readonly ILogger<BootstrapAdminHandler> _logger;
public BootstrapAdminHandler(IAuthDataService authData, UserManager<AppUser> users, IJwtService jwt,
public BootstrapAdminHandler(IAuthDataService authData, IIdentityAccountService users, IJwtService jwt,
IRolePermissionService permissions, IPasswordBreachChecker breachChecker,
ILogger<BootstrapAdminHandler> logger)
{
@@ -39,25 +38,25 @@ public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminComman
if (await _authData.HasAnyUsersAsync(token).ConfigureAwait(false))
return ServiceResult<AuthResponse>.Conflict("Initial administrator setup has already been completed.");
var user = new AppUser
var user = new IdentityAccount
{
UserName = request.Email,
Email = request.Email,
DisplayName = request.DisplayName,
EmailConfirmed = true
};
var created = await _users.CreateAsync(user, request.Password).ConfigureAwait(false);
var created = await _users.CreateAsync(user, request.Password, ct).ConfigureAwait(false);
if (!created.Succeeded)
{
_logger.LogWarning("Identity rejected initial administrator creation with codes {Codes}", string.Join(',', created.Errors.Select(e => e.Code)));
_logger.LogWarning("Identity rejected initial administrator creation with codes {Codes}", string.Join(',', created.ErrorCodes));
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
}
var role = await _users.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
var role = await _users.AddToRoleAsync(user, "Admin", token).ConfigureAwait(false);
if (!role.Succeeded)
{
await _users.DeleteAsync(user).ConfigureAwait(false);
_logger.LogWarning("Identity rejected initial administrator role assignment with codes {Codes}", string.Join(',', role.Errors.Select(e => e.Code)));
await _users.DeleteAsync(user, ct).ConfigureAwait(false);
_logger.LogWarning("Identity rejected initial administrator role assignment with codes {Codes}", string.Join(',', role.ErrorCodes));
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
}
@@ -2,19 +2,18 @@ using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.ChangePassword;
public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IPasswordBreachChecker _breachChecker;
private readonly ILogger<ChangePasswordHandler> _logger;
public ChangePasswordHandler(
UserManager<AppUser> userManager,
IIdentityAccountService userManager,
IPasswordBreachChecker breachChecker,
ILogger<ChangePasswordHandler> logger)
{
@@ -27,7 +26,7 @@ public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, Serv
{
_logger.LogDebug("ChangePassword: UserId={UserId}", request.UserId);
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("ChangePassword: User not found UserId={UserId}", request.UserId);
@@ -42,15 +41,15 @@ public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, Serv
"This password has appeared in a data breach. Please choose a different password.");
}
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword).ConfigureAwait(false);
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword, ct).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogWarning("Identity rejected password change with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
_logger.LogWarning("Identity rejected password change with codes {Codes}", string.Join(',', result.ErrorCodes));
return ServiceResult.Failure("Password change failed");
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp)
{
_logger.LogError("Identity could not revoke sessions after password change for user {UserId}", request.UserId);
return ServiceResult.Failure("Password changed but active sessions could not be revoked", 500);
@@ -3,19 +3,19 @@ using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCommand, ServiceResult<Complete2faSetupResponse>>
{
private readonly UserManager<AppUser> _users;
private readonly IIdentityAccountService _users;
private readonly IApplicationDbContext _db;
private readonly ILogger<Complete2faSetupHandler> _logger;
public Complete2faSetupHandler(UserManager<AppUser> users, IApplicationDbContext db, ILogger<Complete2faSetupHandler> logger)
public Complete2faSetupHandler(IIdentityAccountService users, IApplicationDbContext db, ILogger<Complete2faSetupHandler> logger)
{
_users = users;
_db = db;
@@ -26,12 +26,12 @@ public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCo
{
if (string.IsNullOrWhiteSpace(request.Code) || request.Code.Trim().Length != 6)
return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
var user = await _users.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
var user = await _users.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null) return ServiceResult<Complete2faSetupResponse>.NotFound("User not found");
if (await _users.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
if (await _users.GetTwoFactorEnabledAsync(user, ct).ConfigureAwait(false))
return ServiceResult<Complete2faSetupResponse>.Conflict("Two-factor authentication is already enabled");
var valid = await _users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, request.Code.Trim()).ConfigureAwait(false);
var valid = await _users.VerifyAuthenticatorTokenAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
if (!valid) return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
var oldCodes = await _db.UserRecoveryCodes.Where(x => x.UserId == user.Id).ToListAsync(ct).ConfigureAwait(false);
@@ -40,7 +40,7 @@ public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCo
foreach (var code in codes) _db.UserRecoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(code)));
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
var result = await _users.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);
var result = await _users.SetTwoFactorEnabledAsync(user, true, ct).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogWarning("Identity rejected enabling two-factor authentication for user {UserId}", request.UserId);
@@ -48,10 +48,10 @@ public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCo
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to enable two-factor authentication");
}
var stamp = await _users.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
var stamp = await _users.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp)
{
await _users.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
await _users.SetTwoFactorEnabledAsync(user, false, ct).ConfigureAwait(false);
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
_logger.LogError("Identity could not revoke existing sessions after enabling two-factor authentication for user {UserId}", user.Id);
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to complete two-factor setup");
@@ -1,17 +1,17 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Commands.ConfirmEmail;
public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly ILogger<ConfirmEmailHandler> _logger;
public ConfirmEmailHandler(UserManager<AppUser> userManager, ILogger<ConfirmEmailHandler> logger)
public ConfirmEmailHandler(IIdentityAccountService userManager, ILogger<ConfirmEmailHandler> logger)
{
_userManager = userManager;
_logger = logger;
@@ -27,7 +27,7 @@ public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceR
return ServiceResult.Failure("Invalid user ID");
}
var user = await _userManager.FindByIdAsync(request.UserId).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(Guid.TryParse(request.UserId, out var parsedUserId) ? parsedUserId : Guid.Empty, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("ConfirmEmail: User not found UserId={UserId}", request.UserId);
@@ -41,10 +41,10 @@ public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceR
}
var decodedToken = Uri.UnescapeDataString(request.Token);
var result = await _userManager.ConfirmEmailAsync(user, decodedToken).ConfigureAwait(false);
var result = await _userManager.ConfirmEmailAsync(user, decodedToken, ct).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogWarning("Identity rejected email confirmation with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
_logger.LogWarning("Identity rejected email confirmation with codes {Codes}", string.Join(',', result.ErrorCodes));
return ServiceResult.Failure("Email confirmation failed");
}
@@ -1,19 +1,19 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Commands.Disable2fa;
public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IApplicationDbContext _db;
private readonly ILogger<Disable2faHandler> _logger;
public Disable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Disable2faHandler> logger)
public Disable2faHandler(IIdentityAccountService userManager, IApplicationDbContext db, ILogger<Disable2faHandler> logger)
{
_userManager = userManager;
_db = db;
@@ -24,7 +24,7 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
{
_logger.LogDebug("Disable2fa: UserId={UserId}", request.UserId);
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Disable2fa: User not found UserId={UserId}", request.UserId);
@@ -32,18 +32,18 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
}
if (string.IsNullOrEmpty(request.CurrentPassword)
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword, ct).ConfigureAwait(false))
return ServiceResult.Failure("Current password is incorrect", 400);
var result = await _userManager.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
var result = await _userManager.SetTwoFactorEnabledAsync(user, false, ct).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogError("Disable2fa: Failed UserId={UserId}", request.UserId);
return ServiceResult.Failure("Failed to disable 2FA");
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp) return ServiceResult.Failure("Unable to revoke existing sessions");
// Purger les codes de récupération — ils ne sont plus valables
var codes = await _db.UserRecoveryCodes
@@ -3,19 +3,19 @@ using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Commands.Enable2fa;
public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<Enable2faResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IApplicationDbContext _db;
private readonly ILogger<Enable2faHandler> _logger;
public Enable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
public Enable2faHandler(IIdentityAccountService userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
{
_userManager = userManager;
_db = db;
@@ -26,7 +26,7 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
{
_logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId);
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId);
@@ -34,18 +34,18 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
}
if (string.IsNullOrEmpty(request.CurrentPassword)
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword, ct).ConfigureAwait(false))
return ServiceResult<Enable2faResponse>.Failure("Current password is incorrect", 400);
if (await _userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
if (await _userManager.GetTwoFactorEnabledAsync(user, ct).ConfigureAwait(false))
return ServiceResult<Enable2faResponse>.Conflict("Two-factor authentication is already enabled");
// Generate authenticator key for the QR code setup (l'utilisateur doit scanner le code avec son app)
// Note: key is generated AFTER enabling 2FA so it's available immediately
var reset = await _userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);
var reset = await _userManager.ResetAuthenticatorKeyAsync(user, ct).ConfigureAwait(false);
if (!reset.Succeeded)
return ServiceResult<Enable2faResponse>.Failure("Unable to initialize authenticator setup");
var key = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);
var key = await _userManager.GetAuthenticatorKeyAsync(user, ct).ConfigureAwait(false);
if (string.IsNullOrEmpty(key))
{
_logger.LogError("Enable2fa: Failed to generate authenticator key UserId={UserId}", request.UserId);
@@ -4,19 +4,18 @@ using Heimdall.Application.Localization;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.ForgotPassword;
public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IEmailService _emailService;
private readonly ILogger<ForgotPasswordHandler> _logger;
public ForgotPasswordHandler(
UserManager<AppUser> userManager,
IIdentityAccountService userManager,
IEmailService emailService,
ILogger<ForgotPasswordHandler> logger)
{
@@ -29,15 +28,15 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
{
_logger.LogInformation("Password reset request received");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
var user = await _userManager.FindByEmailAsync(request.Email, ct).ConfigureAwait(false);
// Ne pas divulguer si l'email existe ou pas
if (user is null || !await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false))
if (user is null || !await _userManager.IsEmailConfirmedAsync(user, ct).ConfigureAwait(false))
{
_logger.LogInformation("Password reset request completed without an eligible account");
return ServiceResult.Success();
}
var token = await _userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);
var token = await _userManager.GeneratePasswordResetTokenAsync(user, ct).ConfigureAwait(false);
var encodedToken = Uri.EscapeDataString(token);
var resetLink = $"heimdall://reset-password?email={Uri.EscapeDataString(request.Email)}&token={encodedToken}";
@@ -5,14 +5,13 @@ using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace Heimdall.Application.Auth.Commands.Login;
public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IAuthSignInService _signInService;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
@@ -22,7 +21,7 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
private readonly ILogger<LoginHandler> _logger;
public LoginHandler(
UserManager<AppUser> userManager,
IIdentityAccountService userManager,
IAuthSignInService signInService,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
@@ -45,7 +44,7 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
{
_logger.LogInformation("Login attempt received");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
var user = await _userManager.FindByEmailAsync(request.Email, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Login rejected: account unavailable");
@@ -53,14 +52,14 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
if (await _userManager.IsLockedOutAsync(user))
if (await _userManager.IsLockedOutAsync(user, ct))
{
_logger.LogWarning("Login rejected: account unavailable");
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
var result = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false);
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user, ct);
if (result.ResultType == SignInResultType.LockedOut)
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
if (result.ResultType != SignInResultType.Success
@@ -6,7 +6,6 @@ using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
@@ -15,14 +14,14 @@ namespace Heimdall.Application.Auth.Commands.RefreshToken;
public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceResult<AuthResponse>>
{
private readonly IJwtService _jwtService;
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IRolePermissionService _rolePermissionService;
private readonly IAuthDataService _authData;
private readonly ILogger<RefreshTokenHandler> _logger;
public RefreshTokenHandler(
IJwtService jwtService,
UserManager<AppUser> userManager,
IIdentityAccountService userManager,
IRolePermissionService rolePermissionService,
IAuthDataService authData,
ILogger<RefreshTokenHandler> logger)
@@ -61,7 +60,9 @@ public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceR
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
}
var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false);
if (!Guid.TryParse(userId, out var parsedUserId))
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
var user = await _userManager.FindByIdAsync(parsedUserId, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("RefreshToken: User not found UserId={UserId}", userId);
@@ -1,17 +1,17 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Commands.ResetPassword;
public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly ILogger<ResetPasswordHandler> _logger;
public ResetPasswordHandler(UserManager<AppUser> userManager, ILogger<ResetPasswordHandler> logger)
public ResetPasswordHandler(IIdentityAccountService userManager, ILogger<ResetPasswordHandler> logger)
{
_userManager = userManager;
_logger = logger;
@@ -21,7 +21,7 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
{
_logger.LogInformation("Password reset completion requested");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
var user = await _userManager.FindByEmailAsync(request.Email, ct).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Password reset completion rejected");
@@ -29,15 +29,15 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
}
var decodedToken = Uri.UnescapeDataString(request.Token);
var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword).ConfigureAwait(false);
var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword, ct).ConfigureAwait(false);
if (!result.Succeeded)
{
_logger.LogWarning("Identity rejected password reset with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
_logger.LogWarning("Identity rejected password reset with codes {Codes}", string.Join(',', result.ErrorCodes));
return ServiceResult.Failure("Invalid or expired reset request", 400);
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp)
{
_logger.LogError("Identity could not revoke sessions after password reset");
return ServiceResult.Failure("Password reset failed", 500);
@@ -4,7 +4,6 @@ using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
@@ -12,14 +11,14 @@ namespace Heimdall.Application.Auth.Commands.Verify2fa;
public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<AuthResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
private readonly IApplicationDbContext _db;
private readonly ILogger<Verify2faHandler> _logger;
public Verify2faHandler(
UserManager<AppUser> userManager,
IIdentityAccountService userManager,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
IApplicationDbContext db,
@@ -38,18 +37,17 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
if (challenge is null)
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired challenge");
var user = await _userManager.FindByIdAsync(challenge.UserId.ToString());
var user = await _userManager.FindByIdAsync(challenge.UserId, ct);
var emailSetting = await _db.AppSettings.AsNoTracking()
.Where(x => x.Key == "email.confirmation.required").Select(x => x.Value).SingleOrDefaultAsync(ct);
var emailRequired = string.Equals(emailSetting, "true", StringComparison.OrdinalIgnoreCase);
if (user is null || user.SecurityStamp != challenge.SecurityStamp
|| !await _userManager.GetTwoFactorEnabledAsync(user)
|| await _userManager.IsLockedOutAsync(user)
|| !await _userManager.GetTwoFactorEnabledAsync(user, ct)
|| await _userManager.IsLockedOutAsync(user, ct)
|| (emailRequired && !user.EmailConfirmed))
return ServiceResult<AuthResponse>.Unauthorized("Account unavailable");
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
var isValid = await _userManager.VerifyAuthenticatorTokenAsync(user, request.Code, ct).ConfigureAwait(false);
if (!isValid)
{
@@ -58,14 +56,14 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
if (!redeemed)
{
_logger.LogWarning("Verify2fa: Invalid code UserId={UserId}", challenge.UserId);
await _userManager.AccessFailedAsync(user);
if (await _userManager.IsLockedOutAsync(user))
await _userManager.UpdateSecurityStampAsync(user);
await _userManager.AccessFailedAsync(user, ct);
if (await _userManager.IsLockedOutAsync(user, ct))
await _userManager.UpdateSecurityStampAsync(user, ct);
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
}
var stampUpdate = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stampUpdate.Succeeded)
var stampUpdate = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stampUpdate)
{
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
@@ -75,12 +73,12 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1)
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
await _userManager.ResetAccessFailedCountAsync(user);
await _userManager.ResetAccessFailedCountAsync(user, ct);
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
}
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct)
private async Task<bool> TryRedeemRecoveryCodeAsync(IdentityAccount user, string code, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(code))
return false;
@@ -3,6 +3,7 @@ using Heimdall.Application.Auth.Commands.Login;
using Heimdall.Application.Auth.Commands.Register;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Mapping;
@@ -10,7 +11,7 @@ public class AuthMappingProfile : Profile
{
public AuthMappingProfile()
{
CreateMap<AppUser, UserInfo>()
CreateMap<IdentityAccount, UserInfo>()
.ForMember(d => d.Email, o => o.MapFrom(s => s.Email ?? string.Empty))
.ForMember(d => d.Roles, o => o.Ignore());
@@ -1,9 +1,7 @@
using System.Security.Claims;
using System.Globalization;
using Heimdall.Application.Services;
using System.Security.Claims;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Auth.Services;
@@ -13,40 +11,35 @@ public static class AccountSessionPolicy
public const string StampClaim = "security_stamp";
public const string StartedClaim = "session_started";
public static async Task<bool> IsValidAsync(ClaimsPrincipal principal, UserManager<AppUser> users, IAuthDataService data, CancellationToken ct)
public static async Task<bool> IsValidAsync(ClaimsPrincipal principal, IIdentityAccountService users, IAuthDataService data, CancellationToken ct)
{
if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
return false;
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var user = id is null ? null : await users.FindByIdAsync(id);
if (!TryReadStarted(principal, out _)) return false;
if (!Guid.TryParse(principal.FindFirstValue(ClaimTypes.NameIdentifier), out var userId)) return false;
var user = await users.FindByIdAsync(userId, ct).ConfigureAwait(false);
if (user is null || string.IsNullOrEmpty(user.SecurityStamp)
|| principal.FindFirstValue(StampClaim) != user.SecurityStamp
|| await users.IsLockedOutAsync(user)) return false;
var required = await data.GetSettingValueAsync("email.confirmation.required", ct);
if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed) return false;
return true;
|| await users.IsLockedOutAsync(user, ct).ConfigureAwait(false)) return false;
var required = await data.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
return !string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
}
/// <summary>Validates a live connection against persisted values without using Identity's tracked user cache.</summary>
public static async Task<bool> IsValidLiveAsync(ClaimsPrincipal principal, IApplicationDbContext db, CancellationToken ct)
/// <summary>Checks session state from a fresh persisted projection, bypassing Identity's tracked user cache.</summary>
public static async Task<bool> IsValidLiveAsync(ClaimsPrincipal principal, IIdentityAccountService users, IApplicationDbContext db, CancellationToken ct)
{
if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
return false;
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (!Guid.TryParse(id, out var userId)) return false;
var user = await db.Users.AsNoTracking().Where(u => u.Id == userId)
.Select(u => new { u.SecurityStamp, u.LockoutEnabled, u.LockoutEnd, u.EmailConfirmed })
.SingleOrDefaultAsync(ct);
if (!TryReadStarted(principal, out _)) return false;
if (!Guid.TryParse(principal.FindFirstValue(ClaimTypes.NameIdentifier), out var userId)) return false;
var user = await users.GetSessionRecordAsync(userId, ct).ConfigureAwait(false);
if (user is null || string.IsNullOrEmpty(user.SecurityStamp)
|| principal.FindFirstValue(StampClaim) != user.SecurityStamp
|| (user.LockoutEnabled && user.LockoutEnd > DateTimeOffset.UtcNow)) return false;
var confirmationRequired = await db.AppSettings.AsNoTracking()
.Where(s => s.Key == "email.confirmation.required")
.Select(s => s.Value).SingleOrDefaultAsync(ct);
return !string.Equals(confirmationRequired, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
var required = await db.AppSettings.AsNoTracking().Where(setting => setting.Key == "email.confirmation.required")
.Select(setting => setting.Value).SingleOrDefaultAsync(ct).ConfigureAwait(false);
return !string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
}
private static bool TryReadStarted(ClaimsPrincipal principal, out DateTime started)
=> DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out started)
&& started <= DateTime.UtcNow && started.AddDays(7) > DateTime.UtcNow;
}
@@ -0,0 +1,9 @@
using System.Security.Claims;
namespace Heimdall.Application.Auth.Services;
internal static class ClaimsPrincipalExtensions
{
internal static string? FindFirstValue(this ClaimsPrincipal principal, string claimType)
=> principal.FindFirst(claimType)?.Value;
}
@@ -3,6 +3,7 @@ using System.Text;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Heimdall.Application.Services;
namespace Heimdall.Application.Auth.Services;
@@ -10,7 +11,7 @@ public static class LoginChallengeService
{
public static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
public static async Task<string> CreateAsync(IApplicationDbContext db, AppUser user, CancellationToken ct)
public static async Task<string> CreateAsync(IApplicationDbContext db, IdentityAccount user, CancellationToken ct)
{
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
db.GetSet<LoginChallenge>().Add(new LoginChallenge
@@ -12,7 +12,6 @@ public interface IApplicationDbContext
DbSet<AnalysisJob> AnalysisJobs { get; }
DbSet<ApiKey> ApiKeys { get; }
DbSet<AppSetting> AppSettings { get; }
DbSet<AppUser> Users { get; }
DbSet<AuditLog> AuditLogs { get; }
DbSet<Camera> Cameras { get; }
DbSet<CameraAssignment> CameraAssignments { get; }
@@ -46,10 +45,6 @@ public interface IApplicationDbContext
DbSet<Vehicle> Vehicles { get; }
DbSet<GroupCameraAccess> GroupCameraAccesses { get; }
// Identity tables (for synchronous admin checks in IQueryable filters)
DbSet<AppRole> Roles { get; }
DbSet<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>> UserRoles { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default);
@@ -10,4 +10,10 @@ public interface IUserRepository
Task AddAuditLogAsync(Guid? userId, string action, string resourceType, string? resourceId, string? oldValue, string? newValue, CancellationToken ct);
Task SetUserSitesAsync(Guid userId, IList<Guid> siteIds, CancellationToken ct);
Task RemoveUserDataAsync(Guid userId, CancellationToken ct);
Task<bool> ExistsAsync(Guid userId, CancellationToken ct);
Task<int> CountUsersAsync(CancellationToken ct);
Task<IReadOnlyDictionary<Guid, string>> GetLanguagesAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct);
Task<IReadOnlyDictionary<Guid, string?>> GetEmailsAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct);
Task<IReadOnlyList<GroupMemberResponse>> GetGroupMembersAsync(Guid groupId, CancellationToken ct);
Task<bool> IsAdminAsync(Guid userId, CancellationToken ct);
}
@@ -1,9 +1,8 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Localization;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Notifications;
@@ -12,26 +11,18 @@ public class EventCreatedNotificationHandler : INotificationHandler<EventCreated
private readonly IEventBroadcastService _broadcast;
private readonly ICameraAccessService _cameraAccess;
private readonly INotificationService _notifications;
private readonly IApplicationDbContext? _context;
public EventCreatedNotificationHandler(
IEventBroadcastService broadcast,
ICameraAccessService cameraAccess,
INotificationService notifications)
: this(broadcast, cameraAccess, notifications, null)
{
}
private readonly IUserRepository? _users;
public EventCreatedNotificationHandler(
IEventBroadcastService broadcast,
ICameraAccessService cameraAccess,
INotificationService notifications,
IApplicationDbContext? context)
IUserRepository? users = null)
{
_broadcast = broadcast;
_cameraAccess = cameraAccess;
_notifications = notifications;
_context = context;
_users = users;
}
public async Task Handle(EventCreatedNotification notification, CancellationToken ct)
@@ -43,13 +34,9 @@ public class EventCreatedNotificationHandler : INotificationHandler<EventCreated
var recipients = await _cameraAccess.GetUserIdsWithCameraAccessAsync(cameraEvent.CameraId, ct)
.ConfigureAwait(false);
var languages = _context is null || recipients.Count == 0
var languages = _users is null || recipients.Count == 0
? new Dictionary<Guid, string>()
: await _context.Users.AsNoTracking()
.Where(user => recipients.Contains(user.Id))
.Select(user => new { user.Id, user.Language })
.ToDictionaryAsync(user => user.Id, user => user.Language, ct)
.ConfigureAwait(false);
: new Dictionary<Guid, string>(await _users.GetLanguagesAsync(recipients, ct).ConfigureAwait(false));
var titleKey = cameraEvent.Type switch
{
@@ -3,6 +3,7 @@ using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using Heimdall.Application.Services;
namespace Heimdall.Application.Groups.Commands.AddUserToGroup;
@@ -11,8 +12,9 @@ public record AddUserToGroupCommand(Guid GroupId, Guid UserId, Guid? ActorId = n
public class AddUserToGroupCommandHandler : IRequestHandler<AddUserToGroupCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
private readonly IIdentityAccountService _identity;
public AddUserToGroupCommandHandler(IApplicationDbContext db) => _db = db;
public AddUserToGroupCommandHandler(IApplicationDbContext db, IIdentityAccountService identity) => (_db, _identity) = (db, identity);
public async Task<ServiceResult> Handle(AddUserToGroupCommand request, CancellationToken ct)
{
@@ -20,7 +22,7 @@ public class AddUserToGroupCommandHandler : IRequestHandler<AddUserToGroupComman
if (group is null)
return ServiceResult.NotFound("Group not found");
var user = await _db.Users.FindAsync([request.UserId], ct).ConfigureAwait(false);
var user = await _identity.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
@@ -11,8 +11,5 @@ public class GroupMappingProfile : Profile
CreateMap<Group, GroupResponse>()
.ForMember(d => d.UserCount, o => o.MapFrom(s => s.UserGroups.Count));
CreateMap<UserGroup, GroupMemberResponse>()
.ForMember(d => d.Email, o => o.MapFrom(s => s.User.Email ?? string.Empty))
.ForMember(d => d.DisplayName, o => o.MapFrom(s => s.User.DisplayName));
}
}
@@ -1,5 +1,6 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Common.Persistence;
using MediatR;
using Microsoft.EntityFrameworkCore;
@@ -11,8 +12,9 @@ public class GetGroupMembersQueryHandler
: IRequestHandler<GetGroupMembersQuery, ServiceResult<IReadOnlyList<GroupMemberResponse>>>
{
private readonly IApplicationDbContext _db;
private readonly IUserRepository _users;
public GetGroupMembersQueryHandler(IApplicationDbContext db) => _db = db;
public GetGroupMembersQueryHandler(IApplicationDbContext db, IUserRepository users) => (_db, _users) = (db, users);
public async Task<ServiceResult<IReadOnlyList<GroupMemberResponse>>> Handle(
GetGroupMembersQuery request, CancellationToken ct)
@@ -21,14 +23,7 @@ public class GetGroupMembersQueryHandler
if (!groupExists)
return ServiceResult<IReadOnlyList<GroupMemberResponse>>.NotFound("Group not found");
var members = await _db.UserGroups.AsNoTracking()
.Where(ug => ug.GroupId == request.GroupId)
.Join(_db.Users.AsNoTracking(),
ug => ug.UserId,
u => u.Id,
(ug, u) => new GroupMemberResponse(u.Id, u.Email ?? string.Empty, u.DisplayName))
.OrderBy(m => m.DisplayName)
.ToListAsync(ct);
var members = await _users.GetGroupMembersAsync(request.GroupId, ct).ConfigureAwait(false);
return ServiceResult<IReadOnlyList<GroupMemberResponse>>.Success(members);
}
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Heimdall.Domain\Heimdall.Domain.csproj" />
@@ -9,7 +9,6 @@
<PackageReference Include="FluentValidation" Version="11.11.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" />
<PackageReference Include="MediatR" Version="12.5.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.13" />
<!-- Use the same patched native SQLite bundle for server, agent and tests. -->
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" />
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Application.Services;
namespace Heimdall.Application.Services;
@@ -14,6 +15,6 @@ public record SignInServiceResult(SignInResultType ResultType);
public interface IAuthSignInService
{
Task<SignInServiceResult> PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure);
Task<SignInServiceResult> PasswordSignInAsync(IdentityAccount user, string password, bool lockoutOnFailure);
Task SignOutAsync();
}
@@ -0,0 +1,62 @@
using Heimdall.Application.Common;
namespace Heimdall.Application.Services;
/// <summary>Application-facing account data. ASP.NET Core Identity types stay in Infrastructure.</summary>
public sealed class IdentityAccount
{
public Guid Id { get; set; }
public string? UserName { get; set; }
public string? Email { get; set; }
public string DisplayName { get; set; } = string.Empty;
public string? Theme { get; set; } = "Auto";
public string Language { get; set; } = "fr";
public DateTime CreatedAt { get; init; }
public bool MustChangePassword { get; set; }
public bool EmailConfirmed { get; set; }
public bool LockoutEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public int AccessFailedCount { get; set; }
public bool TwoFactorEnabled { get; set; }
public string? SecurityStamp { get; set; }
}
public sealed record IdentityOperationResult(bool Succeeded, IReadOnlyList<string> ErrorCodes)
{
public static IdentityOperationResult Success { get; } = new(true, []);
}
public sealed record UserSessionRecord(string? SecurityStamp, bool LockoutEnabled, DateTimeOffset? LockoutEnd, bool EmailConfirmed);
public interface IIdentityAccountService
{
Task<IdentityAccount?> FindByIdAsync(Guid userId, CancellationToken ct = default);
Task<IdentityAccount?> FindByEmailAsync(string email, CancellationToken ct = default);
Task<IdentityOperationResult> CreateAsync(IdentityAccount account, string password, CancellationToken ct = default);
Task<IdentityOperationResult> DeleteAsync(IdentityAccount account, CancellationToken ct = default);
Task<IdentityOperationResult> UpdateAsync(IdentityAccount account, CancellationToken ct = default);
Task<IList<string>> GetRolesAsync(IdentityAccount account, CancellationToken ct = default);
Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken ct = default);
Task<IdentityOperationResult> AddToRoleAsync(IdentityAccount account, string role, CancellationToken ct = default);
Task<IdentityOperationResult> AddToRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default);
Task<IdentityOperationResult> RemoveFromRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default);
Task<bool> CheckPasswordAsync(IdentityAccount account, string password, CancellationToken ct = default);
Task<IdentityOperationResult> ChangePasswordAsync(IdentityAccount account, string currentPassword, string newPassword, CancellationToken ct = default);
Task<string> GeneratePasswordResetTokenAsync(IdentityAccount account, CancellationToken ct = default);
Task<IdentityOperationResult> ResetPasswordAsync(IdentityAccount account, string token, string password, CancellationToken ct = default);
Task<string> GenerateEmailConfirmationTokenAsync(IdentityAccount account, CancellationToken ct = default);
Task<IdentityOperationResult> ConfirmEmailAsync(IdentityAccount account, string token, CancellationToken ct = default);
Task<bool> IsEmailConfirmedAsync(IdentityAccount account, CancellationToken ct = default);
Task<bool> IsLockedOutAsync(IdentityAccount account, CancellationToken ct = default);
Task<IdentityOperationResult> SetLockoutEndDateAsync(IdentityAccount account, DateTimeOffset? lockoutEnd, CancellationToken ct = default);
Task<IdentityOperationResult> ResetAccessFailedCountAsync(IdentityAccount account, CancellationToken ct = default);
Task<IdentityOperationResult> AccessFailedAsync(IdentityAccount account, CancellationToken ct = default);
Task<bool> GetTwoFactorEnabledAsync(IdentityAccount account, CancellationToken ct = default);
Task<IdentityOperationResult> SetTwoFactorEnabledAsync(IdentityAccount account, bool enabled, CancellationToken ct = default);
Task<IdentityOperationResult> ResetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default);
Task<string?> GetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default);
Task<bool> UpdateSecurityStampAsync(IdentityAccount account, CancellationToken ct = default);
Task<bool> VerifyAuthenticatorTokenAsync(IdentityAccount account, string token, CancellationToken ct = default);
Task<UserSessionRecord?> GetSessionRecordAsync(Guid userId, CancellationToken ct = default);
}
@@ -1,14 +1,15 @@
using System.Security.Claims;
using Heimdall.Domain.Entities;
using Heimdall.Application.Services;
namespace Heimdall.Application.Services;
public interface IJwtService
{
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions, DateTime sessionStarted) => GenerateAccessToken(user, roles, permissions);
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user);
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted) => GenerateRefreshToken(user);
(string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions);
(string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions, DateTime sessionStarted) => GenerateAccessToken(user, roles, permissions);
(string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user);
(string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user, DateTime sessionStarted) => GenerateRefreshToken(user);
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
string? GetUserIdFromExpiredToken(string token);
}
@@ -1,5 +1,6 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
@@ -11,8 +12,9 @@ public record GetStatsQuery : IRequest<ServiceResult<StatsResponse>>;
public class GetStatsQueryHandler : IRequestHandler<GetStatsQuery, ServiceResult<StatsResponse>>
{
private readonly IApplicationDbContext _db;
private readonly IUserRepository _users;
public GetStatsQueryHandler(IApplicationDbContext db) => _db = db;
public GetStatsQueryHandler(IApplicationDbContext db, IUserRepository users) => (_db, _users) = (db, users);
public async Task<ServiceResult<StatsResponse>> Handle(GetStatsQuery request, CancellationToken ct)
{
@@ -23,7 +25,7 @@ public class GetStatsQueryHandler : IRequestHandler<GetStatsQuery, ServiceResult
var onlineAgents = await _db.Agents.CountAsync(a => a.Status == AgentStatus.Online, ct).ConfigureAwait(false);
var activeSites = await _db.Sites.CountAsync(s => s.Enabled, ct).ConfigureAwait(false);
var camerasOnline = await _db.Cameras.CountAsync(c => c.Status == CameraStatus.Online, ct).ConfigureAwait(false);
var totalUsers = await _db.Users.CountAsync(ct).ConfigureAwait(false);
var totalUsers = await _users.CountUsersAsync(ct).ConfigureAwait(false);
return ServiceResult<StatsResponse>.Success(new StatsResponse(
totalSites,
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.AssignRoles;
public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public AssignRolesHandler(UserManager<AppUser> userManager, IUserRepository repository)
public AssignRolesHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -19,11 +19,11 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
public async Task<ServiceResult> Handle(AssignRolesCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
var currentRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
var currentRoles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
var wasAdmin = currentRoles.Contains("Admin");
var willBeAdmin = command.Roles.Contains("Admin");
@@ -39,26 +39,26 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
var rolesToRemove = currentRoles.Except(command.Roles, StringComparer.OrdinalIgnoreCase).ToArray();
if (rolesToAdd.Length > 0)
{
var added = await _userManager.AddToRolesAsync(user, rolesToAdd).ConfigureAwait(false);
var added = await _userManager.AddToRolesAsync(user, rolesToAdd, ct).ConfigureAwait(false);
if (!added.Succeeded) return ServiceResult.Failure("Unable to update user roles");
}
if (rolesToRemove.Length > 0)
{
var removed = await _userManager.RemoveFromRolesAsync(user, rolesToRemove).ConfigureAwait(false);
var removed = await _userManager.RemoveFromRolesAsync(user, rolesToRemove, ct).ConfigureAwait(false);
if (!removed.Succeeded)
{
if (rolesToAdd.Length > 0)
await _userManager.RemoveFromRolesAsync(user, rolesToAdd).ConfigureAwait(false);
await _userManager.RemoveFromRolesAsync(user, rolesToAdd, ct).ConfigureAwait(false);
return ServiceResult.Failure("Unable to update user roles");
}
}
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp)
{
if (rolesToRemove.Length > 0)
await _userManager.AddToRolesAsync(user, rolesToRemove).ConfigureAwait(false);
await _userManager.AddToRolesAsync(user, rolesToRemove, ct).ConfigureAwait(false);
if (rolesToAdd.Length > 0)
await _userManager.RemoveFromRolesAsync(user, rolesToAdd).ConfigureAwait(false);
await _userManager.RemoveFromRolesAsync(user, rolesToAdd, ct).ConfigureAwait(false);
return ServiceResult.Failure("Unable to revoke existing sessions");
}
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.AssignSites;
public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public AssignSitesHandler(UserManager<AppUser> userManager, IUserRepository repository)
public AssignSitesHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -19,7 +19,7 @@ public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceRes
public async Task<ServiceResult> Handle(AssignSitesCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.ConfirmEmail;
public class ConfirmEmailCommandHandler : IRequestHandler<ConfirmEmailCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public ConfirmEmailCommandHandler(UserManager<AppUser> userManager, IUserRepository repository)
public ConfirmEmailCommandHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -19,15 +19,15 @@ public class ConfirmEmailCommandHandler : IRequestHandler<ConfirmEmailCommand, S
public async Task<ServiceResult> Handle(ConfirmEmailCommand request, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.Failure("Utilisateur introuvable", 404);
if (user.EmailConfirmed)
return ServiceResult.Failure("L'email est déjà confirmé", 400);
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var result = await _userManager.ConfirmEmailAsync(user, token).ConfigureAwait(false);
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user, ct);
var result = await _userManager.ConfirmEmailAsync(user, token, ct).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult.Failure("Erreur lors de la confirmation de l'email", 400);
@@ -3,16 +3,16 @@ using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.CreateUser;
public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResult<UserResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public CreateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
public CreateUserHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -20,27 +20,27 @@ public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResul
public async Task<ServiceResult<UserResponse>> Handle(CreateUserCommand command, CancellationToken ct)
{
var existing = await _userManager.FindByEmailAsync(command.Email).ConfigureAwait(false);
var existing = await _userManager.FindByEmailAsync(command.Email, ct).ConfigureAwait(false);
if (existing is not null)
return ServiceResult<UserResponse>.Conflict("Email already registered");
var user = new AppUser
var user = new IdentityAccount
{
UserName = command.Email,
Email = command.Email,
DisplayName = command.DisplayName
};
var result = await _userManager.CreateAsync(user, command.Password).ConfigureAwait(false);
var result = await _userManager.CreateAsync(user, command.Password, ct).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult<UserResponse>.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
string.Join(", ", result.ErrorCodes));
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
var assignment = await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
var assignment = await _userManager.AddToRolesAsync(user, roles, ct).ConfigureAwait(false);
if (!assignment.Succeeded)
{
await _userManager.DeleteAsync(user).ConfigureAwait(false);
await _userManager.DeleteAsync(user, ct).ConfigureAwait(false);
return ServiceResult<UserResponse>.Failure("Unable to assign requested account roles");
}
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.DeleteUser;
public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public DeleteUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
public DeleteUserHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -22,11 +22,11 @@ public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResul
if (command.UserId == command.CurrentUserId)
return ServiceResult.Failure("You cannot delete your own account.", 400);
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
var roles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
if (roles.Contains("Admin"))
{
var adminCount = await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false);
@@ -37,10 +37,10 @@ public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResul
await _repository.RemoveUserDataAsync(command.UserId, ct).ConfigureAwait(false);
var result = await _userManager.DeleteAsync(user).ConfigureAwait(false);
var result = await _userManager.DeleteAsync(user, ct).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
string.Join(", ", result.ErrorCodes));
await _repository.AddAuditLogAsync(command.CurrentUserId, "UserDeleted", "User",
command.UserId.ToString(), null, null, ct);
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.LockUser;
public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public LockUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
public LockUserHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -19,19 +19,19 @@ public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
public async Task<ServiceResult> Handle(LockUserCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
var roles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
if (roles.Contains("Admin", StringComparer.OrdinalIgnoreCase)
&& await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false) <= 1)
return ServiceResult.Failure("Cannot lock the last administrator account.", 400);
var lockout = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
var lockout = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue, ct).ConfigureAwait(false);
if (!lockout.Succeeded) return ServiceResult.Failure("Unable to lock account");
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp) return ServiceResult.Failure("Unable to revoke existing sessions");
await _repository.AddAuditLogAsync(command.ActorId, "UserLocked", "User",
command.UserId.ToString(), null, null, ct);
@@ -4,16 +4,16 @@ using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.ResetPassword;
public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ServiceResult<ResetPasswordResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public ResetPasswordHandler(UserManager<AppUser> userManager, IUserRepository repository)
public ResetPasswordHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -21,22 +21,22 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
public async Task<ServiceResult<ResetPasswordResponse>> Handle(ResetPasswordCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult<ResetPasswordResponse>.NotFound("User not found");
var temporaryPassword = GenerateTemporaryPassword();
var token = await _userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword).ConfigureAwait(false);
var token = await _userManager.GeneratePasswordResetTokenAsync(user, ct).ConfigureAwait(false);
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword, ct).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
user.MustChangePassword = true;
var updated = await _userManager.UpdateAsync(user).ConfigureAwait(false);
var updated = await _userManager.UpdateAsync(user, ct).ConfigureAwait(false);
if (!updated.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
await _repository.AddAuditLogAsync(command.ActorId, "UserPasswordReset", "User",
command.UserId.ToString(), null, null, ct);
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.UnlockUser;
public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResult>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public UnlockUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
public UnlockUserHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -19,16 +19,16 @@ public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResul
public async Task<ServiceResult> Handle(UnlockUserCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult.NotFound("User not found");
var unlock = await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);
var unlock = await _userManager.SetLockoutEndDateAsync(user, null, ct).ConfigureAwait(false);
if (!unlock.Succeeded) return ServiceResult.Failure("Unable to unlock account");
var reset = await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
var reset = await _userManager.ResetAccessFailedCountAsync(user, ct).ConfigureAwait(false);
if (!reset.Succeeded) return ServiceResult.Failure("Unable to reset failed sign-in count");
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp) return ServiceResult.Failure("Unable to revoke existing sessions");
await _repository.AddAuditLogAsync(command.ActorId, "UserUnlocked", "User",
command.UserId.ToString(), null, null, ct);
@@ -3,17 +3,17 @@ using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Commands.UpdateUser;
public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResult<UserResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
public UpdateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
public UpdateUserHandler(IIdentityAccountService userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
@@ -21,7 +21,7 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
public async Task<ServiceResult<UserResponse>> Handle(UpdateUserCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.Id.ToString()).ConfigureAwait(false);
var user = await _userManager.FindByIdAsync(command.Id, ct).ConfigureAwait(false);
if (user is null)
return ServiceResult<UserResponse>.NotFound("User not found");
@@ -40,7 +40,7 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
if (!string.Equals(oldEmail, newEmail, StringComparison.OrdinalIgnoreCase))
{
var existingUser = await _userManager.FindByEmailAsync(newEmail).ConfigureAwait(false);
var existingUser = await _userManager.FindByEmailAsync(newEmail, ct).ConfigureAwait(false);
if (existingUser is not null && existingUser.Id != user.Id)
return ServiceResult<UserResponse>.Failure("Cette adresse email est déjà utilisée", 409);
@@ -55,15 +55,15 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
user.Theme = command.Theme ?? user.Theme;
user.Language = language ?? user.Language;
var result = await _userManager.UpdateAsync(user).ConfigureAwait(false);
var result = await _userManager.UpdateAsync(user, ct).ConfigureAwait(false);
if (!result.Succeeded)
return ServiceResult<UserResponse>.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
string.Join(", ", result.ErrorCodes));
if (emailChanged)
{
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
if (!stamp.Succeeded)
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
if (!stamp)
return ServiceResult<UserResponse>.Failure("Email updated but existing sessions could not be revoked", 500);
}
@@ -3,6 +3,7 @@ using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Commands.CreateUser;
using Heimdall.Application.Users.Commands.UpdateUser;
using Heimdall.Domain.Entities;
using Heimdall.Application.Services;
namespace Heimdall.Application.Users.Mapping;
@@ -10,7 +11,7 @@ public class UserMappingProfile : Profile
{
public UserMappingProfile()
{
CreateMap<AppUser, UserResponse>()
CreateMap<IdentityAccount, UserResponse>()
.ForMember(d => d.Email, o => o.MapFrom(s => s.Email ?? string.Empty))
.ForMember(d => d.Roles, o => o.Ignore())
.ForMember(d => d.SiteIds, o => o.Ignore())
+1 -95
View File
@@ -39,16 +39,6 @@
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0"
}
},
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Identity.Stores": "10.0.13"
}
},
"Microsoft.Data.Sqlite": {
"type": "Direct",
"requested": "[10.0.13, )",
@@ -102,19 +92,6 @@
"resolved": "2.0.1",
"contentHash": "FYv95bNT4UwcNA+G/J1oX5OpRiSUxteXaUt2BJbRSdRNiIUNbggJF69wy6mnk2wYToaanpdXZdCwVylt96MpwQ=="
},
"Microsoft.AspNetCore.Cryptography.Internal": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
},
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
}
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -178,15 +155,6 @@
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -195,15 +163,6 @@
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Binder": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -222,46 +181,6 @@
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Stores": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.Identity.Core": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Logging": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -289,18 +208,6 @@
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options.ConfigurationExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -365,8 +272,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
-10
View File
@@ -1,10 +0,0 @@
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Domain.Entities;
public class AppRole : IdentityRole<Guid>
{
public AppRole() { }
public AppRole(string name) : base(name) { }
}
-20
View File
@@ -1,20 +0,0 @@
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Domain.Entities;
public class AppUser : IdentityUser<Guid>
{
public string DisplayName { get; set; } = string.Empty;
public string? Theme { get; set; } = "Auto";
public string Language { get; set; } = "fr";
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public bool MustChangePassword { get; set; }
// Navigation
private readonly List<UserSite> _userSites = [];
public IReadOnlyCollection<UserSite> UserSites => _userSites.AsReadOnly();
private readonly List<UserGroup> _userGroups = [];
public IReadOnlyCollection<UserGroup> UserGroups => _userGroups.AsReadOnly();
}
-3
View File
@@ -16,9 +16,6 @@ public class AuditLog
public string? IpAddress { get; private set; }
public DateTime Timestamp { get; private set; } = DateTime.UtcNow;
// Navigation
public AppUser? User { get; private set; }
private AuditLog() { } // EF Core
public AuditLog(
@@ -10,7 +10,6 @@ public class UserCamera
public Guid UserId { get; private set; }
public Guid CameraId { get; private set; }
public AppUser User { get; private set; } = null!;
public Camera Camera { get; private set; } = null!;
private UserCamera() { } // EF Core
@@ -19,7 +19,6 @@ public class UserCameraAccess : Entity<Guid>, IAuditableEntity
public DateTime UpdatedAt { get; set; }
// Navigation
public AppUser User { get; private set; } = null!;
public Site Site { get; private set; } = null!;
public Camera? Camera { get; private set; }
@@ -8,8 +8,6 @@ public class UserGroup
public Guid UserId { get; private set; }
public Guid GroupId { get; private set; }
// Navigation
public AppUser User { get; private set; } = null!;
public Group Group { get; private set; } = null!;
private UserGroup() { } // EF Core
-1
View File
@@ -9,7 +9,6 @@ public class UserSite
public Guid UserId { get; private set; }
public Guid SiteId { get; private set; }
public AppUser User { get; private set; } = null!;
public Site Site { get; private set; } = null!;
private UserSite() { } // EF Core
+1 -5
View File
@@ -1,13 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Heimdall.Domain.Primitives\Heimdall.Domain.Primitives.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.13" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
-198
View File
@@ -2,204 +2,6 @@
"version": 1,
"dependencies": {
"net10.0": {
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Identity.Stores": "10.0.13"
}
},
"Microsoft.AspNetCore.Cryptography.Internal": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
},
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Abstractions": "10.0.13",
"Microsoft.EntityFrameworkCore.Analyzers": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A=="
},
"Microsoft.EntityFrameworkCore.Analyzers": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA=="
},
"Microsoft.EntityFrameworkCore.Relational": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==",
"dependencies": {
"Microsoft.EntityFrameworkCore": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "UOJqcdNMoFcV/5RUcOlVKq9pPmbrcmbpLx5iYz9QtrmMcWRQzlL5Q/NZRfbPPLNyIEc1HWjjs5Z7nIwqewU1sg==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Caching.Memory": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "q+At65RACuCtGwUDVI08TmmrC73YFouimMkJAtlhsGhFcU/dVpqYEKpNBOF9TUxkJ6aefEOShqe7StLK7q3NqA==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==",
"dependencies": {
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Configuration.Binder": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
"dependencies": {
"Microsoft.Extensions.Configuration": "10.0.13",
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
}
},
"Microsoft.Extensions.Diagnostics.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
"dependencies": {
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
"Microsoft.Extensions.Diagnostics": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Identity.Stores": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
"dependencies": {
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
"Microsoft.Extensions.Identity.Core": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.Extensions.Logging": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection": "10.0.13",
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13"
}
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
}
},
"Microsoft.Extensions.Options": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Options.ConfigurationExtensions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
"dependencies": {
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
"Microsoft.Extensions.Options": "10.0.13",
"Microsoft.Extensions.Primitives": "10.0.13"
}
},
"Microsoft.Extensions.Primitives": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA=="
},
"heimdall.domain.primitives": {
"type": "Project"
}
@@ -7,9 +7,10 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Data;
public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicationDbContext
public class AppDbContext : IdentityDbContext<IdentityAppUser, IdentityAppRole, Guid>, IApplicationDbContext, IIdentityPersistenceContext
{
private readonly AuditInterceptor _auditInterceptor;
private readonly IServiceProvider? _serviceProvider;
@@ -69,14 +70,6 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
// 2FA recovery codes (stored hashed)
public DbSet<UserRecoveryCode> UserRecoveryCodes => Set<UserRecoveryCode>();
// Identity tables (for synchronous admin checks in IQueryable filters)
public new DbSet<AppRole> Roles => Set<AppRole>();
// Suppress CS0114 — base IdentityDbContext.UserRoles is virtual but we need
// the specific DbSet<IdentityUserRole<Guid>> type exposed through IApplicationDbContext.
public new DbSet<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>> UserRoles
=> Set<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>>();
// Domain métier (spec 2.1)
public DbSet<Vehicle> Vehicles => Set<Vehicle>();
public DbSet<Recording> Recordings => Set<Recording>();
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -34,7 +35,7 @@ public class AuditLogConfiguration : IEntityTypeConfiguration<AuditLog>
.HasDefaultValueSql("NOW()");
// Relationships
builder.HasOne(al => al.User)
builder.HasOne<IdentityAppUser>()
.WithMany()
.HasForeignKey(al => al.UserId)
.OnDelete(DeleteBehavior.SetNull);
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -52,8 +53,8 @@ public class UserGroupConfiguration : IEntityTypeConfiguration<UserGroup>
builder.HasKey(ug => new { ug.UserId, ug.GroupId });
builder.HasOne(ug => ug.User)
.WithMany(u => u.UserGroups)
builder.HasOne<IdentityAppUser>()
.WithMany()
.HasForeignKey(ug => ug.UserId)
.OnDelete(DeleteBehavior.Cascade);
@@ -3,11 +3,12 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Data.Configurations;
public class AppUserConfiguration : IEntityTypeConfiguration<AppUser>
public class IdentityAppUserConfiguration : IEntityTypeConfiguration<IdentityAppUser>
{
public void Configure(EntityTypeBuilder<AppUser> builder)
public void Configure(EntityTypeBuilder<IdentityAppUser> builder)
{
builder.ToTable("users");
@@ -33,9 +34,9 @@ public class AppUserConfiguration : IEntityTypeConfiguration<AppUser>
}
}
public class AppRoleConfiguration : IEntityTypeConfiguration<AppRole>
public class IdentityAppRoleConfiguration : IEntityTypeConfiguration<IdentityAppRole>
{
public void Configure(EntityTypeBuilder<AppRole> builder)
public void Configure(EntityTypeBuilder<IdentityAppRole> builder)
{
builder.ToTable("roles");
}
@@ -2,6 +2,7 @@ using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Data.Configurations;
public class LoginChallengeConfiguration : IEntityTypeConfiguration<LoginChallenge>
@@ -13,6 +14,6 @@ public class LoginChallengeConfiguration : IEntityTypeConfiguration<LoginChallen
builder.Property(x => x.Id).HasMaxLength(64);
builder.Property(x => x.SecurityStamp).HasMaxLength(256);
builder.HasIndex(x => x.ExpiresAt);
builder.HasOne<AppUser>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<IdentityAppUser>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
}
}
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -12,7 +13,7 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration<UserCamera
builder.HasKey(eca => new { eca.UserId, eca.SiteId, eca.CameraId });
builder.HasOne(eca => eca.User)
builder.HasOne<IdentityAppUser>()
.WithMany()
.HasForeignKey(eca => eca.UserId)
.OnDelete(DeleteBehavior.Cascade);
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -12,7 +13,7 @@ public class UserCameraConfiguration : IEntityTypeConfiguration<UserCamera>
builder.HasKey(uc => new { uc.UserId, uc.CameraId });
builder.HasOne(uc => uc.User)
builder.HasOne<IdentityAppUser>()
.WithMany()
.HasForeignKey(uc => uc.UserId)
.OnDelete(DeleteBehavior.Cascade);
@@ -1,4 +1,5 @@
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
@@ -12,8 +13,8 @@ public class UserSiteConfiguration : IEntityTypeConfiguration<UserSite>
builder.HasKey(us => new { us.UserId, us.SiteId });
builder.HasOne(us => us.User)
.WithMany(u => u.UserSites)
builder.HasOne<IdentityAppUser>()
.WithMany()
.HasForeignKey(us => us.UserId)
.OnDelete(DeleteBehavior.Cascade);
@@ -19,6 +19,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure;
public static class DependencyInjection
@@ -43,6 +44,7 @@ public static class DependencyInjection
ServiceLifetime.Scoped); // must be Scoped: AddDbContext registers DbContextOptions as Scoped, and a Singleton factory would fail DI validation (singleton → scoped)
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
services.AddScoped<IIdentityPersistenceContext>(sp => sp.GetRequiredService<AppDbContext>());
// Stockage (spec Phase 8) — provider résolu depuis les settings DB
// (storage.provider = Local | S3), factory scoped (lit la config à
@@ -60,7 +62,7 @@ public static class DependencyInjection
.AddCheck<Infrastructure.HealthChecks.AiHealthCheck>("codeproject-ai", tags: ["live"]);
// Identity
services.AddIdentity<AppUser, AppRole>(options =>
services.AddIdentity<IdentityAppUser, IdentityAppRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = false; // Heimdall enforces the configurable policy at its auth boundary.
@@ -149,6 +151,7 @@ public static class DependencyInjection
// Data access
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IIdentityAccountService, IdentityAccountService>();
// Camera discovery services (used by CQRS handlers)
services.AddHttpClient("Discovery", client =>
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Infrastructure.Identity;
/// <summary>Infrastructure-only query surface for Identity entities used in composed authorization queries.</summary>
public interface IIdentityPersistenceContext
{
DbSet<IdentityAppUser> Users { get; }
DbSet<IdentityAppRole> Roles { get; }
DbSet<IdentityUserRole<Guid>> UserRoles { get; }
}
@@ -0,0 +1,162 @@
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Infrastructure.Identity;
/// <summary>Adapts ASP.NET Core Identity to the application account port.</summary>
public sealed class IdentityAccountService(UserManager<IdentityAppUser> users, AppDbContext db) : IIdentityAccountService
{
public async Task<IdentityAccount?> FindByIdAsync(Guid userId, CancellationToken ct = default)
=> Map(await users.FindByIdAsync(userId.ToString()).ConfigureAwait(false));
public async Task<IdentityAccount?> FindByEmailAsync(string email, CancellationToken ct = default)
=> Map(await users.FindByEmailAsync(email).ConfigureAwait(false));
public async Task<IdentityOperationResult> CreateAsync(IdentityAccount account, string password, CancellationToken ct = default)
{
var user = new IdentityAppUser { Id = account.Id == Guid.Empty ? Guid.NewGuid() : account.Id };
Copy(account, user);
var result = await users.CreateAsync(user, password).ConfigureAwait(false);
account.Id = user.Id;
account.SecurityStamp = user.SecurityStamp;
return Map(result);
}
public async Task<IdentityOperationResult> DeleteAsync(IdentityAccount account, CancellationToken ct = default)
{
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
return user is null ? Failure("UserNotFound") : Map(await users.DeleteAsync(user).ConfigureAwait(false));
}
public async Task<IdentityOperationResult> UpdateAsync(IdentityAccount account, CancellationToken ct = default)
{
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
if (user is null) return Failure("UserNotFound");
Copy(account, user);
return Map(await users.UpdateAsync(user).ConfigureAwait(false));
}
public async Task<IList<string>> GetRolesAsync(IdentityAccount account, CancellationToken ct = default)
{
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
return user is null ? [] : await users.GetRolesAsync(user).ConfigureAwait(false);
}
public async Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken ct = default)
{
var user = await FindEntityAsync(userId).ConfigureAwait(false);
return user is not null && await users.IsInRoleAsync(user, role).ConfigureAwait(false);
}
public async Task<IdentityOperationResult> AddToRoleAsync(IdentityAccount account, string role, CancellationToken ct = default)
=> await WithUser(account, u => users.AddToRoleAsync(u, role)).ConfigureAwait(false);
public async Task<IdentityOperationResult> AddToRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default)
=> await WithUser(account, u => users.AddToRolesAsync(u, roles)).ConfigureAwait(false);
public async Task<IdentityOperationResult> RemoveFromRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default)
=> await WithUser(account, u => users.RemoveFromRolesAsync(u, roles)).ConfigureAwait(false);
public async Task<bool> CheckPasswordAsync(IdentityAccount account, string password, CancellationToken ct = default)
=> await WithUserValue(account, u => users.CheckPasswordAsync(u, password)).ConfigureAwait(false);
public async Task<IdentityOperationResult> ChangePasswordAsync(IdentityAccount account, string currentPassword, string newPassword, CancellationToken ct = default)
=> await WithUser(account, u => users.ChangePasswordAsync(u, currentPassword, newPassword)).ConfigureAwait(false);
public async Task<string> GeneratePasswordResetTokenAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUserValue(account, users.GeneratePasswordResetTokenAsync).ConfigureAwait(false) ?? string.Empty;
public async Task<IdentityOperationResult> ResetPasswordAsync(IdentityAccount account, string token, string password, CancellationToken ct = default)
=> await WithUser(account, u => users.ResetPasswordAsync(u, token, password)).ConfigureAwait(false);
public async Task<string> GenerateEmailConfirmationTokenAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUserValue(account, users.GenerateEmailConfirmationTokenAsync).ConfigureAwait(false) ?? string.Empty;
public async Task<IdentityOperationResult> ConfirmEmailAsync(IdentityAccount account, string token, CancellationToken ct = default)
=> await WithUser(account, u => users.ConfirmEmailAsync(u, token)).ConfigureAwait(false);
public async Task<bool> IsEmailConfirmedAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUserValue(account, users.IsEmailConfirmedAsync).ConfigureAwait(false);
public async Task<bool> IsLockedOutAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUserValue(account, users.IsLockedOutAsync).ConfigureAwait(false);
public async Task<IdentityOperationResult> SetLockoutEndDateAsync(IdentityAccount account, DateTimeOffset? lockoutEnd, CancellationToken ct = default)
=> await WithUser(account, u => users.SetLockoutEndDateAsync(u, lockoutEnd)).ConfigureAwait(false);
public async Task<IdentityOperationResult> ResetAccessFailedCountAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUser(account, users.ResetAccessFailedCountAsync).ConfigureAwait(false);
public async Task<IdentityOperationResult> AccessFailedAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUser(account, users.AccessFailedAsync).ConfigureAwait(false);
public async Task<bool> GetTwoFactorEnabledAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUserValue(account, users.GetTwoFactorEnabledAsync).ConfigureAwait(false);
public async Task<IdentityOperationResult> SetTwoFactorEnabledAsync(IdentityAccount account, bool enabled, CancellationToken ct = default)
=> await WithUser(account, u => users.SetTwoFactorEnabledAsync(u, enabled)).ConfigureAwait(false);
public async Task<IdentityOperationResult> ResetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUser(account, users.ResetAuthenticatorKeyAsync).ConfigureAwait(false);
public async Task<string?> GetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default)
=> await WithUserValue(account, users.GetAuthenticatorKeyAsync).ConfigureAwait(false);
public async Task<bool> VerifyAuthenticatorTokenAsync(IdentityAccount account, string token, CancellationToken ct = default)
=> await WithUserValue(account, u => users.VerifyTwoFactorTokenAsync(u, "Authenticator", token)).ConfigureAwait(false);
public async Task<bool> UpdateSecurityStampAsync(IdentityAccount account, CancellationToken ct = default)
=> (await WithUser(account, users.UpdateSecurityStampAsync).ConfigureAwait(false)).Succeeded;
public async Task<UserSessionRecord?> GetSessionRecordAsync(Guid userId, CancellationToken ct = default)
{
var row = await db.Users.AsNoTracking().Where(user => user.Id == userId)
.Select(user => new { user.SecurityStamp, user.LockoutEnabled, user.LockoutEnd, user.EmailConfirmed })
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
return row is null ? null : new UserSessionRecord(row.SecurityStamp, row.LockoutEnabled, row.LockoutEnd, row.EmailConfirmed);
}
private async Task<IdentityAppUser?> FindEntityAsync(Guid id) => await users.FindByIdAsync(id.ToString()).ConfigureAwait(false);
private async Task<IdentityOperationResult> WithUser(IdentityAccount account, Func<IdentityAppUser, Task<IdentityResult>> action)
{
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
return user is null ? Failure("UserNotFound") : Map(await action(user).ConfigureAwait(false));
}
private async Task<T> WithUserValue<T>(IdentityAccount account, Func<IdentityAppUser, Task<T>> action)
{
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
return user is null ? default! : await action(user).ConfigureAwait(false);
}
private static IdentityAccount? Map(IdentityAppUser? user) => user is null ? null : new IdentityAccount
{
Id = user.Id, UserName = user.UserName, Email = user.Email, DisplayName = user.DisplayName,
Theme = user.Theme, Language = user.Language, CreatedAt = user.CreatedAt,
MustChangePassword = user.MustChangePassword, EmailConfirmed = user.EmailConfirmed,
LockoutEnabled = user.LockoutEnabled, LockoutEnd = user.LockoutEnd,
AccessFailedCount = user.AccessFailedCount, TwoFactorEnabled = user.TwoFactorEnabled,
SecurityStamp = user.SecurityStamp
};
private static void Copy(IdentityAccount source, IdentityAppUser target)
{
target.UserName = source.UserName ?? source.Email;
target.Email = source.Email;
target.DisplayName = source.DisplayName;
target.Theme = source.Theme;
target.Language = source.Language;
target.MustChangePassword = source.MustChangePassword;
target.EmailConfirmed = source.EmailConfirmed;
target.LockoutEnabled = source.LockoutEnabled;
target.LockoutEnd = source.LockoutEnd;
target.AccessFailedCount = source.AccessFailedCount;
target.TwoFactorEnabled = source.TwoFactorEnabled;
}
private static IdentityOperationResult Map(IdentityResult result) => new(result.Succeeded, result.Errors.Select(e => e.Code).ToArray());
private static IdentityOperationResult Failure(string code) => new(false, [code]);
}
@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Identity;
namespace Heimdall.Infrastructure.Identity;
/// <summary>ASP.NET Core Identity persistence model. Kept out of Domain and Application.</summary>
public sealed class IdentityAppUser : IdentityUser<Guid>
{
public string DisplayName { get; set; } = string.Empty;
public string? Theme { get; set; } = "Auto";
public string Language { get; set; } = "fr";
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public bool MustChangePassword { get; set; }
}
public sealed class IdentityAppRole : IdentityRole<Guid>
{
public IdentityAppRole() { }
public IdentityAppRole(string name) : base(name) { }
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class MoveIdentityPersistenceToInfrastructure : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
@@ -1,4 +1,4 @@
// <auto-generated />
// <auto-generated />
using System;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
@@ -17,7 +17,7 @@ namespace Heimdall.Infrastructure.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("ProductVersion", "10.0.13")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -117,6 +117,9 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(255)");
b.Property<DateTime?>("InventoryObservedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
@@ -187,9 +190,6 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("TemperatureJson")
.HasColumnType("text");
b.Property<DateTime?>("InventoryObservedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ThreadsPerCore")
.HasColumnType("integer");
@@ -290,13 +290,16 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<double?>("GpuUtilizationPercent")
.HasColumnType("double precision");
b.Property<DateTime?>("InventoryObservedAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<int?>("LogicalCores")
.HasColumnType("integer");
b.Property<long?>("MemTotalBytes")
b.Property<long?>("MemAvailableBytes")
.HasColumnType("bigint");
b.Property<long?>("MemAvailableBytes")
b.Property<long?>("MemTotalBytes")
.HasColumnType("bigint");
b.Property<long?>("MemoryUsageBytes")
@@ -308,16 +311,13 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("TemperatureJson")
.HasColumnType("text");
b.Property<DateTime?>("InventoryObservedAtUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("CapturedAtUtc");
b.HasIndex("AgentId", "CapturedAtUtc")
.IsUnique();
b.HasIndex("CapturedAtUtc");
b.HasIndex("SiteId", "CapturedAtUtc");
b.ToTable("agent_metric_samples", (string)null);
@@ -511,33 +511,6 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("api_keys", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("roles", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
{
b.Property<Guid>("Id")
@@ -596,101 +569,6 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("app_settings", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<string>("Language")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("character varying(10)")
.HasDefaultValue("fr");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<string>("Theme")
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)")
.HasDefaultValue("Auto");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("users", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
{
b.Property<Guid>("Id")
@@ -972,9 +850,6 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
{
b.Property<string>("ExecutionProfileJson")
.HasColumnType("text");
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
@@ -999,6 +874,9 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<bool>("DetectVehicle")
.HasColumnType("boolean");
b.Property<string>("ExecutionProfileJson")
.HasColumnType("text");
b.Property<bool>("FaceRecognition")
.HasColumnType("boolean");
@@ -1065,20 +943,17 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<int?>("HomeKitCategory")
.HasColumnType("integer");
b.Property<string>("HomeKitDeviceId")
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("character varying(50)");
b.Property<int?>("HomeKitCategory")
.HasColumnType("integer");
b.Property<bool?>("HomeKitIsPaired")
.HasColumnType("boolean");
b.Property<int?>("HomeKitPort")
.HasColumnType("integer");
b.Property<string>("HomeKitModel")
.HasMaxLength(200)
.IsUnicode(false)
@@ -1089,6 +964,9 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(200)");
b.Property<int?>("HomeKitPort")
.HasColumnType("integer");
b.Property<string>("Hostname")
.HasMaxLength(255)
.IsUnicode(false)
@@ -1223,19 +1101,17 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<Guid?>("RecordingId")
.HasColumnType("uuid");
b.Property<string>("SnapshotThumbUrl")
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotObjectKey")
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotThumbObjectKey")
b.Property<string>("SnapshotStorageBucket")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("SnapshotStorageEndpoint")
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotStorageProvider")
@@ -1247,13 +1123,15 @@ namespace Heimdall.Infrastructure.Migrations
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotStorageEndpoint")
b.Property<string>("SnapshotThumbObjectKey")
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotStorageBucket")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("SnapshotThumbUrl")
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("SnapshotUrl")
.HasMaxLength(2000)
@@ -1289,8 +1167,6 @@ namespace Heimdall.Infrastructure.Migrations
b.HasIndex("ParentEventId");
b.HasIndex("PersonId", "OccurredAt");
b.HasIndex("RecordingId");
b.HasIndex("TrackId");
@@ -1302,6 +1178,8 @@ namespace Heimdall.Infrastructure.Migrations
b.HasIndex("CameraId", "Type");
b.HasIndex("PersonId", "OccurredAt");
b.ToTable("camera_events", (string)null);
});
@@ -1513,9 +1391,6 @@ namespace Heimdall.Infrastructure.Migrations
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<bool>("Verifying")
.HasColumnType("boolean");
b.Property<int>("Attempts")
.HasColumnType("integer");
@@ -1533,6 +1408,9 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<bool>("Verifying")
.HasColumnType("boolean");
b.HasKey("Id");
b.HasIndex("ExpiresAt");
@@ -1545,6 +1423,7 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AgentId")
@@ -1573,10 +1452,10 @@ namespace Heimdall.Infrastructure.Migrations
b.HasKey("Id");
b.HasIndex("CameraId", "CreatedAt");
b.HasIndex("ExpiresAt");
b.HasIndex("CameraId", "CreatedAt");
b.ToTable("manual_snapshot_requests", (string)null);
});
@@ -1708,13 +1587,13 @@ namespace Heimdall.Infrastructure.Migrations
b.HasKey("Id");
b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt")
.HasDatabaseName("ix_notification_deliveries_dispatch");
b.HasIndex("NotificationId", "Channel")
.IsUnique()
.HasDatabaseName("ux_notification_deliveries_notification_channel");
b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt")
.HasDatabaseName("ix_notification_deliveries_dispatch");
b.ToTable("notification_deliveries", (string)null);
});
@@ -1846,21 +1725,17 @@ namespace Heimdall.Infrastructure.Migrations
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<bool>("StorageLocationCaptured")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<string>("StoragePath")
.IsRequired()
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnType("character varying(2000)");
b.Property<string>("StorageRoot")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<bool>("StorageLocationCaptured")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<Guid?>("StoragePolicyId")
.HasColumnType("uuid");
@@ -1870,6 +1745,10 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<string>("StorageRoot")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTime>("Timestamp")
.HasColumnType("timestamp with time zone");
@@ -2031,42 +1910,6 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("site_credentials", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<int>("RetentionDays")
.HasColumnType("integer");
b.Property<string>("StorageProvider")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("Id");
b.ToTable("storage_policies", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b =>
{
b.Property<Guid>("Id")
@@ -2110,6 +1953,42 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("storage_destinations", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<int>("RetentionDays")
.HasColumnType("integer");
b.Property<string>("StorageProvider")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("Id");
b.ToTable("storage_policies", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b =>
{
b.Property<Guid>("UserId")
@@ -2328,6 +2207,128 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("vehicles", (string)null);
});
modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("roles", (string)null);
});
modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<string>("Language")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("character varying(10)")
.HasDefaultValue("fr");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<string>("Theme")
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)")
.HasDefaultValue("Auto");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("users", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
@@ -2431,15 +2432,6 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("user_tokens", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b =>
{
b.HasOne("Heimdall.Domain.Entities.Notification", null)
.WithMany()
.HasForeignKey("NotificationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
{
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
@@ -2512,12 +2504,10 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
@@ -2668,13 +2658,22 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b =>
{
b.HasOne("Heimdall.Domain.Entities.Notification", null)
.WithMany()
.HasForeignKey("NotificationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b =>
{
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
@@ -2712,15 +2711,13 @@ namespace Heimdall.Infrastructure.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Camera");
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
@@ -2736,7 +2733,7 @@ namespace Heimdall.Infrastructure.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -2745,8 +2742,6 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("Camera");
b.Navigation("Site");
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b =>
@@ -2757,15 +2752,13 @@ namespace Heimdall.Infrastructure.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
.WithMany("UserGroups")
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
@@ -2776,15 +2769,13 @@ namespace Heimdall.Infrastructure.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
.WithMany("UserSites")
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Site");
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b =>
@@ -2799,7 +2790,7 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
@@ -2808,7 +2799,7 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -2817,7 +2808,7 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -2826,13 +2817,13 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -2841,7 +2832,7 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
@@ -2853,13 +2844,6 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("Cameras");
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
{
b.Navigation("UserGroups");
b.Navigation("UserSites");
});
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
{
b.Navigation("Credentials");
@@ -1,5 +1,6 @@
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Infrastructure.Identity;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Security;
@@ -11,9 +12,9 @@ namespace Heimdall.Infrastructure.Persistence;
public class UserRepository : IUserRepository
{
private readonly AppDbContext _db;
private readonly UserManager<AppUser> _userManager;
private readonly UserManager<IdentityAppUser> _userManager;
public UserRepository(AppDbContext db, UserManager<AppUser> userManager)
public UserRepository(AppDbContext db, UserManager<IdentityAppUser> userManager)
{
_db = db;
_userManager = userManager;
@@ -131,7 +132,37 @@ public class UserRepository : IUserRepository
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
}
private static UserResponse MapToResponse(AppUser user, List<string> roles, List<Guid> siteIds)
public Task<bool> ExistsAsync(Guid userId, CancellationToken ct)
=> _db.Users.AsNoTracking().AnyAsync(user => user.Id == userId, ct);
public Task<int> CountUsersAsync(CancellationToken ct)
=> _db.Users.AsNoTracking().CountAsync(ct);
public async Task<IReadOnlyDictionary<Guid, string>> GetLanguagesAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct)
=> await _db.Users.AsNoTracking().Where(user => userIds.Contains(user.Id))
.ToDictionaryAsync(user => user.Id, user => user.Language, ct).ConfigureAwait(false);
public async Task<IReadOnlyDictionary<Guid, string?>> GetEmailsAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct)
=> await _db.Users.AsNoTracking().Where(user => userIds.Contains(user.Id))
.ToDictionaryAsync(user => user.Id, user => user.Email, ct).ConfigureAwait(false);
public async Task<IReadOnlyList<GroupMemberResponse>> GetGroupMembersAsync(Guid groupId, CancellationToken ct)
=> await (from membership in _db.UserGroups.AsNoTracking()
join user in _db.Users.AsNoTracking() on membership.UserId equals user.Id
where membership.GroupId == groupId
orderby user.DisplayName
select new GroupMemberResponse(user.Id, user.Email ?? string.Empty, user.DisplayName))
.ToListAsync(ct).ConfigureAwait(false);
public async Task<bool> IsAdminAsync(Guid userId, CancellationToken ct)
{
var roleId = await _db.Roles.AsNoTracking().Where(role => role.Name == AppRoles.Admin)
.Select(role => (Guid?)role.Id).SingleOrDefaultAsync(ct).ConfigureAwait(false);
return roleId.HasValue && await _db.UserRoles.AsNoTracking()
.AnyAsync(userRole => userRole.UserId == userId && userRole.RoleId == roleId.Value, ct).ConfigureAwait(false);
}
private static UserResponse MapToResponse(IdentityAppUser user, List<string> roles, List<Guid> siteIds)
{
return new UserResponse(
user.Id,
@@ -1,3 +1,4 @@
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Security;
/// <summary>
@@ -1,20 +1,22 @@
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Security;
public class AuthSignInService : IAuthSignInService
{
private readonly SignInManager<AppUser> _signInManager;
private readonly SignInManager<IdentityAppUser> _signInManager;
public AuthSignInService(SignInManager<AppUser> signInManager)
public AuthSignInService(SignInManager<IdentityAppUser> signInManager)
{
_signInManager = signInManager;
}
public async Task<SignInServiceResult> PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure)
public async Task<SignInServiceResult> PasswordSignInAsync(IdentityAccount account, string password, bool lockoutOnFailure)
{
var user = await _signInManager.UserManager.FindByIdAsync(account.Id.ToString()).ConfigureAwait(false);
if (user is null) return new SignInServiceResult(SignInResultType.Failed);
var result = await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure).ConfigureAwait(false);
if (result.IsLockedOut)
await _signInManager.UserManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
@@ -4,11 +4,11 @@ using System.Globalization;
using System.Security.Claims;
using System.Text;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Security;
public class JwtService : IJwtService
@@ -22,10 +22,10 @@ public class JwtService : IJwtService
_logger = logger;
}
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions)
public (string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions)
=> GenerateAccessToken(user, roles, permissions, DateTime.UtcNow);
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions, DateTime sessionStarted)
public (string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions, DateTime sessionStarted)
{
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(GetJwtKey()));
@@ -61,10 +61,10 @@ public class JwtService : IJwtService
return (new JwtSecurityTokenHandler().WriteToken(token), expiresAt);
}
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user)
public (string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user)
=> GenerateRefreshToken(user, DateTime.UtcNow);
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted)
public (string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user, DateTime sessionStarted)
{
var refreshKeyValue = GetJwtRefreshKey();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshKeyValue));
@@ -5,17 +5,18 @@ using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Security;
public sealed class RolePermissionService : IRolePermissionService
{
private const string PermissionClaim = "permission";
private const string ConfiguredClaim = "heimdall:permissions-configured";
private readonly RoleManager<AppRole> _roles;
private readonly UserManager<AppUser> _users;
private readonly RoleManager<IdentityAppRole> _roles;
private readonly UserManager<IdentityAppUser> _users;
private readonly IUserRepository _userRepository;
public RolePermissionService(RoleManager<AppRole> roles, UserManager<AppUser> users, IUserRepository userRepository)
public RolePermissionService(RoleManager<IdentityAppRole> roles, UserManager<IdentityAppUser> users, IUserRepository userRepository)
{
_roles = roles;
_users = users;
@@ -128,7 +129,7 @@ public sealed class RolePermissionService : IRolePermissionService
}
}
private async Task<bool> AddClaimsAsync(AppRole role, IEnumerable<Claim> claims)
private async Task<bool> AddClaimsAsync(IdentityAppRole role, IEnumerable<Claim> claims)
{
var added = new List<Claim>();
foreach (var claim in claims)
@@ -146,7 +147,7 @@ public sealed class RolePermissionService : IRolePermissionService
return true;
}
private async Task<bool> RemoveClaimsAsync(AppRole role, IEnumerable<Claim> claims)
private async Task<bool> RemoveClaimsAsync(IdentityAppRole role, IEnumerable<Claim> claims)
{
var removed = new List<Claim>();
foreach (var claim in claims)
@@ -2,12 +2,12 @@ using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Identity;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Infrastructure.Services;
/// <summary>Union of explicit camera grants, legacy grants, sites and live group membership.</summary>
public class CameraAccessService(IApplicationDbContext context) : ICameraAccessService
public class CameraAccessService(IApplicationDbContext context, IIdentityPersistenceContext identity) : ICameraAccessService
{
public async Task<bool> HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default)
=> await ApplyCameraFilter(context.Cameras, userId).AnyAsync(c => c.Id == cameraId, ct);
@@ -24,10 +24,10 @@ public class CameraAccessService(IApplicationDbContext context) : ICameraAccessS
.ConfigureAwait(false);
if (!siteId.HasValue) return [];
return await context.Users.AsNoTracking()
return await identity.Users.AsNoTracking()
.Where(user =>
context.UserRoles.Any(ur => ur.UserId == user.Id &&
context.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin)) ||
identity.UserRoles.Any(ur => ur.UserId == user.Id &&
identity.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin)) ||
context.UserCameraAccesses.Any(grant => grant.UserId == user.Id && grant.SiteId == siteId.Value &&
(grant.CameraId == null || grant.CameraId == cameraId)) ||
context.UserCameras.Any(grant => grant.UserId == user.Id && grant.CameraId == cameraId) ||
@@ -68,6 +68,6 @@ public class CameraAccessService(IApplicationDbContext context) : ICameraAccessS
context.UserGroups.Any(m => m.UserId == userId && m.GroupId == a.GroupId)));
}
private bool IsAdmin(Guid userId) => userId != Guid.Empty && context.UserRoles.Any(ur =>
ur.UserId == userId && context.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
private bool IsAdmin(Guid userId) => userId != Guid.Empty && identity.UserRoles.Any(ur =>
ur.UserId == userId && identity.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
}
@@ -301,11 +301,11 @@ public class SettingsController : ControllerBase
[ProducesResponseType(typeof(object), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> TestEmail(
[FromServices] IEmailService emailService,
[FromServices] IApplicationDbContext db,
[FromServices] IIdentityAccountService identityAccounts,
CancellationToken ct)
{
var language = this.TryGetUserId(out var userId)
? await db.Users.AsNoTracking().Where(user => user.Id == userId).Select(user => user.Language).FirstOrDefaultAsync(ct)
? (await identityAccounts.FindByIdAsync(userId, ct).ConfigureAwait(false))?.Language
: null;
var settings = await _mediator.Send(new GetSettingsQuery(), ct);
if (!settings.IsSuccess)
+7 -7
View File
@@ -209,9 +209,9 @@ public partial class Program
{
using var seedScope = app.Services.CreateScope();
var roleManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Infrastructure.Identity.IdentityAppRole>>();
var userManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Infrastructure.Identity.IdentityAppUser>>();
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
await SeedRolesAsync(roleManager);
@@ -225,13 +225,13 @@ public partial class Program
await SeedDemoDataAsync(configuration, userManager, groupDb);
}
private static async Task SeedRolesAsync(Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole> roleManager)
private static async Task SeedRolesAsync(Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Infrastructure.Identity.IdentityAppRole> roleManager)
{
foreach (var roleName in AppRoles.All)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
await roleManager.CreateAsync(new Heimdall.Infrastructure.Identity.IdentityAppRole(roleName));
}
}
}
@@ -382,7 +382,7 @@ public partial class Program
private static async Task SeedDemoDataAsync(
IConfiguration configuration,
Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser> userManager,
Microsoft.AspNetCore.Identity.UserManager<Heimdall.Infrastructure.Identity.IdentityAppUser> userManager,
AppDbContext groupDb)
{
if (!configuration.GetValue<bool>("Seed:DemoOnStartup", false))
@@ -394,7 +394,7 @@ public partial class Program
var testAdmin = await userManager.FindByEmailAsync(adminLogin);
if (testAdmin is null)
{
testAdmin = new Heimdall.Domain.Entities.AppUser
testAdmin = new Heimdall.Infrastructure.Identity.IdentityAppUser
{
UserName = adminLogin,
Email = adminLogin,
@@ -689,7 +689,7 @@ public partial class Program
private static Task<bool> ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) =>
Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidAsync(principal,
http.RequestServices.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>(),
http.RequestServices.GetRequiredService<Heimdall.Application.Services.IIdentityAccountService>(),
http.RequestServices.GetRequiredService<Heimdall.Application.Services.IAuthDataService>(), http.RequestAborted);
private static void ConfigureJwtBearerAuthentication(AuthenticationBuilder authBuilder, string jwtKey, string jwtIssuer, string jwtAudience)
+4 -3
View File
@@ -14,7 +14,8 @@ public sealed record Requester(RequesterKind Kind, Guid Id, Guid? SiteId = null)
/// <summary>Resolves identities from persisted state; never treats an API key ID as a user ID.</summary>
public sealed class ResourceAccess(
IApplicationDbContext db,
ICameraAccessService cameras)
ICameraAccessService cameras,
IIdentityAccountService identityAccounts)
{
public async Task<Requester?> ResolveAsync(ClaimsPrincipal? principal, CancellationToken ct = default)
{
@@ -37,12 +38,12 @@ public sealed class ResourceAccess(
(claimedSite is not null && claimedSite != key.SiteId.Value.ToString())) return null;
return new(RequesterKind.Agent, bound[0], key.SiteId);
}
if (!await AccountSessionPolicy.IsValidLiveAsync(principal, db, ct)) return null;
if (!await AccountSessionPolicy.IsValidLiveAsync(principal, identityAccounts, db, ct)) return null;
return new(RequesterKind.Human, id);
}
public Task<bool> IsAdminAsync(Requester r, CancellationToken ct = default) => r.Kind == RequesterKind.Human
? db.UserRoles.AnyAsync(ur => ur.UserId == r.Id && db.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin), ct)
? identityAccounts.IsInRoleAsync(r.Id, AppRoles.Admin, ct)
: Task.FromResult(false);
// Full-site rights are required for site metadata, inventories, agents and site-wide changes.
@@ -3,7 +3,6 @@ using System.IdentityModel.Tokens.Jwt;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.AspNetCore.Components.Authorization;
@@ -44,7 +43,7 @@ public class HeimdallAuthStateProvider : RevalidatingServerAuthenticationStatePr
if (_scopeFactory is null) return false;
await using var scope = _scopeFactory.CreateAsyncScope();
var valid = await AccountSessionPolicy.IsValidAsync(state.User,
scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>(),
scope.ServiceProvider.GetRequiredService<IIdentityAccountService>(),
scope.ServiceProvider.GetRequiredService<IAuthDataService>(), cancellationToken);
if (!valid) await NotifyLogoutAsync();
return valid;
+4 -6
View File
@@ -44,9 +44,9 @@
},
"Microsoft.AspNetCore.App.Internal.Assets": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "Y2cXnMnqht5fvja2H8kkr5WA2fYItIPwXiBVo83+/9oySuKZCrz4T+yyZRFtLpxxDScvtYDt7e+J0eNElJ+AiA=="
"requested": "[10.0.14, )",
"resolved": "10.0.14",
"contentHash": "T1IOYbID1msKjQEh684HebnN+Xnq/pocMXDukOMZtzzPTf9c4/30+/JndM/1txrqwuSYqWvLiAQWzu4U93cshw=="
},
"Microsoft.AspNetCore.OpenApi": {
"type": "Direct",
@@ -496,7 +496,6 @@
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
@@ -509,8 +508,7 @@
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
@@ -5,12 +5,13 @@ using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Shouldly;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class CreateUserCameraAccessHandlerTests
{
private readonly List<AppUser> _users = [new AppUser { Id = Guid.NewGuid(), Email = "test@heimdall.local", UserName = "test" }];
private readonly List<IdentityAccount> _users = [new IdentityAccount { Id = Guid.NewGuid(), Email = "test@heimdall.local", UserName = "test" }];
private readonly List<Site> _sites = [new Site("Site1", "Paris", "Europe/Paris")];
private readonly List<Camera> _cameras = [new Camera(Guid.NewGuid(), "Cam1", "rtsp://cam1")];
@@ -21,13 +22,12 @@ public class CreateUserCameraAccessHandlerTests
var siteId = _sites[0].Id;
var context = Substitute.For<IApplicationDbContext>();
context.Users.Returns(MockDbSetHelper.CreateFor(_users));
context.Sites.Returns(MockDbSetHelper.CreateFor(_sites));
context.Cameras.Returns(MockDbSetHelper.CreateFor(_cameras));
context.UserCameraAccesses.Returns(MockDbSetHelper.CreateFor<UserCameraAccess>([]));
context.AuditLogs.Returns(Substitute.For<Microsoft.EntityFrameworkCore.DbSet<AuditLog>>());
var handler = new CreateUserCameraAccessHandler(context);
var handler = new CreateUserCameraAccessHandler(context, IdentityForUser(userId));
var command = new CreateUserCameraAccessCommand(userId, siteId, CameraId: null);
var result = await handler.Handle(command, CancellationToken.None);
@@ -53,13 +53,12 @@ public class CreateUserCameraAccessHandlerTests
var cameraId = camera.Id;
var context = Substitute.For<IApplicationDbContext>();
context.Users.Returns(MockDbSetHelper.CreateFor(_users));
context.Sites.Returns(MockDbSetHelper.CreateFor(_sites));
context.Cameras.Returns(MockDbSetHelper.CreateFor(new List<Camera> { camera }));
context.UserCameraAccesses.Returns(MockDbSetHelper.CreateFor<UserCameraAccess>([]));
context.AuditLogs.Returns(Substitute.For<Microsoft.EntityFrameworkCore.DbSet<AuditLog>>());
var handler = new CreateUserCameraAccessHandler(context);
var handler = new CreateUserCameraAccessHandler(context, IdentityForUser(userId));
var command = new CreateUserCameraAccessCommand(userId, siteId, cameraId, actorId);
var result = await handler.Handle(command, CancellationToken.None);
@@ -76,11 +75,10 @@ public class CreateUserCameraAccessHandlerTests
public async Task Create_should_return_not_found_when_user_not_exists()
{
var context = Substitute.For<IApplicationDbContext>();
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([]));
context.Sites.Returns(MockDbSetHelper.CreateFor(_sites));
context.UserCameraAccesses.Returns(MockDbSetHelper.CreateFor<UserCameraAccess>([]));
var handler = new CreateUserCameraAccessHandler(context);
var handler = new CreateUserCameraAccessHandler(context, Substitute.For<IIdentityAccountService>());
var command = new CreateUserCameraAccessCommand(Guid.NewGuid(), _sites[0].Id);
var result = await handler.Handle(command, CancellationToken.None);
@@ -93,11 +91,10 @@ public class CreateUserCameraAccessHandlerTests
public async Task Create_should_return_not_found_when_site_not_exists()
{
var context = Substitute.For<IApplicationDbContext>();
context.Users.Returns(MockDbSetHelper.CreateFor(_users));
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>([]));
context.UserCameraAccesses.Returns(MockDbSetHelper.CreateFor<UserCameraAccess>([]));
var handler = new CreateUserCameraAccessHandler(context);
var handler = new CreateUserCameraAccessHandler(context, IdentityForUser(_users[0].Id));
var command = new CreateUserCameraAccessCommand(_users[0].Id, Guid.NewGuid());
var result = await handler.Handle(command, CancellationToken.None);
@@ -111,12 +108,11 @@ public class CreateUserCameraAccessHandlerTests
{
var camera = new Camera(Guid.NewGuid(), "CamOther", "rtsp://other");
var context = Substitute.For<IApplicationDbContext>();
context.Users.Returns(MockDbSetHelper.CreateFor(_users));
context.Sites.Returns(MockDbSetHelper.CreateFor(_sites));
context.Cameras.Returns(MockDbSetHelper.CreateFor(_cameras));
context.UserCameraAccesses.Returns(MockDbSetHelper.CreateFor<UserCameraAccess>([]));
var handler = new CreateUserCameraAccessHandler(context);
var handler = new CreateUserCameraAccessHandler(context, IdentityForUser(_users[0].Id));
var command = new CreateUserCameraAccessCommand(_users[0].Id, _sites[0].Id, camera.Id);
var result = await handler.Handle(command, CancellationToken.None);
@@ -133,11 +129,10 @@ public class CreateUserCameraAccessHandlerTests
var existingAccess = new UserCameraAccess(userId, siteId);
var context = Substitute.For<IApplicationDbContext>();
context.Users.Returns(MockDbSetHelper.CreateFor(_users));
context.Sites.Returns(MockDbSetHelper.CreateFor(_sites));
context.UserCameraAccesses.Returns(MockDbSetHelper.CreateFor([existingAccess]));
var handler = new CreateUserCameraAccessHandler(context);
var handler = new CreateUserCameraAccessHandler(context, IdentityForUser(userId));
var command = new CreateUserCameraAccessCommand(userId, siteId);
var result = await handler.Handle(command, CancellationToken.None);
@@ -145,4 +140,11 @@ public class CreateUserCameraAccessHandlerTests
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(409);
}
private static IIdentityAccountService IdentityForUser(Guid userId)
{
var identity = Substitute.For<IIdentityAccountService>();
identity.FindByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(new IdentityAccount { Id = userId });
return identity;
}
}
@@ -6,6 +6,7 @@ using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using Shouldly;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Assignments;
@@ -14,12 +15,12 @@ public class ReplaceUserCameraAccessHandlerTests
[Fact]
public async Task Replace_validates_before_mutating_and_keeps_existing_grants_on_invalid_camera()
{
var user = new AppUser { Id = Guid.NewGuid() };
var user = new IdentityAccount { Id = Guid.NewGuid() };
var site = new Site("Site", "Paris", "Europe/Paris");
var existing = new UserCameraAccess(user.Id, site.Id);
var accesses = MockDbSetHelper.CreateFor([existing]);
var db = CreateContext(user, site, [], accesses);
var handler = new ReplaceUserCameraAccessCommandHandler(db);
var handler = new ReplaceUserCameraAccessCommandHandler(db, IdentityForUser(user.Id));
var result = await handler.Handle(new ReplaceUserCameraAccessCommand(user.Id,
[new UserCameraAccessGrantRequest(site.Id, Guid.NewGuid())], Guid.NewGuid()), CancellationToken.None);
@@ -33,14 +34,14 @@ public class ReplaceUserCameraAccessHandlerTests
[Fact]
public async Task Replace_applies_complete_grant_set_and_audits_actor_and_snapshots()
{
var user = new AppUser { Id = Guid.NewGuid() };
var user = new IdentityAccount { Id = Guid.NewGuid() };
var site = new Site("Site", "Paris", "Europe/Paris");
var camera = new Camera(site.Id, "Cam", "rtsp://camera");
var existing = new UserCameraAccess(user.Id, site.Id);
var accesses = MockDbSetHelper.CreateFor([existing]);
var db = CreateContext(user, site, [camera], accesses);
db.AuditLogs.Returns(Substitute.For<DbSet<AuditLog>>());
var handler = new ReplaceUserCameraAccessCommandHandler(db);
var handler = new ReplaceUserCameraAccessCommandHandler(db, IdentityForUser(user.Id));
var actorId = Guid.NewGuid();
var result = await handler.Handle(new ReplaceUserCameraAccessCommand(user.Id,
@@ -59,12 +60,12 @@ public class ReplaceUserCameraAccessHandlerTests
[Fact]
public async Task Replace_rejects_duplicate_grants_without_changing_accesses()
{
var user = new AppUser { Id = Guid.NewGuid() };
var user = new IdentityAccount { Id = Guid.NewGuid() };
var site = new Site("Site", "Paris", "Europe/Paris");
var existing = new UserCameraAccess(user.Id, site.Id);
var accesses = MockDbSetHelper.CreateFor([existing]);
var db = CreateContext(user, site, [], accesses);
var handler = new ReplaceUserCameraAccessCommandHandler(db);
var handler = new ReplaceUserCameraAccessCommandHandler(db, IdentityForUser(user.Id));
var result = await handler.Handle(new ReplaceUserCameraAccessCommand(user.Id,
[new UserCameraAccessGrantRequest(site.Id), new UserCameraAccessGrantRequest(site.Id)], Guid.NewGuid()),
@@ -76,14 +77,20 @@ public class ReplaceUserCameraAccessHandlerTests
}
private static IApplicationDbContext CreateContext(
AppUser user, Site site, IEnumerable<Camera> cameras, DbSet<UserCameraAccess> accesses)
IdentityAccount user, Site site, IEnumerable<Camera> cameras, DbSet<UserCameraAccess> accesses)
{
var db = Substitute.For<IApplicationDbContext>();
db.Users.Returns(MockDbSetHelper.CreateFor([user]));
db.Sites.Returns(MockDbSetHelper.CreateFor([site]));
db.Cameras.Returns(MockDbSetHelper.CreateFor(cameras));
db.UserCameraAccesses.Returns(accesses);
db.AuditLogs.Returns(Substitute.For<DbSet<AuditLog>>());
return db;
}
private static IIdentityAccountService IdentityForUser(Guid userId)
{
var identity = Substitute.For<IIdentityAccountService>();
identity.FindByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(new IdentityAccount { Id = userId });
return identity;
}
}
@@ -1,7 +1,6 @@
using Heimdall.Application.Auth.Commands.ChangePassword;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -9,16 +8,14 @@ namespace Heimdall.Application.Tests.Handlers.Auth;
public class ChangePasswordHandlerTests
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IPasswordBreachChecker _breachChecker;
private readonly ILogger<ChangePasswordHandler> _logger;
private readonly ChangePasswordHandler _handler;
public ChangePasswordHandlerTests()
{
var userStore = Substitute.For<IUserStore<AppUser>>();
var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions());
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_breachChecker = Substitute.For<IPasswordBreachChecker>();
_logger = Substitute.For<ILogger<ChangePasswordHandler>>();
_handler = new ChangePasswordHandler(_userManager, _breachChecker, _logger);
@@ -27,11 +24,11 @@ public class ChangePasswordHandlerTests
[Fact]
public async Task Change_password_with_valid_data_should_return_success()
{
var user = new AppUser { Id = Guid.NewGuid() };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
var user = new IdentityAccount { Id = Guid.NewGuid() };
_userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
_userManager.ChangePasswordAsync(user, "old-password", "new-password")
.Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(user).Returns(IdentityResult.Success);
.Returns(IdentityOperationResult.Success);
_userManager.UpdateSecurityStampAsync(user).Returns(true);
var result = await _handler.Handle(
new ChangePasswordCommand(user.Id, "old-password", "new-password"), CancellationToken.None);
@@ -43,7 +40,7 @@ public class ChangePasswordHandlerTests
public async Task Change_password_for_unknown_user_should_return_not_found()
{
var userId = Guid.NewGuid();
_userManager.FindByIdAsync(userId.ToString()).Returns((AppUser?)null);
_userManager.FindByIdAsync(userId, Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(
new ChangePasswordCommand(userId, "old", "new"), CancellationToken.None);
@@ -55,10 +52,10 @@ public class ChangePasswordHandlerTests
[Fact]
public async Task Change_password_when_change_fails_should_return_error()
{
var user = new AppUser { Id = Guid.NewGuid() };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
var user = new IdentityAccount { Id = Guid.NewGuid() };
_userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
_userManager.ChangePasswordAsync(user, "wrong", "new")
.Returns(IdentityResult.Failed(new IdentityError { Description = "Incorrect password" }));
.Returns(new IdentityOperationResult(false, ["PasswordMismatch"]));
var result = await _handler.Handle(
new ChangePasswordCommand(user.Id, "wrong", "new"), CancellationToken.None);
@@ -2,9 +2,9 @@ using Heimdall.Application.Auth.Commands.Disable2fa;
using Heimdall.Application.Common;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Auth;
@@ -13,13 +13,11 @@ public sealed class Disable2faHandlerTests
[Fact]
public async Task Wrong_current_password_does_not_disable_two_factor()
{
var store = Substitute.For<IUserStore<AppUser>>();
var users = Substitute.For<UserManager<AppUser>>(store,
Microsoft.Extensions.Options.Options.Create(new IdentityOptions()), null!, null!, null!, null!, null!, null!, null!);
var users = Substitute.For<IIdentityAccountService>();
var db = Substitute.For<IApplicationDbContext>();
db.UserRecoveryCodes.Returns(MockDbSetHelper.CreateFor<UserRecoveryCode>());
var user = new AppUser { Id = Guid.NewGuid() };
users.FindByIdAsync(user.Id.ToString()).Returns(user);
var user = new IdentityAccount { Id = Guid.NewGuid() };
users.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
users.CheckPasswordAsync(user, "wrong").Returns(false);
var handler = new Disable2faHandler(users, db, Substitute.For<ILogger<Disable2faHandler>>());
@@ -3,15 +3,15 @@ using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Auth;
public class Enable2faHandlerTests
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IApplicationDbContext _db;
private readonly ILogger<Enable2faHandler> _logger;
private readonly Enable2faHandler _handler;
@@ -19,9 +19,7 @@ public class Enable2faHandlerTests
public Enable2faHandlerTests()
{
var userStore = Substitute.For<IUserStore<AppUser>>();
var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions());
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_db = Substitute.For<IApplicationDbContext>();
_logger = Substitute.For<ILogger<Enable2faHandler>>();
_recoveryCodes = (InMemoryDbSet<UserRecoveryCode>)MockDbSetHelper.CreateFor<UserRecoveryCode>();
@@ -32,10 +30,10 @@ public class Enable2faHandlerTests
[Fact]
public async Task Enable2fa_should_initialize_key_without_activating_or_issuing_recovery_codes()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
_userManager.CheckPasswordAsync(user, "Current-password-123!").Returns(true);
_userManager.ResetAuthenticatorKeyAsync(user).Returns(IdentityResult.Success);
_userManager.ResetAuthenticatorKeyAsync(user).Returns(IdentityOperationResult.Success);
_userManager.GetAuthenticatorKeyAsync(user).Returns("ABCDEF123456");
var result = await _handler.Handle(new Enable2faCommand(user.Id, "Current-password-123!"), CancellationToken.None);
@@ -50,7 +48,7 @@ public class Enable2faHandlerTests
[Fact]
public async Task Enable2fa_with_unknown_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
_userManager.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(new Enable2faCommand(Guid.NewGuid(), "Current-password-123!"), CancellationToken.None);
@@ -62,8 +60,8 @@ public class Enable2faHandlerTests
[Fact]
public async Task Enable2fa_with_wrong_current_password_should_not_rotate_authenticator_key()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
_userManager.CheckPasswordAsync(user, "wrong").Returns(false);
var result = await _handler.Handle(new Enable2faCommand(user.Id, "wrong"), CancellationToken.None);
@@ -76,11 +74,11 @@ public class Enable2faHandlerTests
[Fact]
public async Task Enable2fa_when_identity_fails_should_return_failure()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
_userManager.CheckPasswordAsync(user, "Current-password-123!").Returns(true);
_userManager.ResetAuthenticatorKeyAsync(user)
.Returns(IdentityResult.Failed(new IdentityError { Description = "boom" }));
.Returns(new IdentityOperationResult(false, ["Failure"]));
var result = await _handler.Handle(new Enable2faCommand(user.Id, "Current-password-123!"), CancellationToken.None);
@@ -5,7 +5,6 @@ using Heimdall.Application.Services;
using Heimdall.Application.Common;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Heimdall.Application.Common.Persistence;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -14,7 +13,7 @@ namespace Heimdall.Application.Tests.Handlers.Auth;
public class LoginHandlerTests
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IAuthSignInService _signInService;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
@@ -25,9 +24,7 @@ public class LoginHandlerTests
public LoginHandlerTests()
{
var userStore = Substitute.For<IUserStore<AppUser>>();
var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions());
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_signInService = Substitute.For<IAuthSignInService>();
_jwtService = Substitute.For<IJwtService>();
_rolePermissionService = Substitute.For<IRolePermissionService>();
@@ -47,8 +44,8 @@ public class LoginHandlerTests
[Fact]
public async Task Login_with_valid_credentials_should_return_success()
{
var user = new AppUser { UserName = "test@test.com", Email = "test@test.com", DisplayName = "Test" };
_userManager.FindByEmailAsync("test@test.com").Returns(user);
var user = new IdentityAccount { UserName = "test@test.com", Email = "test@test.com", DisplayName = "Test" };
_userManager.FindByEmailAsync("test@test.com", Arg.Any<CancellationToken>()).Returns(user);
_userManager.IsLockedOutAsync(user).Returns(false);
_userManager.GetTwoFactorEnabledAsync(user).Returns(false);
_userManager.GetRolesAsync(user).Returns(["Viewer"]);
@@ -70,7 +67,7 @@ public class LoginHandlerTests
[Fact]
public async Task Login_with_unknown_email_should_return_unauthorized()
{
_userManager.FindByEmailAsync("unknown@test.com").Returns((AppUser?)null);
_userManager.FindByEmailAsync("unknown@test.com").Returns((IdentityAccount?)null);
var result = await _handler.Handle(new LoginCommand("unknown@test.com", "password"), CancellationToken.None);
@@ -81,8 +78,8 @@ public class LoginHandlerTests
[Fact]
public async Task Login_with_locked_account_should_return_generic_unauthorized()
{
var user = new AppUser { UserName = "locked@test.com", Email = "locked@test.com" };
_userManager.FindByEmailAsync("locked@test.com").Returns(user);
var user = new IdentityAccount { UserName = "locked@test.com", Email = "locked@test.com" };
_userManager.FindByEmailAsync("locked@test.com", Arg.Any<CancellationToken>()).Returns(user);
_userManager.IsLockedOutAsync(user).Returns(true);
var result = await _handler.Handle(new LoginCommand("locked@test.com", "password"), CancellationToken.None);
@@ -94,8 +91,8 @@ public class LoginHandlerTests
[Fact]
public async Task Login_with_2fa_enabled_should_require_2fa()
{
var user = new AppUser { UserName = "2fa@test.com", Email = "2fa@test.com" };
_userManager.FindByEmailAsync("2fa@test.com").Returns(user);
var user = new IdentityAccount { UserName = "2fa@test.com", Email = "2fa@test.com" };
_userManager.FindByEmailAsync("2fa@test.com", Arg.Any<CancellationToken>()).Returns(user);
_userManager.IsLockedOutAsync(user).Returns(false);
_userManager.GetTwoFactorEnabledAsync(user).Returns(true);
_signInService.PasswordSignInAsync(user, "password", true)
@@ -110,8 +107,8 @@ public class LoginHandlerTests
[Fact]
public async Task Login_with_wrong_password_should_return_unauthorized()
{
var user = new AppUser { UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByEmailAsync("test@test.com").Returns(user);
var user = new IdentityAccount { UserName = "test@test.com", Email = "test@test.com" };
_userManager.FindByEmailAsync("test@test.com", Arg.Any<CancellationToken>()).Returns(user);
_userManager.IsLockedOutAsync(user).Returns(false);
_userManager.GetTwoFactorEnabledAsync(user).Returns(false);
_signInService.PasswordSignInAsync(user, "wrong", true)
@@ -3,7 +3,6 @@ using Heimdall.Application.Auth.Commands.RefreshToken;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -12,7 +11,7 @@ namespace Heimdall.Application.Tests.Handlers.Auth;
public class RefreshTokenHandlerTests
{
private readonly IJwtService _jwtService;
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IRolePermissionService _rolePermissionService;
private readonly IAuthDataService _authData;
private readonly ILogger<RefreshTokenHandler> _logger;
@@ -20,10 +19,8 @@ public class RefreshTokenHandlerTests
public RefreshTokenHandlerTests()
{
var userStore = Substitute.For<IUserStore<AppUser>>();
_jwtService = Substitute.For<IJwtService>();
var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions());
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_rolePermissionService = Substitute.For<IRolePermissionService>();
_authData = Substitute.For<IAuthDataService>();
_logger = Substitute.For<ILogger<RefreshTokenHandler>>();
@@ -33,11 +30,11 @@ public class RefreshTokenHandlerTests
[Fact]
public async Task Refresh_with_valid_token_should_return_new_tokens()
{
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", DisplayName = "Test", SecurityStamp = "stamp" };
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test@test.com", DisplayName = "Test", SecurityStamp = "stamp" };
var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim("jti", "token-id"), new Claim("security_stamp", "stamp"), new Claim("session_started", DateTime.UtcNow.ToString("O"))]));
_jwtService.ValidateRefreshToken("valid-token").Returns(principal);
_authData.IsRefreshTokenRevokedAsync("token-id", Arg.Any<CancellationToken>()).Returns(false);
_userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
_userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
_userManager.GetRolesAsync(user).Returns(["Viewer"]);
_jwtService.GenerateAccessToken(user, Arg.Any<IList<string>>(), Arg.Any<IList<string>>(), Arg.Any<DateTime>())
.Returns(("new-access-token", DateTime.UtcNow.AddHours(1)));
@@ -83,7 +80,7 @@ public class RefreshTokenHandlerTests
new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim("jti", "token-id"), new Claim("security_stamp", "stamp"), new Claim("session_started", DateTime.UtcNow.ToString("O"))]));
_jwtService.ValidateRefreshToken("token").Returns(principal);
_authData.IsRefreshTokenRevokedAsync("token-id", Arg.Any<CancellationToken>()).Returns(false);
_userManager.FindByIdAsync(userId.ToString()).Returns((AppUser?)null);
_userManager.FindByIdAsync(userId, Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(new RefreshTokenCommand("token"), CancellationToken.None);
@@ -4,7 +4,6 @@ using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -12,7 +11,7 @@ namespace Heimdall.Application.Tests.Handlers.Auth;
public class Verify2faHandlerTests
{
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IJwtService _jwtService;
private readonly IRolePermissionService _rolePermissionService;
private readonly IApplicationDbContext _db;
@@ -22,9 +21,7 @@ public class Verify2faHandlerTests
public Verify2faHandlerTests()
{
var userStore = Substitute.For<IUserStore<AppUser>>();
var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions());
_userManager = Substitute.For<UserManager<AppUser>>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_jwtService = Substitute.For<IJwtService>();
_rolePermissionService = Substitute.For<IRolePermissionService>();
_rolePermissionService.GetPermissionsForRolesAsync(Arg.Any<IList<string>>(), Arg.Any<CancellationToken>())
@@ -44,6 +41,6 @@ public class Verify2faHandlerTests
{
var result = await _handler.Handle(new Verify2faCommand(proof, "123456"), CancellationToken.None);
result.StatusCode.ShouldBe(401);
await _userManager.DidNotReceiveWithAnyArgs().VerifyTwoFactorTokenAsync(null!, null!, null!);
await _userManager.DidNotReceiveWithAnyArgs().VerifyAuthenticatorTokenAsync(Arg.Any<IdentityAccount>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}
@@ -4,13 +4,14 @@ using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class AddUserToGroupHandlerTests
{
private readonly Group _group = new("Test Group", "Description");
private readonly AppUser _user = new()
private readonly IdentityAccount _user = new()
{
Id = Guid.NewGuid(),
UserName = "user@test.com",
@@ -24,12 +25,13 @@ public class AddUserToGroupHandlerTests
AuditLog? auditLog = null;
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([_user]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var auditLogs = Substitute.For<DbSet<AuditLog>>();
auditLogs.When(set => set.Add(Arg.Any<AuditLog>())).Do(call => auditLog = call.Arg<AuditLog>());
context.AuditLogs.Returns(auditLogs);
var handler = new AddUserToGroupCommandHandler(context);
var identity = Substitute.For<IIdentityAccountService>();
identity.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
var handler = new AddUserToGroupCommandHandler(context, identity);
var result = await handler.Handle(
new AddUserToGroupCommand(_group.Id, _user.Id, actorId), CancellationToken.None);
@@ -47,9 +49,10 @@ public class AddUserToGroupHandlerTests
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([_user]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new AddUserToGroupCommandHandler(context);
var identity = Substitute.For<IIdentityAccountService>();
identity.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
var handler = new AddUserToGroupCommandHandler(context, identity);
var result = await handler.Handle(
new AddUserToGroupCommand(Guid.NewGuid(), _user.Id), CancellationToken.None);
@@ -63,9 +66,8 @@ public class AddUserToGroupHandlerTests
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>());
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new AddUserToGroupCommandHandler(context);
var handler = new AddUserToGroupCommandHandler(context, Substitute.For<IIdentityAccountService>());
var result = await handler.Handle(
new AddUserToGroupCommand(_group.Id, Guid.NewGuid()), CancellationToken.None);
@@ -80,9 +82,10 @@ public class AddUserToGroupHandlerTests
var existingMembership = new UserGroup(_user.Id, _group.Id);
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([_user]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>([existingMembership]));
var handler = new AddUserToGroupCommandHandler(context);
var identity = Substitute.For<IIdentityAccountService>();
identity.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
var handler = new AddUserToGroupCommandHandler(context, identity);
var result = await handler.Handle(
new AddUserToGroupCommand(_group.Id, _user.Id), CancellationToken.None);
@@ -5,6 +5,8 @@ using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
using Heimdall.Application.Services;
using Heimdall.Application.Common.Persistence;
namespace Heimdall.Application.Tests.Handlers.Groups;
@@ -19,14 +21,16 @@ public class GetGroupMembersHandlerTests
var userGroup1 = new UserGroup(userId1, group.Id);
var userGroup2 = new UserGroup(userId2, group.Id);
var user1 = new AppUser { Id = userId1, UserName = "a@test.com", Email = "a@test.com", DisplayName = "User A" };
var user2 = new AppUser { Id = userId2, UserName = "b@test.com", Email = "b@test.com", DisplayName = "User B" };
var user1 = new IdentityAccount { Id = userId1, UserName = "a@test.com", Email = "a@test.com", DisplayName = "User A" };
var user2 = new IdentityAccount { Id = userId2, UserName = "b@test.com", Email = "b@test.com", DisplayName = "User B" };
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([group]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>([userGroup1, userGroup2]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([user1, user2]));
var handler = new GetGroupMembersQueryHandler(context);
var users = Substitute.For<IUserRepository>();
users.GetGroupMembersAsync(group.Id, Arg.Any<CancellationToken>()).Returns([
new GroupMemberResponse(user1.Id, user1.Email!, user1.DisplayName),
new GroupMemberResponse(user2.Id, user2.Email!, user2.DisplayName)]);
var handler = new GetGroupMembersQueryHandler(context, users);
var result = await handler.Handle(new GetGroupMembersQuery(group.Id), CancellationToken.None);
@@ -40,7 +44,7 @@ public class GetGroupMembersHandlerTests
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>());
var handler = new GetGroupMembersQueryHandler(context);
var handler = new GetGroupMembersQueryHandler(context, Substitute.For<IUserRepository>());
var result = await handler.Handle(new GetGroupMembersQuery(Guid.NewGuid()), CancellationToken.None);
@@ -54,9 +58,9 @@ public class GetGroupMembersHandlerTests
var group = new Group("Empty Group", null);
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([group]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>());
var handler = new GetGroupMembersQueryHandler(context);
var users = Substitute.For<IUserRepository>();
users.GetGroupMembersAsync(group.Id, Arg.Any<CancellationToken>()).Returns([]);
var handler = new GetGroupMembersQueryHandler(context, users);
var result = await handler.Handle(new GetGroupMembersQuery(group.Id), CancellationToken.None);
@@ -2,28 +2,27 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.AssignRoles;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
public class AssignRolesHandlerTests
{
private readonly AppUser _user = new()
private readonly IdentityAccount _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
Email = "test@test.com"
};
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
private readonly AssignRolesHandler _handler;
public AssignRolesHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_repository = Substitute.For<IUserRepository>();
_handler = new AssignRolesHandler(_userManager, _repository);
}
@@ -31,11 +30,11 @@ public class AssignRolesHandlerTests
[Fact]
public async Task Assign_roles_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityOperationResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityOperationResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(true);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Admin", "Manager" }), CancellationToken.None);
@@ -48,7 +47,7 @@ public class AssignRolesHandlerTests
[Fact]
public async Task Assign_roles_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
_userManager.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(
new AssignRolesCommand(Guid.NewGuid(), new List<string> { "Admin" }), CancellationToken.None);
@@ -60,7 +59,7 @@ public class AssignRolesHandlerTests
[Fact]
public async Task Remove_last_admin_role_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin" });
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(1);
@@ -74,11 +73,11 @@ public class AssignRolesHandlerTests
[Fact]
public async Task Assign_roles_should_allow_keeping_admin()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin", "Viewer" });
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityOperationResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityOperationResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(true);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Admin", "Manager" }), CancellationToken.None);
@@ -2,28 +2,27 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.AssignSites;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
public class AssignSitesHandlerTests
{
private readonly AppUser _user = new()
private readonly IdentityAccount _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
Email = "test@test.com"
};
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
private readonly AssignSitesHandler _handler;
public AssignSitesHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_repository = Substitute.For<IUserRepository>();
_handler = new AssignSitesHandler(_userManager, _repository);
}
@@ -31,7 +30,7 @@ public class AssignSitesHandlerTests
[Fact]
public async Task Assign_sites_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
var siteIds = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() };
var result = await _handler.Handle(
@@ -44,7 +43,7 @@ public class AssignSitesHandlerTests
[Fact]
public async Task Assign_sites_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
_userManager.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(
new AssignSitesCommand(Guid.NewGuid(), new List<Guid>()), CancellationToken.None);
@@ -56,7 +55,7 @@ public class AssignSitesHandlerTests
[Fact]
public async Task Assign_empty_sites_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
var emptySiteIds = new List<Guid>();
var result = await _handler.Handle(
@@ -1,9 +1,9 @@
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.ConfirmEmail;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Shouldly;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
@@ -13,11 +13,11 @@ public class ConfirmEmailCommandHandlerTests
public async Task Confirm_email_records_the_authenticated_actor()
{
var actorId = Guid.NewGuid();
var user = new AppUser { Id = Guid.NewGuid(), Email = "user@example.test", EmailConfirmed = false };
var user = new IdentityAccount { Id = Guid.NewGuid(), Email = "user@example.test", EmailConfirmed = false };
var userManager = CreateUserManager();
userManager.FindByIdAsync(user.Id.ToString()).Returns(user);
userManager.FindByIdAsync(user.Id, Arg.Any<CancellationToken>()).Returns(user);
userManager.GenerateEmailConfirmationTokenAsync(user).Returns("confirmation-token");
userManager.ConfirmEmailAsync(user, "confirmation-token").Returns(IdentityResult.Success);
userManager.ConfirmEmailAsync(user, "confirmation-token").Returns(IdentityOperationResult.Success);
var repository = Substitute.For<IUserRepository>();
var handler = new ConfirmEmailCommandHandler(userManager, repository);
@@ -30,7 +30,6 @@ public class ConfirmEmailCommandHandlerTests
Arg.Any<CancellationToken>());
}
private static UserManager<AppUser> CreateUserManager() =>
Substitute.For<UserManager<AppUser>>(
Substitute.For<IUserStore<AppUser>>(), null!, null!, null!, null!, null!, null!, null!, null!);
private static IIdentityAccountService CreateUserManager() =>
Substitute.For<IIdentityAccountService>();
}
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.DeleteUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
public class DeleteUserHandlerTests
{
private readonly AppUser _user = new()
private readonly IdentityAccount _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
@@ -20,14 +20,13 @@ public class DeleteUserHandlerTests
};
private readonly Guid _currentUserId = Guid.NewGuid();
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
private readonly DeleteUserHandler _handler;
public DeleteUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_repository = Substitute.For<IUserRepository>();
_handler = new DeleteUserHandler(_userManager, _repository);
}
@@ -35,9 +34,9 @@ public class DeleteUserHandlerTests
[Fact]
public async Task Delete_user_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.DeleteAsync(_user).Returns(IdentityResult.Success);
_userManager.DeleteAsync(_user).Returns(IdentityOperationResult.Success);
var result = await _handler.Handle(new DeleteUserCommand(_user.Id, _currentUserId), CancellationToken.None);
@@ -59,7 +58,7 @@ public class DeleteUserHandlerTests
[Fact]
public async Task Delete_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
_userManager.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(new DeleteUserCommand(Guid.NewGuid(), _currentUserId), CancellationToken.None);
@@ -70,7 +69,7 @@ public class DeleteUserHandlerTests
[Fact]
public async Task Delete_last_admin_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin" });
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(1);
@@ -83,9 +82,9 @@ public class DeleteUserHandlerTests
[Fact]
public async Task Delete_user_when_identity_fails_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.DeleteAsync(_user).Returns(IdentityResult.Failed(new IdentityError { Description = "Delete failed" }));
_userManager.DeleteAsync(_user).Returns(new IdentityOperationResult(false, ["Failure"]));
var result = await _handler.Handle(new DeleteUserCommand(_user.Id, _currentUserId), CancellationToken.None);
@@ -1,29 +1,28 @@
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.LockUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
public sealed class LockUserHandlerTests
{
private readonly AppUser _user = new() { Id = Guid.NewGuid(), UserName = "admin@example.test" };
private readonly UserManager<AppUser> _users;
private readonly IdentityAccount _user = new() { Id = Guid.NewGuid(), UserName = "admin@example.test" };
private readonly IIdentityAccountService _users;
private readonly IUserRepository _repository = Substitute.For<IUserRepository>();
private readonly LockUserHandler _handler;
public LockUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_users = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_users = Substitute.For<IIdentityAccountService>();
_handler = new LockUserHandler(_users, _repository);
}
[Fact]
public async Task Cannot_lock_the_last_admin()
{
_users.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_users.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_users.GetRolesAsync(_user).Returns(["Admin"]);
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(1);
@@ -31,17 +30,17 @@ public sealed class LockUserHandlerTests
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
await _users.DidNotReceive().SetLockoutEndDateAsync(Arg.Any<AppUser>(), Arg.Any<DateTimeOffset?>());
await _users.DidNotReceive().SetLockoutEndDateAsync(Arg.Any<IdentityAccount>(), Arg.Any<DateTimeOffset?>());
}
[Fact]
public async Task Can_lock_an_admin_when_another_admin_exists()
{
_users.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_users.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_users.GetRolesAsync(_user).Returns(["Admin"]);
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(2);
_users.SetLockoutEndDateAsync(_user, Arg.Any<DateTimeOffset?>()).Returns(IdentityResult.Success);
_users.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
_users.SetLockoutEndDateAsync(_user, Arg.Any<DateTimeOffset?>()).Returns(IdentityOperationResult.Success);
_users.UpdateSecurityStampAsync(_user).Returns(true);
var result = await _handler.Handle(new LockUserCommand(_user.Id), CancellationToken.None);
@@ -2,14 +2,14 @@ using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.UnlockUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
public class UnlockUserHandlerTests
{
private readonly AppUser _user = new()
private readonly IdentityAccount _user = new()
{
Id = Guid.NewGuid(),
UserName = "locked@test.com",
@@ -17,14 +17,13 @@ public class UnlockUserHandlerTests
LockoutEnd = DateTimeOffset.UtcNow.AddHours(1)
};
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
private readonly UnlockUserHandler _handler;
public UnlockUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_repository = Substitute.For<IUserRepository>();
_handler = new UnlockUserHandler(_userManager, _repository);
}
@@ -32,10 +31,10 @@ public class UnlockUserHandlerTests
[Fact]
public async Task Unlock_user_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.SetLockoutEndDateAsync(_user, null).Returns(IdentityResult.Success);
_userManager.ResetAccessFailedCountAsync(_user).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.SetLockoutEndDateAsync(_user, null).Returns(IdentityOperationResult.Success);
_userManager.ResetAccessFailedCountAsync(_user).Returns(IdentityOperationResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(true);
var result = await _handler.Handle(new UnlockUserCommand(_user.Id), CancellationToken.None);
@@ -47,7 +46,7 @@ public class UnlockUserHandlerTests
[Fact]
public async Task Unlock_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
_userManager.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(new UnlockUserCommand(Guid.NewGuid()), CancellationToken.None);
@@ -58,17 +57,17 @@ public class UnlockUserHandlerTests
[Fact]
public async Task Unlock_already_unlocked_user_should_return_success()
{
var unlockedUser = new AppUser
var unlockedUser = new IdentityAccount
{
Id = Guid.NewGuid(),
UserName = "unlocked@test.com",
Email = "unlocked@test.com",
LockoutEnd = null
};
_userManager.FindByIdAsync(unlockedUser.Id.ToString()).Returns(unlockedUser);
_userManager.SetLockoutEndDateAsync(unlockedUser, null).Returns(IdentityResult.Success);
_userManager.ResetAccessFailedCountAsync(unlockedUser).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(unlockedUser).Returns(IdentityResult.Success);
_userManager.FindByIdAsync(unlockedUser.Id, Arg.Any<CancellationToken>()).Returns(unlockedUser);
_userManager.SetLockoutEndDateAsync(unlockedUser, null).Returns(IdentityOperationResult.Success);
_userManager.ResetAccessFailedCountAsync(unlockedUser).Returns(IdentityOperationResult.Success);
_userManager.UpdateSecurityStampAsync(unlockedUser).Returns(true);
var result = await _handler.Handle(new UnlockUserCommand(unlockedUser.Id), CancellationToken.None);
@@ -3,14 +3,14 @@ using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Commands.UpdateUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Heimdall.Application.Services;
namespace Heimdall.Application.Tests.Handlers.Users;
public class UpdateUserHandlerTests
{
private readonly AppUser _user = new()
private readonly IdentityAccount _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
@@ -20,14 +20,13 @@ public class UpdateUserHandlerTests
Language = "fr"
};
private readonly UserManager<AppUser> _userManager;
private readonly IIdentityAccountService _userManager;
private readonly IUserRepository _repository;
private readonly UpdateUserHandler _handler;
public UpdateUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_userManager = Substitute.For<IIdentityAccountService>();
_repository = Substitute.For<IUserRepository>();
_handler = new UpdateUserHandler(_userManager, _repository);
}
@@ -35,8 +34,8 @@ public class UpdateUserHandlerTests
[Fact]
public async Task Update_user_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Success);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityOperationResult.Success);
_repository.GetByIdAsync(_user.Id, Arg.Any<CancellationToken>())
.Returns(new UserResponse(_user.Id, _user.Email!, "New Name", "Light", "en",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow));
@@ -52,7 +51,7 @@ public class UpdateUserHandlerTests
[Fact]
public async Task Update_user_nonexistent_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
_userManager.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IdentityAccount?)null);
var result = await _handler.Handle(
new UpdateUserCommand(Guid.NewGuid(), "Name", null, null), CancellationToken.None);
@@ -64,8 +63,8 @@ public class UpdateUserHandlerTests
[Fact]
public async Task Update_user_partial_should_keep_unchanged_values()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Success);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityOperationResult.Success);
_repository.GetByIdAsync(_user.Id, Arg.Any<CancellationToken>())
.Returns(new UserResponse(_user.Id, _user.Email!, "Old Name", "Dark", "fr",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow));
@@ -82,10 +81,10 @@ public class UpdateUserHandlerTests
var actorId = Guid.NewGuid();
const string newEmail = "updated@example.test";
_user.EmailConfirmed = true;
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByEmailAsync(newEmail).Returns((AppUser?)null);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(IdentityResult.Success);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.FindByEmailAsync(newEmail).Returns((IdentityAccount?)null);
_userManager.UpdateAsync(_user).Returns(IdentityOperationResult.Success);
_userManager.UpdateSecurityStampAsync(_user).Returns(true);
_repository.GetByIdAsync(_user.Id, Arg.Any<CancellationToken>())
.Returns(new UserResponse(_user.Id, newEmail, "Old Name", "Dark", "fr",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow));
@@ -108,8 +107,8 @@ public class UpdateUserHandlerTests
[Fact]
public async Task Update_user_email_returns_conflict_when_address_is_taken()
{
var otherUser = new AppUser { Id = Guid.NewGuid(), Email = "taken@example.test" };
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
var otherUser = new IdentityAccount { Id = Guid.NewGuid(), Email = "taken@example.test" };
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.FindByEmailAsync(otherUser.Email!).Returns(otherUser);
var result = await _handler.Handle(
@@ -117,27 +116,27 @@ public class UpdateUserHandlerTests
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(409);
await _userManager.DidNotReceive().UpdateAsync(Arg.Any<AppUser>());
await _userManager.DidNotReceive().UpdateAsync(Arg.Any<IdentityAccount>());
}
[Fact]
public async Task Update_user_email_rejects_malformed_address()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
var result = await _handler.Handle(
new UpdateUserCommand(_user.Id, null, null, null, "not-an-email"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.Error.ShouldBe("Adresse email invalide");
await _userManager.DidNotReceive().UpdateAsync(Arg.Any<AppUser>());
await _userManager.DidNotReceive().UpdateAsync(Arg.Any<IdentityAccount>());
}
[Fact]
public async Task Update_user_when_identity_fails_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Failed(new IdentityError { Description = "Update failed" }));
_userManager.FindByIdAsync(_user.Id, Arg.Any<CancellationToken>()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(new IdentityOperationResult(false, ["Failure"]));
var result = await _handler.Handle(
new UpdateUserCommand(_user.Id, "New Name", null, null), CancellationToken.None);
@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Playwright;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.E2E.Tests.Pages;
@@ -34,7 +35,7 @@ public class AuthFlowTests : E2ETestBase
{
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
foreach (var user in users.Users.ToList())
{
var deleted = await users.DeleteAsync(user);
@@ -62,7 +63,7 @@ public class AuthFlowTests : E2ETestBase
finally
{
using var scope = App.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
foreach (var user in users.Users.ToList())
await users.DeleteAsync(user);
await Program.SeedAsync(App, App.Configuration);
@@ -5,6 +5,7 @@ using Heimdall.Infrastructure.Security;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Tests;
@@ -77,7 +78,7 @@ public class AuthDataServiceTests : IDisposable
{
using (var db = CreateDbContext())
{
db.Users.Add(new AppUser { UserName = "test", DisplayName = "Test" });
db.Users.Add(new IdentityAppUser { UserName = "test", DisplayName = "Test" });
await db.SaveChangesAsync();
}
@@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Tests;
@@ -30,7 +31,7 @@ public class AuthMigrationCompatibilityTests(PostgreSqlContainerFixture postgres
var prior = db.Database.GetMigrations().Last(x => string.CompareOrdinal(x, "20261020002409") < 0);
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync(prior);
var user = new AppUser { Id = Guid.NewGuid(), Email = "existing@example.test", UserName = "existing", SecurityStamp = "preserved" };
var user = new IdentityAppUser { Id = Guid.NewGuid(), Email = "existing@example.test", UserName = "existing", SecurityStamp = "preserved" };
db.Users.Add(user);
await db.SaveChangesAsync();
await migrator.MigrateAsync();
@@ -1,5 +1,5 @@
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
@@ -8,36 +8,37 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Infrastructure.Tests;
public class AuthSignInServiceTests
{
private static (SignInManager<AppUser> signInManager, ILoggerFactory loggerFactory) CreateSignInManager()
private static (SignInManager<IdentityAppUser> signInManager, ILoggerFactory loggerFactory) CreateSignInManager()
{
var userManager = Substitute.For<UserManager<AppUser>>(
Substitute.For<IUserStore<AppUser>>(),
var userManager = Substitute.For<UserManager<IdentityAppUser>>(
Substitute.For<IUserStore<IdentityAppUser>>(),
Substitute.For<IOptions<IdentityOptions>>(),
Substitute.For<IPasswordHasher<AppUser>>(),
Array.Empty<IUserValidator<AppUser>>(),
Array.Empty<IPasswordValidator<AppUser>>(),
Substitute.For<IPasswordHasher<IdentityAppUser>>(),
Array.Empty<IUserValidator<IdentityAppUser>>(),
Array.Empty<IPasswordValidator<IdentityAppUser>>(),
Substitute.For<ILookupNormalizer>(),
Substitute.For<IdentityErrorDescriber>(),
Substitute.For<IServiceProvider>(),
Substitute.For<ILogger<UserManager<AppUser>>>());
Substitute.For<ILogger<UserManager<IdentityAppUser>>>());
var loggerFactory = Substitute.For<ILoggerFactory>();
var logger = Substitute.For<ILogger<SignInManager<AppUser>>>();
var logger = Substitute.For<ILogger<SignInManager<IdentityAppUser>>>();
loggerFactory.CreateLogger(Arg.Any<string>()).Returns(logger);
var signInManager = Substitute.For<SignInManager<AppUser>>(
var signInManager = Substitute.For<SignInManager<IdentityAppUser>>(
userManager,
Substitute.For<IHttpContextAccessor>(),
Substitute.For<IUserClaimsPrincipalFactory<AppUser>>(),
Substitute.For<IUserClaimsPrincipalFactory<IdentityAppUser>>(),
Substitute.For<IOptions<IdentityOptions>>(),
logger,
Substitute.For<IAuthenticationSchemeProvider>(),
Substitute.For<IUserConfirmation<AppUser>>());
Substitute.For<IUserConfirmation<IdentityAppUser>>());
return (signInManager, loggerFactory);
}
@@ -46,8 +47,10 @@ public class AuthSignInServiceTests
public async Task PasswordSignInAsync_Success_ReturnsSuccess()
{
var (signInManager, _) = CreateSignInManager();
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
signInManager.CheckPasswordSignInAsync(user, "password", false)
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
var identityUser = new IdentityAppUser { Id = user.Id, UserName = user.UserName, DisplayName = user.DisplayName };
signInManager.UserManager.FindByIdAsync(user.Id.ToString()).Returns(identityUser);
signInManager.CheckPasswordSignInAsync(identityUser, "password", false)
.Returns(SignInResult.Success);
var service = new AuthSignInService(signInManager);
@@ -60,8 +63,10 @@ public class AuthSignInServiceTests
public async Task PasswordSignInAsync_Failed_ReturnsFailed()
{
var (signInManager, _) = CreateSignInManager();
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
signInManager.CheckPasswordSignInAsync(user, "wrong", false)
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
var identityUser = new IdentityAppUser { Id = user.Id, UserName = user.UserName, DisplayName = user.DisplayName };
signInManager.UserManager.FindByIdAsync(user.Id.ToString()).Returns(identityUser);
signInManager.CheckPasswordSignInAsync(identityUser, "wrong", false)
.Returns(SignInResult.Failed);
var service = new AuthSignInService(signInManager);
@@ -74,8 +79,10 @@ public class AuthSignInServiceTests
public async Task PasswordSignInAsync_LockedOut_ReturnsLockedOut()
{
var (signInManager, _) = CreateSignInManager();
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
signInManager.CheckPasswordSignInAsync(user, "password", true)
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
var identityUser = new IdentityAppUser { Id = user.Id, UserName = user.UserName, DisplayName = user.DisplayName };
signInManager.UserManager.FindByIdAsync(user.Id.ToString()).Returns(identityUser);
signInManager.CheckPasswordSignInAsync(identityUser, "password", true)
.Returns(SignInResult.LockedOut);
var service = new AuthSignInService(signInManager);
@@ -88,8 +95,10 @@ public class AuthSignInServiceTests
public async Task PasswordSignInAsync_RequiresTwoFactor_ReturnsRequiresTwoFactor()
{
var (signInManager, _) = CreateSignInManager();
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
signInManager.CheckPasswordSignInAsync(user, "password", false)
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
var identityUser = new IdentityAppUser { Id = user.Id, UserName = user.UserName, DisplayName = user.DisplayName };
signInManager.UserManager.FindByIdAsync(user.Id.ToString()).Returns(identityUser);
signInManager.CheckPasswordSignInAsync(identityUser, "password", false)
.Returns(SignInResult.TwoFactorRequired);
var service = new AuthSignInService(signInManager);
@@ -113,28 +122,32 @@ public class AuthSignInServiceTests
public async Task PasswordSignInAsync_PassesLockoutOnFailure()
{
var (signInManager, _) = CreateSignInManager();
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
signInManager.CheckPasswordSignInAsync(user, "password", true)
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
var identityUser = new IdentityAppUser { Id = user.Id, UserName = user.UserName, DisplayName = user.DisplayName };
signInManager.UserManager.FindByIdAsync(user.Id.ToString()).Returns(identityUser);
signInManager.CheckPasswordSignInAsync(identityUser, "password", true)
.Returns(SignInResult.Failed);
var service = new AuthSignInService(signInManager);
await service.PasswordSignInAsync(user, "password", true);
await signInManager.Received(1).CheckPasswordSignInAsync(user, "password", true);
await signInManager.Received(1).CheckPasswordSignInAsync(identityUser, "password", true);
}
[Fact]
public async Task PasswordSignInAsync_DoesNotPersistCookie()
{
var (signInManager, _) = CreateSignInManager();
var user = new AppUser { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
signInManager.CheckPasswordSignInAsync(user, "password", false)
var user = new IdentityAccount { Id = Guid.NewGuid(), UserName = "test", DisplayName = "Test" };
var identityUser = new IdentityAppUser { Id = user.Id, UserName = user.UserName, DisplayName = user.DisplayName };
signInManager.UserManager.FindByIdAsync(user.Id.ToString()).Returns(identityUser);
signInManager.CheckPasswordSignInAsync(identityUser, "password", false)
.Returns(SignInResult.Success);
var service = new AuthSignInService(signInManager);
await service.PasswordSignInAsync(user, "password", false);
await signInManager.Received(1).CheckPasswordSignInAsync(user, "password", false);
await signInManager.DidNotReceiveWithAnyArgs().PasswordSignInAsync((AppUser)null!, null!, false, false);
await signInManager.Received(1).CheckPasswordSignInAsync(identityUser, "password", false);
await signInManager.DidNotReceiveWithAnyArgs().PasswordSignInAsync((IdentityAppUser)null!, null!, false, false);
}
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more