using System.Security.Claims; 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; using Heimdall.Application.Auth.Commands.Enable2fa; using Heimdall.Application.Auth.Commands.Disable2fa; using Heimdall.Application.Auth.Commands.Logout; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Infrastructure.Security; using MediatR; 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 { private readonly IMediator _mediator; private readonly IWebHostEnvironment _env; private readonly ILogger _logger; public AuthController(IMediator mediator, IWebHostEnvironment env, ILogger logger) { _mediator = mediator; _env = env; _logger = logger; } /// Register a new user. [AllowAnonymous] [HttpPost("register")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Register([FromBody] RegisterRequest request, CancellationToken ct) { _logger.LogInformation("Register attempt for {Email}", request.Email); var command = new RegisterCommand(request.Email, request.Password, request.DisplayName); var result = await _mediator.Send(command, ct); if (result.IsSuccess) { _logger.LogInformation("User registered successfully: {Email}", request.Email); return Ok(result.Data); } _logger.LogWarning("User registration failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Authenticate a user. [AllowAnonymous] [HttpPost("login")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Login([FromBody] LoginRequest request, CancellationToken ct) { _logger.LogInformation("Login attempt for {Email}", request.Email); var command = new LoginCommand(request.Email, request.Password); var result = await _mediator.Send(command, ct); if (result.IsSuccess) { _logger.LogInformation("Login successful for {Email}", request.Email); return Ok(result.Data); } _logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Verify a 2FA code. [AllowAnonymous] [EnableRateLimiting("TwoFactor")] [HttpPost("2fa/verify")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct) { _logger.LogInformation("2FA verification attempt for {Email}", request.Email); var command = new Verify2faCommand(request.Email, request.Code); var result = await _mediator.Send(command, ct); if (result.IsSuccess) { _logger.LogInformation("2FA verification successful for {Email}", request.Email); return Ok(result.Data); } _logger.LogWarning("2FA verification failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Refresh an authentication token. [AllowAnonymous] [HttpPost("refresh")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct) { _logger.LogDebug("Token refresh attempt"); var result = await _mediator.Send(new RefreshTokenCommand(request.RefreshToken), ct); if (result.IsSuccess) { _logger.LogDebug("Token refresh successful"); return Ok(result.Data); } _logger.LogWarning("Token refresh failed: {Error}", result.Error); return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Change the current user's password. [Authorize] [HttpPost("change-password")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task ChangePassword( [FromBody] ChangePasswordRequest request, CancellationToken ct) { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) { _logger.LogWarning("Change password failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); } _logger.LogInformation("Password change attempt for user {UserId}", userId); var command = new ChangePasswordCommand(userId, request.CurrentPassword, request.NewPassword); var result = await _mediator.Send(command, ct); if (result.IsSuccess) { _logger.LogInformation("Password changed successfully for user {UserId}", userId); return Ok(); } _logger.LogWarning("Password change failed for user {UserId}: {Error}", userId, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg). [AllowAnonymous] [EnableRateLimiting("TwoFactor")] [HttpPost("register-admin")] [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct) { if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment()) { _logger.LogWarning("RegisterAdmin endpoint accessed in {Environment} environment - returning 404", _env.EnvironmentName); return NotFound(); } _logger.LogInformation("RegisterAdmin attempt for {Email}", request.Email); var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName); var result = await _mediator.Send(command, ct); if (result.IsSuccess) { _logger.LogInformation("Admin user registered successfully: {Email}", request.Email); return Ok(result.Data); } _logger.LogWarning("Admin registration failed for {Email}: {Error}", request.Email, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Enable 2FA for the current user. Returns the shared key and QR code URI for setup. [Authorize] [HttpPost("2fa/enable")] [ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Enable2fa(CancellationToken ct) { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) { _logger.LogWarning("Enable2fa failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); } _logger.LogInformation("2FA enable attempt for user {UserId}", userId); var result = await _mediator.Send(new Enable2faCommand(userId), ct); if (result.IsSuccess) { _logger.LogInformation("2FA enabled successfully for user {UserId}", userId); return Ok(result.Data); } _logger.LogWarning("2FA enable failed for user {UserId}: {Error}", userId, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Disable 2FA for the current user. [Authorize] [HttpPost("2fa/disable")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Disable2fa(CancellationToken ct) { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) { _logger.LogWarning("Disable2fa failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); } _logger.LogInformation("2FA disable attempt for user {UserId}", userId); var result = await _mediator.Send(new Disable2faCommand(userId), ct); if (result.IsSuccess) { _logger.LogInformation("2FA disabled successfully for user {UserId}", userId); return Ok(); } _logger.LogWarning("2FA disable failed for user {UserId}: {Error}", userId, result.Error); return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Logout — revoke the current refresh token. [Authorize] [HttpPost("logout")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task Logout([FromBody] LogoutRequest request, CancellationToken ct) { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) { _logger.LogWarning("Logout failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); } _logger.LogInformation("Logout attempt for user {UserId}", userId); await _mediator.Send(new LogoutCommand(userId, request.RefreshToken), ct); _logger.LogInformation("Logout successful for user {UserId}", userId); return Ok(); } }