2026-07-20 10:30:01 +00:00
|
|
|
using System.Security.Claims;
|
2026-07-22 19:54:55 +00:00
|
|
|
using Heimdall.Application.Auth.Commands.Register;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.Login;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.Verify2fa;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.RefreshToken;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.ChangePassword;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.RegisterAdmin;
|
2026-07-28 15:03:18 +00:00
|
|
|
using Heimdall.Application.Auth.Commands.ConfirmEmail;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.ForgotPassword;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.ResetPassword;
|
2026-07-22 19:54:55 +00:00
|
|
|
using Heimdall.Application.Auth.Commands.Enable2fa;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.Disable2fa;
|
|
|
|
|
using Heimdall.Application.Auth.Commands.Logout;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Heimdall.Application.Common;
|
|
|
|
|
using Heimdall.Application.DTOs;
|
|
|
|
|
using Heimdall.Infrastructure.Security;
|
2026-07-22 19:54:55 +00:00
|
|
|
using MediatR;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Api.Controllers;
|
|
|
|
|
|
|
|
|
|
[ApiController]
|
|
|
|
|
[Route("api/auth")]
|
|
|
|
|
[EnableRateLimiting("Auth")]
|
|
|
|
|
public class AuthController : ControllerBase
|
|
|
|
|
{
|
2026-07-22 19:54:55 +00:00
|
|
|
private readonly IMediator _mediator;
|
2026-07-24 18:25:33 +00:00
|
|
|
private readonly ILogger<AuthController> _logger;
|
2026-07-20 10:30:01 +00:00
|
|
|
|
2026-07-28 14:57:28 +00:00
|
|
|
public AuthController(IMediator mediator, ILogger<AuthController> logger)
|
2026-07-20 10:30:01 +00:00
|
|
|
{
|
2026-07-22 19:54:55 +00:00
|
|
|
_mediator = mediator;
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger = logger;
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Register a new user.</summary>
|
|
|
|
|
[AllowAnonymous]
|
|
|
|
|
[HttpPost("register")]
|
|
|
|
|
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("Register attempt for {Email}", request.Email);
|
2026-07-22 19:54:55 +00:00
|
|
|
var command = new RegisterCommand(request.Email, request.Password, request.DisplayName);
|
|
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("User registered successfully: {Email}", request.Email);
|
|
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("User registration failed for {Email}: {Error}", request.Email, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Authenticate a user.</summary>
|
|
|
|
|
[AllowAnonymous]
|
|
|
|
|
[HttpPost("login")]
|
|
|
|
|
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
|
|
|
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("Login attempt for {Email}", request.Email);
|
2026-07-22 19:54:55 +00:00
|
|
|
var command = new LoginCommand(request.Email, request.Password);
|
|
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Login successful for {Email}", request.Email);
|
|
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Verify a 2FA code.</summary>
|
|
|
|
|
[AllowAnonymous]
|
2026-07-28 14:37:52 +00:00
|
|
|
[EnableRateLimiting("TwoFactor")]
|
2026-07-20 10:30:01 +00:00
|
|
|
[HttpPost("2fa/verify")]
|
|
|
|
|
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
|
|
|
public async Task<IActionResult> Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("2FA verification attempt for {Email}", request.Email);
|
2026-07-22 19:54:55 +00:00
|
|
|
var command = new Verify2faCommand(request.Email, request.Code);
|
|
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("2FA verification successful for {Email}", request.Email);
|
|
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("2FA verification failed for {Email}: {Error}", request.Email, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Refresh an authentication token.</summary>
|
|
|
|
|
[AllowAnonymous]
|
|
|
|
|
[HttpPost("refresh")]
|
|
|
|
|
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
|
|
|
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogDebug("Token refresh attempt");
|
2026-07-22 19:54:55 +00:00
|
|
|
var result = await _mediator.Send(new RefreshTokenCommand(request.RefreshToken), ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogDebug("Token refresh successful");
|
|
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("Token refresh failed: {Error}", result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Change the current user's password.</summary>
|
2026-08-09 23:43:11 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
2026-07-20 10:30:01 +00:00
|
|
|
[HttpPost("change-password")]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
|
|
|
|
public async Task<IActionResult> ChangePassword(
|
|
|
|
|
[FromBody] ChangePasswordRequest request, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
|
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
2026-07-24 18:25:33 +00:00
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Change password failed: Invalid user identity");
|
2026-07-21 08:47:24 +00:00
|
|
|
return Unauthorized(new { error = "Invalid user identity" });
|
2026-07-24 18:25:33 +00:00
|
|
|
}
|
2026-07-20 10:30:01 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("Password change attempt for user {UserId}", userId);
|
2026-07-22 19:54:55 +00:00
|
|
|
var command = new ChangePasswordCommand(userId, request.CurrentPassword, request.NewPassword);
|
|
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Password changed successfully for user {UserId}", userId);
|
|
|
|
|
return Ok();
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("Password change failed for user {UserId}: {Error}", userId, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 14:57:28 +00:00
|
|
|
/// <summary>Register an admin user. Requires Admin role + feature flag auth.admin-registration.enabled.</summary>
|
2026-08-09 23:43:11 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = "AdminUsers")]
|
2026-07-20 10:30:01 +00:00
|
|
|
[HttpPost("register-admin")]
|
|
|
|
|
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
2026-07-28 14:57:28 +00:00
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status403Forbidden)]
|
2026-07-20 10:30:01 +00:00
|
|
|
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("RegisterAdmin attempt for {Email}", request.Email);
|
2026-07-22 19:54:55 +00:00
|
|
|
var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName);
|
|
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Admin user registered successfully: {Email}", request.Email);
|
|
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("Admin registration failed for {Email}: {Error}", request.Email, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 14:37:52 +00:00
|
|
|
/// <summary>Enable 2FA for the current user. Returns the shared key and QR code URI for setup.</summary>
|
2026-08-09 23:43:11 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
2026-07-21 08:57:53 +00:00
|
|
|
[HttpPost("2fa/enable")]
|
2026-07-28 14:37:52 +00:00
|
|
|
[ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)]
|
2026-07-21 08:57:53 +00:00
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> Enable2fa(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
|
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
2026-07-24 18:25:33 +00:00
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Enable2fa failed: Invalid user identity");
|
2026-07-21 08:57:53 +00:00
|
|
|
return Unauthorized(new { error = "Invalid user identity" });
|
2026-07-24 18:25:33 +00:00
|
|
|
}
|
2026-07-21 08:57:53 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("2FA enable attempt for user {UserId}", userId);
|
2026-07-22 19:54:55 +00:00
|
|
|
var result = await _mediator.Send(new Enable2faCommand(userId), ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("2FA enabled successfully for user {UserId}", userId);
|
2026-07-28 14:37:52 +00:00
|
|
|
return Ok(result.Data);
|
2026-07-24 18:25:33 +00:00
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("2FA enable failed for user {UserId}: {Error}", userId, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
2026-07-21 08:57:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Disable 2FA for the current user.</summary>
|
2026-08-09 23:43:11 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
2026-07-21 08:57:53 +00:00
|
|
|
[HttpPost("2fa/disable")]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> Disable2fa(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
|
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
2026-07-24 18:25:33 +00:00
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Disable2fa failed: Invalid user identity");
|
2026-07-21 08:57:53 +00:00
|
|
|
return Unauthorized(new { error = "Invalid user identity" });
|
2026-07-24 18:25:33 +00:00
|
|
|
}
|
2026-07-21 08:57:53 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("2FA disable attempt for user {UserId}", userId);
|
2026-07-22 19:54:55 +00:00
|
|
|
var result = await _mediator.Send(new Disable2faCommand(userId), ct);
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("2FA disabled successfully for user {UserId}", userId);
|
|
|
|
|
return Ok();
|
|
|
|
|
}
|
2026-07-28 14:37:52 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogWarning("2FA disable failed for user {UserId}: {Error}", userId, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
2026-07-21 08:57:53 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 15:03:18 +00:00
|
|
|
// ─── Email Confirmation ───────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/// <summary>Confirm email address with token.</summary>
|
|
|
|
|
[AllowAnonymous]
|
|
|
|
|
[HttpPost("confirm-email")]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> ConfirmEmail([FromBody] ConfirmEmailRequest request, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("ConfirmEmail attempt for UserId={UserId}", request.UserId);
|
|
|
|
|
var result = await _mediator.Send(new ConfirmEmailCommand(request.UserId, request.Token), ct);
|
|
|
|
|
|
|
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Email confirmed for UserId={UserId}", request.UserId);
|
|
|
|
|
return Ok(new { message = "Email confirmed successfully" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_logger.LogWarning("Email confirmation failed for UserId={UserId}: {Error}", request.UserId, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Forgot & Reset Password ──────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/// <summary>Send password reset link via email.</summary>
|
|
|
|
|
[AllowAnonymous]
|
|
|
|
|
[HttpPost("forgot-password")]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
|
|
|
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest request, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("ForgotPassword request for {Email}", request.Email);
|
|
|
|
|
await _mediator.Send(new ForgotPasswordCommand(request.Email), ct);
|
|
|
|
|
return Ok(new { message = "If the email exists, a reset link has been sent." });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Reset password with token.</summary>
|
|
|
|
|
[AllowAnonymous]
|
|
|
|
|
[HttpPost("reset-password")]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest request, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("ResetPassword attempt for {Email}", request.Email);
|
|
|
|
|
var result = await _mediator.Send(new ResetPasswordCommand(request.Email, request.Token, request.NewPassword), ct);
|
|
|
|
|
|
|
|
|
|
if (result.IsSuccess)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Password reset successfully for {Email}", request.Email);
|
|
|
|
|
return Ok(new { message = "Password reset successfully" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_logger.LogWarning("Password reset failed for {Email}: {Error}", request.Email, result.Error);
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 10:30:01 +00:00
|
|
|
/// <summary>Logout — revoke the current refresh token.</summary>
|
2026-08-09 23:43:11 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer")]
|
2026-07-20 10:30:01 +00:00
|
|
|
[HttpPost("logout")]
|
|
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
|
|
|
public async Task<IActionResult> Logout([FromBody] LogoutRequest request, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
|
|
|
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
2026-07-24 18:25:33 +00:00
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Logout failed: Invalid user identity");
|
2026-07-21 08:47:24 +00:00
|
|
|
return Unauthorized(new { error = "Invalid user identity" });
|
2026-07-24 18:25:33 +00:00
|
|
|
}
|
2026-07-20 10:30:01 +00:00
|
|
|
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("Logout attempt for user {UserId}", userId);
|
2026-07-22 19:54:55 +00:00
|
|
|
await _mediator.Send(new LogoutCommand(userId, request.RefreshToken), ct);
|
2026-07-24 18:25:33 +00:00
|
|
|
_logger.LogInformation("Logout successful for user {UserId}", userId);
|
2026-07-20 10:30:01 +00:00
|
|
|
return Ok();
|
|
|
|
|
}
|
|
|
|
|
}
|