using Features.Users.Commands.Account.DeleteAccount;
using Features.Users.Commands.Account.UpdateEmail;
using Features.Users.Commands.Account.UpdatePassword;
using Features.Users.Commands.Account.UpdateUsername;
using Features.Users.Commands.Authentication.ConfirmUser;
using Features.Users.Commands.Authentication.Login;
using Features.Users.Commands.Authentication.RefreshToken;
using Features.Users.Commands.Authentication.RegisterUser;
using Features.Users.Commands.Authentication.ResendConfirmationEmail;
using Features.Users.Commands.Profile.UpdateProfile;
using Features.Users.Dtos;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared.Contracts;
namespace Features.Users.Controllers;
///
/// Handles user authentication concerns: registration, login, email confirmation, token refresh, and
/// self-service account management.
///
///
/// The controller is decorated with [Authorize(AuthenticationSchemes = "JWT")] by default, but most
/// actions opt out via [AllowAnonymous] since they are entry points used before a caller holds a token.
///
[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "JWT")]
public class AuthController(IMediator mediator) : ControllerBase
{
/// Registers a new user account.
///
/// Anonymous access. Returns 201 Created with the new account's ID, username, and issued tokens.
/// Returns 409 Conflict if the username or email is already taken.
///
[AllowAnonymous]
[HttpPost("register")]
public async Task>> Register(
[FromBody] RegisterUserCommand command
)
{
RegistrationPayload payload = await mediator.Send(command);
return Created(
"/",
new ResponseBody
{
Message = "User registered successfully.",
Payload = payload,
}
);
}
/// Authenticates a user by username and password and issues a new access/refresh token pair.
///
/// Anonymous access. Returns 200 OK with the tokens, or 401 Unauthorized if the credentials are invalid.
///
[AllowAnonymous]
[HttpPost("login")]
public async Task>> Login(
[FromBody] LoginCommand command
)
{
LoginPayload payload = await mediator.Send(command);
return Ok(
new ResponseBody
{
Message = "Logged in successfully.",
Payload = payload,
}
);
}
/// Confirms a user account using a confirmation token.
///
/// Requires a valid JWT bearer token (no [AllowAnonymous] override). Returns 200 OK on success,
/// or 401 Unauthorized if is invalid or expired.
///
[HttpPost("confirm")]
public async Task>> Confirm(
[FromQuery] string token
)
{
ConfirmationPayload payload = await mediator.Send(new ConfirmUserCommand(token));
return Ok(
new ResponseBody
{
Message = "User with ID " + payload.UserAccountId + " is confirmed.",
Payload = payload,
}
);
}
/// Resends the account confirmation email for the given user, generating a fresh confirmation token.
///
/// Requires a valid JWT bearer token (no [AllowAnonymous] override). Always returns 200 OK, even
/// if does not exist or the account is already confirmed, to avoid user
/// enumeration.
///
[HttpPost("confirm/resend")]
public async Task> ResendConfirmation([FromQuery] Guid userId)
{
await mediator.Send(new ResendConfirmationEmailCommand(userId));
return Ok(new ResponseBody { Message = "confirmation email has been resent" });
}
/// Exchanges a valid refresh token for a new access/refresh token pair.
///
/// Anonymous access. The refresh token is supplied via the X-Refresh-Token header, not the
/// request body. Returns 200 OK with the new tokens, 400 Bad Request if the header is missing, or
/// 401 Unauthorized if the refresh token is invalid or expired.
///
[AllowAnonymous]
[HttpPost("refresh")]
public async Task>> Refresh(
[FromHeader(Name = "X-Refresh-Token")] string? refreshToken
)
{
LoginPayload payload = await mediator.Send(
new RefreshTokenCommand(refreshToken ?? string.Empty)
);
return Ok(
new ResponseBody
{
Message = "Token refreshed successfully.",
Payload = payload,
}
);
}
/// Changes the authenticated user's username.
/// Returns 200 OK with the updated username, or 409 Conflict if it is already taken.
[HttpPatch("username")]
public async Task>> UpdateUsername(
[FromBody] UpdateUsernameRequest request
)
{
UpdateUsernamePayload payload = await mediator.Send(
new UpdateUsernameCommand(User.GetAuthenticatedUserId(), request.NewUsername)
);
return Ok(
new ResponseBody
{
Message = "Username updated successfully.",
Payload = payload,
}
);
}
/// Changes the authenticated user's email address.
///
/// Returns 200 OK with the updated (now unconfirmed) email address, or 409 Conflict if it is
/// already in use. The caller should use POST /api/auth/confirm/resend to re-confirm.
///
[HttpPatch("email")]
public async Task>> UpdateEmail(
[FromBody] UpdateEmailRequest request
)
{
UpdateEmailPayload payload = await mediator.Send(
new UpdateEmailCommand(User.GetAuthenticatedUserId(), request.NewEmail)
);
return Ok(
new ResponseBody
{
Message = "Email updated successfully.",
Payload = payload,
}
);
}
/// Changes the authenticated user's password.
///
/// Returns 200 OK on success, or 401 Unauthorized if CurrentPassword does not match the
/// account's current password.
///
[HttpPatch("password")]
public async Task>> UpdatePassword(
[FromBody] UpdatePasswordRequest request
)
{
UpdatePasswordPayload payload = await mediator.Send(
new UpdatePasswordCommand(
User.GetAuthenticatedUserId(),
request.CurrentPassword,
request.NewPassword
)
);
return Ok(
new ResponseBody
{
Message = "Password updated successfully.",
Payload = payload,
}
);
}
/// Updates the authenticated user's profile fields (first name, last name, date of birth).
/// Returns 200 OK with the updated profile.
[HttpPatch("profile")]
public async Task>> UpdateProfile(
[FromBody] UpdateProfileRequest request
)
{
UpdateProfilePayload payload = await mediator.Send(
new UpdateProfileCommand(
User.GetAuthenticatedUserId(),
request.FirstName,
request.LastName,
request.DateOfBirth
)
);
return Ok(
new ResponseBody
{
Message = "Profile updated successfully.",
Payload = payload,
}
);
}
/// Permanently deletes the authenticated user's account.
///
/// Returns 200 OK on success, or 409 Conflict if the account still has associated posts, comments,
/// photos, or follows.
///
[HttpDelete("account")]
public async Task> DeleteAccount()
{
await mediator.Send(new DeleteAccountCommand(User.GetAuthenticatedUserId()));
return Ok(new ResponseBody { Message = "Account deleted successfully." });
}
}