feat(auth): add structured logging throughout auth module

Add ILogger<AuthService> with log events at every step:
register, login, 2FA, refresh token, password change,
logout, admin registration. All error paths now log
the exact failure reason (validation, Identity errors,
public registration disabled, etc.).

Previously all errors were silently swallowed by the
HeimdallApiClient returning null on non-success responses.
This commit is contained in:
Arnaud Dartois committed 2026-07-20 20:16:58 +00:00
1 parent 8ac088de38
commit 81da09c110
1 file changed
+110 -10
@@ -10,6 +10,7 @@ using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
@@ -25,29 +26,40 @@ public class AuthService : IAuthService
private readonly SignInManager<AppUser> _signInManager;
private readonly IJwtService _jwtService;
private readonly AppDbContext _db;
private readonly ILogger<AuthService> _logger;
public AuthService(
UserManager<AppUser> userManager,
SignInManager<AppUser> signInManager,
IJwtService jwtService,
AppDbContext db)
AppDbContext db,
ILogger<AuthService> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_jwtService = jwtService;
_db = db;
_logger = logger;
}
public async Task<ServiceResult<AuthResponse>> RegisterAsync(RegisterRequest request, CancellationToken ct)
{
_logger.LogInformation("Register attempt: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
var existingUser = await _userManager.FindByEmailAsync(request.Email);
if (existingUser is not null)
{
_logger.LogWarning("Register: Email={Email} already registered", request.Email);
return ServiceResult<AuthResponse>.Conflict("Email already registered");
}
// ── First user ever → auto-admin ─────────────────────────────────
var anyUsers = await _db.Users.AnyAsync(ct);
_logger.LogDebug("Register: anyUsers={AnyUsers}", anyUsers);
if (!anyUsers)
{
_logger.LogInformation("Register: First user — creating admin Email={Email}", request.Email);
var firstUser = new AppUser
{
UserName = request.Email,
@@ -57,22 +69,35 @@ public class AuthService : IAuthService
var createResult = await _userManager.CreateAsync(firstUser, request.Password);
if (!createResult.Succeeded)
return ServiceResult<AuthResponse>.Failure(
string.Join(", ", createResult.Errors.Select(e => e.Description)));
{
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
_logger.LogError("Register: First user creation failed: {Errors}", errors);
return ServiceResult<AuthResponse>.Failure(errors);
}
await _userManager.AddToRoleAsync(firstUser, AppRoles.Admin);
_logger.LogInformation("Register: First user created and granted Admin role Email={Email}", request.Email);
return await GenerateAuthResponseAsync(firstUser, ct);
}
// ── Public registration enabled? (disabled by default) ────────────
_logger.LogDebug("Register: checking PublicRegistrationEnabled setting");
var publicRegistrationSetting = await _db.AppSettings
.FirstOrDefaultAsync(s => s.Key == AuthSettings.PublicRegistrationEnabled, ct);
if (publicRegistrationSetting is null)
_logger.LogDebug("Register: PublicRegistrationEnabled not set — registration allowed");
else
_logger.LogDebug("Register: PublicRegistrationEnabled={Value}", publicRegistrationSetting.Value);
if (publicRegistrationSetting is not null &&
!string.Equals(publicRegistrationSetting.Value, "true", StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning("Register: Public registration disabled (setting={Value})", publicRegistrationSetting.Value);
return ServiceResult<AuthResponse>.Failure("Public registration is disabled. Contact an administrator.", 403);
}
// ── Create the user ──────────────────────────────────────────────
_logger.LogInformation("Register: Creating user Email={Email}", request.Email);
var user = new AppUser
{
UserName = request.Email,
@@ -82,31 +107,52 @@ public class AuthService : IAuthService
var result = await _userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
return ServiceResult<AuthResponse>.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
_logger.LogError("Register: User creation failed: {Errors}", errors);
return ServiceResult<AuthResponse>.Failure(errors);
}
_logger.LogDebug("Register: Assigning Viewer role to Email={Email}", request.Email);
await _userManager.AddToRoleAsync(user, AppRoles.Viewer);
_logger.LogInformation("Register: User created successfully Email={Email}", request.Email);
return await GenerateAuthResponseAsync(user, ct);
}
public async Task<ServiceResult<AuthResponse>> LoginAsync(LoginRequest request, CancellationToken ct)
{
_logger.LogInformation("Login attempt: Email={Email}", request.Email);
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
_logger.LogWarning("Login: User not found Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
if (await _userManager.IsLockedOutAsync(user))
{
_logger.LogWarning("Login: Account locked Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
}
if (await _userManager.GetTwoFactorEnabledAsync(user))
{
_logger.LogDebug("Login: 2FA required Email={Email}", request.Email);
var signIn = await _signInManager.PasswordSignInAsync(user, request.Password, false, true);
if (signIn.IsLockedOut)
{
_logger.LogWarning("Login: Account locked after 2FA attempt Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
}
if (!signIn.Succeeded)
{
_logger.LogWarning("Login: 2FA failed Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
_logger.LogInformation("Login: 2FA passed Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Success(new AuthResponse(
string.Empty, string.Empty, DateTime.UtcNow, true,
await MapUserInfoAsync(user)));
@@ -114,23 +160,36 @@ public class AuthService : IAuthService
var result = await _signInManager.PasswordSignInAsync(user, request.Password, false, true);
if (!result.Succeeded)
{
_logger.LogWarning("Login: Password mismatch Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
_logger.LogInformation("Login: Success Email={Email}", request.Email);
return await GenerateAuthResponseAsync(user, ct);
}
public async Task<ServiceResult<AuthResponse>> Verify2faAsync(Verify2faRequest request, CancellationToken ct)
{
_logger.LogDebug("Verify2fa: Email={Email}", request.Email);
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
_logger.LogWarning("Verify2fa: User not found Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid request");
}
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
if (!isValid)
{
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
}
_logger.LogInformation("Verify2fa: Success Email={Email}", request.Email);
return await GenerateAuthResponseAsync(user, ct);
}
@@ -138,55 +197,91 @@ public class AuthService : IAuthService
{
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken))).ToLowerInvariant();
if (_revokedTokens.ContainsKey(tokenHash))
{
_logger.LogWarning("RefreshToken: Token revoked hash={HashPrefix}", tokenHash[..8]);
return ServiceResult<AuthResponse>.Unauthorized("Refresh token has been revoked");
}
var principal = _jwtService.ValidateRefreshToken(refreshToken);
if (principal is null)
{
_logger.LogWarning("RefreshToken: Invalid or expired token");
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired refresh token");
}
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId is null)
{
_logger.LogWarning("RefreshToken: Token missing NameIdentifier");
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
}
var user = await _userManager.FindByIdAsync(userId);
if (user is null)
{
_logger.LogWarning("RefreshToken: User not found UserId={UserId}", userId);
return ServiceResult<AuthResponse>.Unauthorized("User not found");
}
_logger.LogInformation("RefreshToken: Success UserId={UserId}", userId);
return await GenerateAuthResponseAsync(user, ct);
}
public async Task<ServiceResult> Enable2faAsync(Guid userId, CancellationToken ct)
{
_logger.LogDebug("Enable2fa: UserId={UserId}", userId);
var user = await _userManager.FindByIdAsync(userId.ToString());
if (user is null)
{
_logger.LogWarning("Enable2fa: User not found UserId={UserId}", userId);
return ServiceResult.NotFound("User not found");
}
var result = await _userManager.SetTwoFactorEnabledAsync(user, true);
if (!result.Succeeded)
{
_logger.LogError("Enable2fa: Failed UserId={UserId}", userId);
return ServiceResult.Failure("Failed to enable 2FA");
}
_logger.LogInformation("Enable2fa: Enabled UserId={UserId}", userId);
return ServiceResult.Success();
}
public async Task<ServiceResult> ChangePasswordAsync(Guid userId, string currentPassword, string newPassword, CancellationToken ct)
{
_logger.LogDebug("ChangePassword: UserId={UserId}", userId);
var user = await _userManager.FindByIdAsync(userId.ToString());
if (user is null)
{
_logger.LogWarning("ChangePassword: User not found UserId={UserId}", userId);
return ServiceResult.NotFound("User not found");
}
var result = await _userManager.ChangePasswordAsync(user, currentPassword, newPassword);
if (!result.Succeeded)
return ServiceResult.Failure(
string.Join(", ", result.Errors.Select(e => e.Description)));
{
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
_logger.LogError("ChangePassword: Failed UserId={UserId}: {Errors}", userId, errors);
return ServiceResult.Failure(errors);
}
_logger.LogInformation("ChangePassword: Success UserId={UserId}", userId);
return ServiceResult.Success();
}
public async Task<ServiceResult<AuthResponse>> RegisterAdminAsync(RegisterRequest request, CancellationToken ct)
{
_logger.LogInformation("RegisterAdmin: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
var existing = await _userManager.FindByEmailAsync(request.Email);
if (existing is not null)
{
_logger.LogWarning("RegisterAdmin: Already exists Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Conflict("Email already registered");
}
var user = new AppUser
{
@@ -197,22 +292,27 @@ public class AuthService : IAuthService
var createResult = await _userManager.CreateAsync(user, request.Password);
if (!createResult.Succeeded)
return ServiceResult<AuthResponse>.Failure(
string.Join(", ", createResult.Errors.Select(e => e.Description)));
{
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
_logger.LogError("RegisterAdmin: Creation failed Email={Email}: {Errors}", request.Email, errors);
return ServiceResult<AuthResponse>.Failure(errors);
}
await _userManager.AddToRoleAsync(user, AppRoles.Admin);
_logger.LogInformation("RegisterAdmin: Created and granted Admin role Email={Email}", request.Email);
return await GenerateAuthResponseAsync(user, ct);
}
public async Task LogoutAsync(Guid userId, string refreshToken, CancellationToken ct)
{
_logger.LogInformation("Logout: UserId={UserId}", userId);
if (!string.IsNullOrEmpty(refreshToken))
{
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken))).ToLowerInvariant();
_revokedTokens.TryAdd(tokenHash, 0);
// Audit log
_db.AuditLogs.Add(new AuditLog(userId, "User.Logout", "User", userId.ToString()));
await _db.SaveChangesWithRetryAsync(ct: ct);
}