diff --git a/src/Heimdall.Application/Auth/Commands/Disable2fa/Disable2faHandler.cs b/src/Heimdall.Application/Auth/Commands/Disable2fa/Disable2faHandler.cs index 211a273..f096647 100644 --- a/src/Heimdall.Application/Auth/Commands/Disable2fa/Disable2faHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Disable2fa/Disable2faHandler.cs @@ -2,6 +2,7 @@ using Heimdall.Application.Common; using Heimdall.Domain.Entities; using MediatR; using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Heimdall.Application.Auth.Commands.Disable2fa; @@ -9,11 +10,13 @@ namespace Heimdall.Application.Auth.Commands.Disable2fa; public class Disable2faHandler : IRequestHandler { private readonly UserManager _userManager; + private readonly IApplicationDbContext _db; private readonly ILogger _logger; - public Disable2faHandler(UserManager userManager, ILogger logger) + public Disable2faHandler(UserManager userManager, IApplicationDbContext db, ILogger logger) { _userManager = userManager; + _db = db; _logger = logger; } @@ -35,6 +38,17 @@ public class Disable2faHandler : IRequestHandler r.UserId == request.UserId) + .ToListAsync(ct).ConfigureAwait(false); + if (codes.Count > 0) + { + _db.UserRecoveryCodes.RemoveRange(codes); + await _db.SaveChangesAsync(ct).ConfigureAwait(false); + _logger.LogInformation("Disable2fa: Purged {Count} recovery codes UserId={UserId}", codes.Count, request.UserId); + } + _logger.LogInformation("Disable2fa: Disabled UserId={UserId}", request.UserId); return ServiceResult.Success(); } diff --git a/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs b/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs index 798bcca..208a9b6 100644 --- a/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Enable2fa/Enable2faHandler.cs @@ -1,8 +1,10 @@ -using Heimdall.Application.DTOs; +using Heimdall.Application.Auth.Services; 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; namespace Heimdall.Application.Auth.Commands.Enable2fa; @@ -10,11 +12,13 @@ namespace Heimdall.Application.Auth.Commands.Enable2fa; public class Enable2faHandler : IRequestHandler> { private readonly UserManager _userManager; + private readonly IApplicationDbContext _db; private readonly ILogger _logger; - public Enable2faHandler(UserManager userManager, ILogger logger) + public Enable2faHandler(UserManager userManager, IApplicationDbContext db, ILogger logger) { _userManager = userManager; + _db = db; _logger = logger; } @@ -46,8 +50,16 @@ public class Enable2faHandler : IRequestHandler.Failure("Failed to generate 2FA key"); } + // Générer 10 codes de récupération (P0 spec 4.3) — affichés UNE seule fois, stockés hashés + var recoveryCodes = RecoveryCodeService.Generate(10); + foreach (var code in recoveryCodes) + { + _db.UserRecoveryCodes.Add(new UserRecoveryCode(request.UserId, RecoveryCodeService.Hash(code))); + } + await _db.SaveChangesAsync(ct).ConfigureAwait(false); + var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30"; - _logger.LogInformation("Enable2fa: Enabled UserId={UserId}", request.UserId); - return ServiceResult.Success(new Enable2faResponse(key, qrCodeUri)); + _logger.LogInformation("Enable2fa: Enabled UserId={UserId} with {Count} recovery codes", request.UserId, recoveryCodes.Count); + return ServiceResult.Success(new Enable2faResponse(key, qrCodeUri, recoveryCodes, recoveryCodes.Count)); } } diff --git a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs index 62de911..6dfc8f4 100644 --- a/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs +++ b/src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs @@ -1,9 +1,11 @@ +using Heimdall.Application.Auth.Services; using Heimdall.Application.Common; 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; namespace Heimdall.Application.Auth.Commands.Verify2fa; @@ -13,17 +15,20 @@ public class Verify2faHandler : IRequestHandler _userManager; private readonly IJwtService _jwtService; private readonly IRolePermissionService _rolePermissionService; + private readonly IApplicationDbContext _db; private readonly ILogger _logger; public Verify2faHandler( UserManager userManager, IJwtService jwtService, IRolePermissionService rolePermissionService, + IApplicationDbContext db, ILogger logger) { _userManager = userManager; _jwtService = jwtService; _rolePermissionService = rolePermissionService; + _db = db; _logger = logger; } @@ -43,11 +48,35 @@ public class Verify2faHandler : IRequestHandler.Unauthorized("Invalid 2FA code"); + // TOTP invalide → tenter un code de récupération (usage unique) + var redeemed = await TryRedeemRecoveryCodeAsync(user, request.Code.Trim(), ct).ConfigureAwait(false); + if (!redeemed) + { + _logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email); + return ServiceResult.Unauthorized("Invalid 2FA code"); + } + _logger.LogInformation("Verify2fa: Recovery code redeemed Email={Email}", request.Email); } _logger.LogInformation("Verify2fa: Success Email={Email}", request.Email); return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false); } + + private async Task TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(code)) + return false; + + var codeHash = RecoveryCodeService.Hash(code); + var match = await _db.UserRecoveryCodes + .FirstOrDefaultAsync(r => r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null, ct) + .ConfigureAwait(false); + + if (match is null) + return false; + + match.MarkUsed(); + await _db.SaveChangesAsync(ct).ConfigureAwait(false); + return true; + } } diff --git a/src/Heimdall.Application/Auth/Services/RecoveryCodeService.cs b/src/Heimdall.Application/Auth/Services/RecoveryCodeService.cs new file mode 100644 index 0000000..4b61d36 --- /dev/null +++ b/src/Heimdall.Application/Auth/Services/RecoveryCodeService.cs @@ -0,0 +1,43 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Heimdall.Application.Auth.Services; + +/// +/// Generates and hashes 2FA recovery codes. +/// Codes are generated in a human-friendly grouped format and stored as SHA-256 hashes. +/// +public static class RecoveryCodeService +{ + private const int CodeLength = 5; + private const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no I, O, 0, 1 to avoid confusion + + /// Generate recovery codes in plain text (shown once to the user). + public static IReadOnlyList Generate(int count = 10) + { + var codes = new List(count); + for (var i = 0; i < count; i++) + { + codes.Add(GenerateSingle()); + } + return codes; + } + + /// SHA-256 hex hash of a recovery code (what is stored in the database). + public static string Hash(string code) + { + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(code)); + return Convert.ToHexString(bytes).ToLowerInvariant(); + } + + private static string GenerateSingle() + { + Span chars = stackalloc char[CodeLength]; + var bytes = RandomNumberGenerator.GetBytes(CodeLength); + for (var i = 0; i < CodeLength; i++) + { + chars[i] = Alphabet[bytes[i] % Alphabet.Length]; + } + return new string(chars); + } +} diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 02b9d7d..9a9bca3 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -31,6 +31,7 @@ public interface IApplicationDbContext DbSet Sites { get; } DbSet SiteCredentials { get; } DbSet UserGroups { get; } + DbSet UserRecoveryCodes { get; } DbSet UserSites { get; } Task SaveChangesAsync(CancellationToken cancellationToken); Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default); diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs index f130b4c..6351198 100644 --- a/src/Heimdall.Application/DTOs/AuthDto.cs +++ b/src/Heimdall.Application/DTOs/AuthDto.cs @@ -43,7 +43,9 @@ public record LogoutRequest(string RefreshToken); public record Enable2faResponse( string SharedKey, - string QrCodeUri); + string QrCodeUri, + IReadOnlyList? RecoveryCodes = null, + int RecoveryCodesRemaining = 0); public record ConfirmEmailRequest(string UserId, string Token); public record ForgotPasswordRequest(string Email); diff --git a/src/Heimdall.Domain/Entities/UserRecoveryCode.cs b/src/Heimdall.Domain/Entities/UserRecoveryCode.cs new file mode 100644 index 0000000..9a01de1 --- /dev/null +++ b/src/Heimdall.Domain/Entities/UserRecoveryCode.cs @@ -0,0 +1,28 @@ +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// A single-use 2FA recovery code, stored hashed (SHA-256) — never in plain text. +/// 10 codes are generated at 2FA enrollment and shown to the user exactly once. +/// +public class UserRecoveryCode : Entity +{ + public Guid UserId { get; private set; } + public string CodeHash { get; private set; } = string.Empty; + public DateTime CreatedAt { get; private set; } = DateTime.UtcNow; + public DateTime? UsedAt { get; private set; } + + private UserRecoveryCode() { } // EF Core + + public UserRecoveryCode(Guid userId, string codeHash) + : base(Guid.NewGuid()) + { + UserId = userId; + CodeHash = codeHash; + } + + public bool IsUsed => UsedAt is not null; + + public void MarkUsed() => UsedAt = DateTime.UtcNow; +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 9386679..5615ff2 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -57,6 +57,9 @@ public class AppDbContext : IdentityDbContext, IApplicat public DbSet Persons => Set(); public DbSet KnownFaces => Set(); + // 2FA recovery codes (stored hashed) + public DbSet UserRecoveryCodes => Set(); + public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default) { await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/UserRecoveryCodeConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/UserRecoveryCodeConfiguration.cs new file mode 100644 index 0000000..028e082 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/UserRecoveryCodeConfiguration.cs @@ -0,0 +1,34 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class UserRecoveryCodeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("user_recovery_codes"); + + builder.HasKey(r => r.Id); + + builder.Property(r => r.CodeHash) + .HasMaxLength(64) + .IsRequired() + .IsUnicode(false); + + builder.Property(r => r.UserId) + .IsRequired(); + + builder.Property(r => r.CreatedAt) + .HasDefaultValueSql("NOW()"); + + builder.Property(r => r.UsedAt); + + // Indexes for lookup during login (single-use redemption) + builder.HasIndex(r => new { r.UserId, r.CodeHash }) + .IsUnique(); + + builder.HasIndex(r => r.UserId); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260811192914_AddUserRecoveryCodes.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260811192914_AddUserRecoveryCodes.Designer.cs new file mode 100644 index 0000000..b582b88 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260811192914_AddUserRecoveryCodes.Designer.cs @@ -0,0 +1,1914 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260811192914_AddUserRecoveryCodes")] + partial class AddUserRecoveryCodes + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("OccurredAt"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + 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"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260811192914_AddUserRecoveryCodes.cs b/src/Heimdall.Infrastructure/Migrations/20260811192914_AddUserRecoveryCodes.cs new file mode 100644 index 0000000..cb38e16 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260811192914_AddUserRecoveryCodes.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddUserRecoveryCodes : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "user_recovery_codes", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + CodeHash = table.Column(type: "character varying(64)", unicode: false, maxLength: 64, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UsedAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_user_recovery_codes", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_user_recovery_codes_UserId", + table: "user_recovery_codes", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_user_recovery_codes_UserId_CodeHash", + table: "user_recovery_codes", + columns: new[] { "UserId", "CodeHash" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "user_recovery_codes"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 390ccf5..0d308fb 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1456,6 +1456,39 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("user_notification_configs", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => { b.Property("UserId") diff --git a/src/Heimdall.Web/Components/Pages/Profile.razor b/src/Heimdall.Web/Components/Pages/Profile.razor index bebda9c..82556b7 100644 --- a/src/Heimdall.Web/Components/Pages/Profile.razor +++ b/src/Heimdall.Web/Components/Pages/Profile.razor @@ -1,6 +1,7 @@ @page "/profile" @attribute [Authorize] @layout MainLayout +@using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse @inject HeimdallApiClient Api @inject AuthState Auth @inject ISnackbar Snackbar @@ -88,11 +89,27 @@ else if (_profile is not null) 2FA - + @(_profile.TwoFactorEnabled ? "Activé" : "Désactivé") + @if (_profile.TwoFactorEnabled) + { + + @if (_toggling2fa) { } + Désactiver la 2FA + + } + else + { + + @if (_toggling2fa) { } + Activer la 2FA + + } Rôles @@ -194,6 +211,66 @@ else if (_profile is not null) } +@* ─── Dialog d'enrôlement 2FA (QR + codes de récupération) ─── *@ + + + + + + Activer la double authentification (2FA) + + + + @if (_2faError is not null) + { + @_2faError + } + else if (_2faSetup is not null) + { + + + Scannez le code QR avec votre application d'authentification (Google Authenticator, Authy…) + ou saisissez la clé manuellement. + + + Clé : @_2faSetup.SharedKey + + @if (!string.IsNullOrEmpty(_2faSetup.QrCodeUri)) + { + + Lien de configuration : ouvrir dans l'app + + } + + + @if (_2faSetup.RecoveryCodes is { Count: > 0 }) + { + + + Codes de récupération — conservez-les précieusement. + Ils permettent de vous connecter si vous perdez votre application d'authentification. + Chaque code ne peut être utilisé qu'une seule fois. + + + +
+ @foreach (var rc in _2faSetup.RecoveryCodes) + { + + @rc + + } +
+
+ + } + } +
+ + Fermer + +
+ @code { private UserItem? _profile; private bool _loading = true; @@ -213,6 +290,13 @@ else if (_profile is not null) private string _confirmPassword = ""; private string _passwordError = ""; + // Section 2FA + private bool _toggling2fa; + private bool _show2faDialog; + private Enable2faResponse? _2faSetup; + private string? _2faError; + private bool _recoveryCodesConfirmed; + protected override async Task OnInitializedAsync() { await LoadProfile(); @@ -273,6 +357,62 @@ else if (_profile is not null) // ─── Section 3: Changer le mot de passe ─────────────────────── + private async Task Enable2fa() + { + _toggling2fa = true; + _2faError = null; + _2faSetup = null; + _recoveryCodesConfirmed = false; + try + { + var setup = await Api.Enable2faAsync(); + if (setup is null) + { + _2faError = "Échec de l'activation de la 2FA. Réessayez."; + _show2faDialog = true; + return; + } + _2faSetup = setup; + _show2faDialog = true; + } + catch + { + _2faError = UiErrors.OperationFailed(); + _show2faDialog = true; + } + finally + { + _toggling2fa = false; + await LoadProfile(); + } + } + + private async Task Disable2fa() + { + _toggling2fa = true; + try + { + var ok = await Api.Disable2faAsync(); + if (ok) + { + Snackbar.Add("Double authentification désactivée", Severity.Success); + } + else + { + Snackbar.Add("Échec de la désactivation de la 2FA", Severity.Error); + } + } + catch + { + Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); + } + finally + { + _toggling2fa = false; + await LoadProfile(); + } + } + private async Task ChangePassword() { if (string.IsNullOrWhiteSpace(_currentPassword)) diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index d25b2b7..c227768 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -2,6 +2,7 @@ using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; +using Heimdall.Application.DTOs; namespace Heimdall.Web.Services; @@ -159,6 +160,21 @@ public class HeimdallApiClient return result; } + public async Task Enable2faAsync() + { + var client = CreateClient(); + var response = await client.PostAsync("api/auth/2fa/enable", null); + if (!response.IsSuccessStatusCode) return null; + return await response.Content.ReadFromJsonAsync(Json); + } + + public async Task Disable2faAsync() + { + var client = CreateClient(); + var response = await client.PostAsync("api/auth/2fa/disable", null); + return response.IsSuccessStatusCode; + } + /// /// Stores the last successful auth response for use by the token refresh handler. /// diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/Enable2faHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/Enable2faHandlerTests.cs new file mode 100644 index 0000000..5e38e2c --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/Enable2faHandlerTests.cs @@ -0,0 +1,106 @@ +using Heimdall.Application.Auth.Commands.Enable2fa; +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; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class Enable2faHandlerTests +{ + private readonly UserManager _userManager; + private readonly IApplicationDbContext _db; + private readonly ILogger _logger; + private readonly Enable2faHandler _handler; + private readonly InMemoryDbSet _recoveryCodes; + + public Enable2faHandlerTests() + { + var userStore = Substitute.For>(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _db = Substitute.For(); + _logger = Substitute.For>(); + _recoveryCodes = (InMemoryDbSet)MockDbSetHelper.CreateFor(); + _db.UserRecoveryCodes.Returns(_recoveryCodes); + _handler = new Enable2faHandler(_userManager, _db, _logger); + } + + [Fact] + public async Task Enable2fa_should_generate_10_recovery_codes_and_store_hashes() + { + var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" }; + _userManager.FindByIdAsync(user.Id.ToString()).Returns(user); + _userManager.SetTwoFactorEnabledAsync(user, true) + .Returns(IdentityResult.Success); + _userManager.ResetAuthenticatorKeyAsync(user).Returns(IdentityResult.Success); + _userManager.GetAuthenticatorKeyAsync(user).Returns("ABCDEF123456"); + + var result = await _handler.Handle(new Enable2faCommand(user.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data!.RecoveryCodes.ShouldNotBeNull(); + result.Data.RecoveryCodes!.Count.ShouldBe(10); + result.Data.RecoveryCodesRemaining.ShouldBe(10); + + // Stockage hashé : chaque hash en base ≠ code en clair, longueur SHA-256 hex (64) + _recoveryCodes.Count().ShouldBe(10); + foreach (var stored in _recoveryCodes) + { + stored.UserId.ShouldBe(user.Id); + stored.CodeHash.ShouldNotBeNull(); + stored.CodeHash.Length.ShouldBe(64); + result.Data.RecoveryCodes.ShouldNotContain(stored.CodeHash); + } + + // Les hash correspondent bien aux codes retournés + foreach (var code in result.Data.RecoveryCodes) + { + _recoveryCodes.ShouldContain(r => r.CodeHash == RecoveryCodeService.Hash(code)); + } + } + + [Fact] + public async Task Enable2fa_with_unknown_user_should_return_not_found() + { + _userManager.FindByIdAsync(Arg.Any()).Returns((AppUser?)null); + + var result = await _handler.Handle(new Enable2faCommand(Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + _recoveryCodes.Count().ShouldBe(0); + } + + [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); + _userManager.SetTwoFactorEnabledAsync(user, true) + .Returns(IdentityResult.Failed(new IdentityError { Description = "boom" })); + + var result = await _handler.Handle(new Enable2faCommand(user.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + _recoveryCodes.Count().ShouldBe(0); + } + + [Fact] + public async Task Enable2fa_generated_codes_are_unique() + { + var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", Email = "test@test.com" }; + _userManager.FindByIdAsync(user.Id.ToString()).Returns(user); + _userManager.SetTwoFactorEnabledAsync(user, true).Returns(IdentityResult.Success); + _userManager.ResetAuthenticatorKeyAsync(user).Returns(IdentityResult.Success); + _userManager.GetAuthenticatorKeyAsync(user).Returns("ABCDEF123456"); + + var result = await _handler.Handle(new Enable2faCommand(user.Id), CancellationToken.None); + + result.Data!.RecoveryCodes!.Distinct().Count().ShouldBe(10); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs new file mode 100644 index 0000000..9ef978a --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/Verify2faHandlerTests.cs @@ -0,0 +1,121 @@ +using Heimdall.Application.Auth.Commands.Verify2fa; +using Heimdall.Application.Auth.Services; +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; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class Verify2faHandlerTests +{ + private readonly UserManager _userManager; + private readonly IJwtService _jwtService; + private readonly IRolePermissionService _rolePermissionService; + private readonly IApplicationDbContext _db; + private readonly ILogger _logger; + private readonly Verify2faHandler _handler; + private readonly InMemoryDbSet _recoveryCodes; + + public Verify2faHandlerTests() + { + var userStore = Substitute.For>(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _jwtService = Substitute.For(); + _rolePermissionService = Substitute.For(); + _db = Substitute.For(); + _logger = Substitute.For>(); + _recoveryCodes = (InMemoryDbSet)MockDbSetHelper.CreateFor(); + _db.UserRecoveryCodes.Returns(_recoveryCodes); + _handler = new Verify2faHandler(_userManager, _jwtService, _rolePermissionService, _db, _logger); + } + + private AppUser SetupUser(string email) + { + var user = new AppUser { Id = Guid.NewGuid(), UserName = email, Email = email, DisplayName = "Test" }; + _userManager.FindByEmailAsync(email).Returns(user); + _userManager.GetRolesAsync(user).Returns(["Viewer"]); + _jwtService.GenerateAccessToken(user, Arg.Any>(), Arg.Any>()) + .Returns(("access-token", DateTime.UtcNow.AddHours(1))); + _jwtService.GenerateRefreshToken(user).Returns(("refresh-token", DateTime.UtcNow.AddDays(7))); + _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); + return user; + } + + [Fact] + public async Task Verify2fa_with_valid_totp_should_return_success() + { + var user = SetupUser("test@test.com"); + _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, "123456") + .Returns(true); + + var result = await _handler.Handle(new Verify2faCommand("test@test.com", "123456"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.AccessToken.ShouldBe("access-token"); + } + + [Fact] + public async Task Verify2fa_with_recovery_code_should_redeem_and_return_success() + { + var user = SetupUser("test@test.com"); + var plainCode = "ABC12"; + _recoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(plainCode))); + _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, plainCode) + .Returns(false); + + var result = await _handler.Handle(new Verify2faCommand("test@test.com", plainCode), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.AccessToken.ShouldBe("access-token"); + + // Usage unique : le code est marqué utilisé + var stored = _recoveryCodes.Single(); + stored.UsedAt.ShouldNotBeNull(); + } + + [Fact] + public async Task Verify2fa_with_invalid_code_should_return_unauthorized() + { + var user = SetupUser("test@test.com"); + _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, "000000") + .Returns(false); + + var result = await _handler.Handle(new Verify2faCommand("test@test.com", "000000"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Verify2fa_with_unknown_user_should_return_unauthorized() + { + _userManager.FindByEmailAsync("unknown@test.com").Returns((AppUser?)null); + + var result = await _handler.Handle(new Verify2faCommand("unknown@test.com", "123456"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Verify2fa_recovery_code_cannot_be_reused() + { + var user = SetupUser("test@test.com"); + var plainCode = "ABC12"; + var code = new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(plainCode)); + code.MarkUsed(); // déjà consommé + _recoveryCodes.Add(code); + _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, plainCode) + .Returns(false); + + var result = await _handler.Handle(new Verify2faCommand("test@test.com", plainCode), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } +}