feat(auth): codes de récupération 2FA — 10 codes hashés à l'enrôlement, usage unique au login (Fixes #12)
This commit is contained in:
1 parent
9e64b03f31
commit
59a864bdfc
16 files changed
+2553
-9
No files matched your search
@@ -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<Disable2faCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Disable2faHandler> _logger;
|
||||
|
||||
public Disable2faHandler(UserManager<AppUser> userManager, ILogger<Disable2faHandler> logger)
|
||||
public Disable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Disable2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -35,6 +38,17 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
|
||||
return ServiceResult.Failure("Failed to disable 2FA");
|
||||
}
|
||||
|
||||
// Purger les codes de récupération — ils ne sont plus valables
|
||||
var codes = await _db.UserRecoveryCodes
|
||||
.Where(r => 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();
|
||||
}
|
||||
|
||||
@@ -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<Enable2faCommand, ServiceResult<Enable2faResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Enable2faHandler> _logger;
|
||||
|
||||
public Enable2faHandler(UserManager<AppUser> userManager, ILogger<Enable2faHandler> logger)
|
||||
public Enable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -46,8 +50,16 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
|
||||
return ServiceResult<Enable2faResponse>.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<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri));
|
||||
_logger.LogInformation("Enable2fa: Enabled UserId={UserId} with {Count} recovery codes", request.UserId, recoveryCodes.Count);
|
||||
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri, recoveryCodes, recoveryCodes.Count));
|
||||
}
|
||||
}
|
||||
@@ -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<Verify2faCommand, ServiceResult<
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Verify2faHandler> _logger;
|
||||
|
||||
public Verify2faHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IApplicationDbContext db,
|
||||
ILogger<Verify2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -43,11 +48,35 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
|
||||
|
||||
if (!isValid)
|
||||
{
|
||||
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.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<AuthResponse>.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<bool> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Heimdall.Application.Auth.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Generates and hashes 2FA recovery codes.
|
||||
/// Codes are generated in a human-friendly grouped format and stored as SHA-256 hashes.
|
||||
/// </summary>
|
||||
public static class RecoveryCodeService
|
||||
{
|
||||
private const int CodeLength = 5;
|
||||
private const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no I, O, 0, 1 to avoid confusion
|
||||
|
||||
/// <summary>Generate <paramref name="count"/> recovery codes in plain text (shown once to the user).</summary>
|
||||
public static IReadOnlyList<string> Generate(int count = 10)
|
||||
{
|
||||
var codes = new List<string>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
codes.Add(GenerateSingle());
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/// <summary>SHA-256 hex hash of a recovery code (what is stored in the database).</summary>
|
||||
public static string Hash(string code)
|
||||
{
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(code));
|
||||
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static string GenerateSingle()
|
||||
{
|
||||
Span<char> 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);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ public interface IApplicationDbContext
|
||||
DbSet<Site> Sites { get; }
|
||||
DbSet<SiteCredential> SiteCredentials { get; }
|
||||
DbSet<UserGroup> UserGroups { get; }
|
||||
DbSet<UserRecoveryCode> UserRecoveryCodes { get; }
|
||||
DbSet<UserSite> UserSites { get; }
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default);
|
||||
|
||||
@@ -43,7 +43,9 @@ public record LogoutRequest(string RefreshToken);
|
||||
|
||||
public record Enable2faResponse(
|
||||
string SharedKey,
|
||||
string QrCodeUri);
|
||||
string QrCodeUri,
|
||||
IReadOnlyList<string>? RecoveryCodes = null,
|
||||
int RecoveryCodesRemaining = 0);
|
||||
|
||||
public record ConfirmEmailRequest(string UserId, string Token);
|
||||
public record ForgotPasswordRequest(string Email);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using Heimdall.Domain.Primitives;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class UserRecoveryCode : Entity<Guid>
|
||||
{
|
||||
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;
|
||||
}
|
||||
@@ -57,6 +57,9 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
public DbSet<Person> Persons => Set<Person>();
|
||||
public DbSet<KnownFace> KnownFaces => Set<KnownFace>();
|
||||
|
||||
// 2FA recovery codes (stored hashed)
|
||||
public DbSet<UserRecoveryCode> UserRecoveryCodes => Set<UserRecoveryCode>();
|
||||
|
||||
public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default)
|
||||
{
|
||||
await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -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<UserRecoveryCode>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<UserRecoveryCode> 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);
|
||||
}
|
||||
}
|
||||
+1914
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddUserRecoveryCodes : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "user_recovery_codes",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
CodeHash = table.Column<string>(type: "character varying(64)", unicode: false, maxLength: 64, nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UsedAt = table.Column<DateTime>(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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "user_recovery_codes");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1456,6 +1456,39 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("user_notification_configs", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("CodeHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<DateTime?>("UsedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("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<Guid>("UserId")
|
||||
|
||||
@@ -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)
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">2FA</MudText>
|
||||
<MudText Typo="Typo.body1" Class="mb-3">
|
||||
<MudText Typo="Typo.body1" Class="mb-1">
|
||||
<MudIcon Icon="@(_profile.TwoFactorEnabled ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
|
||||
Color="@(_profile.TwoFactorEnabled ? Color.Success : Color.Default)" Size="Size.Small" />
|
||||
@(_profile.TwoFactorEnabled ? "Activé" : "Désactivé")
|
||||
</MudText>
|
||||
@if (_profile.TwoFactorEnabled)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" Class="mt-1"
|
||||
OnClick="Disable2fa" Disabled="@_toggling2fa">
|
||||
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Désactiver la 2FA
|
||||
</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small" Class="mt-1"
|
||||
OnClick="Enable2fa" Disabled="@_toggling2fa">
|
||||
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Activer la 2FA
|
||||
</MudButton>
|
||||
}
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Rôles</MudText>
|
||||
@@ -194,6 +211,66 @@ else if (_profile is not null)
|
||||
</MudPaper>
|
||||
}
|
||||
|
||||
@* ─── Dialog d'enrôlement 2FA (QR + codes de récupération) ─── *@
|
||||
<MudOverlay Visible="@_show2faDialog" OnClick="@(() => _show2faDialog = false)" />
|
||||
<MudDialog @bind-Visible="_show2faDialog" Options="new DialogOptions { MaxWidth = MaxWidth.Medium, FullWidth = true }">
|
||||
<TitleContent>
|
||||
<MudText Typo="Typo.h6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Security" Class="mr-1" Size="Size.Small" />
|
||||
Activer la double authentification (2FA)
|
||||
</MudText>
|
||||
</TitleContent>
|
||||
<DialogContent>
|
||||
@if (_2faError is not null)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_2faError</MudAlert>
|
||||
}
|
||||
else if (_2faSetup is not null)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-4">
|
||||
<MudText Typo="Typo.body2" Class="mb-1">
|
||||
Scannez le code QR avec votre application d'authentification (Google Authenticator, Authy…)
|
||||
ou saisissez la clé manuellement.
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Class="mb-1">
|
||||
<strong>Clé :</strong> <code>@_2faSetup.SharedKey</code>
|
||||
</MudText>
|
||||
@if (!string.IsNullOrEmpty(_2faSetup.QrCodeUri))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">
|
||||
Lien de configuration : <a href="@_2faSetup.QrCodeUri" target="_blank">ouvrir dans l'app</a>
|
||||
</MudText>
|
||||
}
|
||||
</MudAlert>
|
||||
|
||||
@if (_2faSetup.RecoveryCodes is { Count: > 0 })
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mb-2">
|
||||
<MudText Typo="Typo.body2" Class="mb-1">
|
||||
<strong>Codes de récupération</strong> — 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.
|
||||
</MudText>
|
||||
</MudAlert>
|
||||
<MudPaper Elevation="0" Class="pa-3 mb-4" Style="border: 1px dashed #f0ad4e; border-radius: 8px;">
|
||||
<div class="d-flex flex-wrap">
|
||||
@foreach (var rc in _2faSetup.RecoveryCodes)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="d-inline mr-4 mb-2" Style="font-family: monospace;">
|
||||
@rc
|
||||
</MudText>
|
||||
}
|
||||
</div>
|
||||
</MudPaper>
|
||||
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label="J'ai sauvegardé mes codes de récupération" Class="mb-2" />
|
||||
}
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _show2faDialog = false)">Fermer</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@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))
|
||||
|
||||
@@ -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<Enable2faResponse?> Enable2faAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/auth/2fa/enable", null);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<Enable2faResponse>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> Disable2faAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/auth/2fa/disable", null);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the last successful auth response for use by the token refresh handler.
|
||||
/// </summary>
|
||||
|
||||
@@ -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<AppUser> _userManager;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Enable2faHandler> _logger;
|
||||
private readonly Enable2faHandler _handler;
|
||||
private readonly InMemoryDbSet<UserRecoveryCode> _recoveryCodes;
|
||||
|
||||
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!);
|
||||
_db = Substitute.For<IApplicationDbContext>();
|
||||
_logger = Substitute.For<ILogger<Enable2faHandler>>();
|
||||
_recoveryCodes = (InMemoryDbSet<UserRecoveryCode>)MockDbSetHelper.CreateFor<UserRecoveryCode>();
|
||||
_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<string>()).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);
|
||||
}
|
||||
}
|
||||
@@ -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<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Verify2faHandler> _logger;
|
||||
private readonly Verify2faHandler _handler;
|
||||
private readonly InMemoryDbSet<UserRecoveryCode> _recoveryCodes;
|
||||
|
||||
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!);
|
||||
_jwtService = Substitute.For<IJwtService>();
|
||||
_rolePermissionService = Substitute.For<IRolePermissionService>();
|
||||
_db = Substitute.For<IApplicationDbContext>();
|
||||
_logger = Substitute.For<ILogger<Verify2faHandler>>();
|
||||
_recoveryCodes = (InMemoryDbSet<UserRecoveryCode>)MockDbSetHelper.CreateFor<UserRecoveryCode>();
|
||||
_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<IList<string>>(), Arg.Any<IList<string>>())
|
||||
.Returns(("access-token", DateTime.UtcNow.AddHours(1)));
|
||||
_jwtService.GenerateRefreshToken(user).Returns(("refresh-token", DateTime.UtcNow.AddDays(7)));
|
||||
_rolePermissionService.GetPermissionsForRoles(Arg.Any<IList<string>>()).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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user