Files
mmorales.photo/back/controllers/UsersController.cs
2025-08-28 16:01:55 +02:00

91 lines
3.3 KiB
C#

using back.DataModels;
using back.services.bussines;
using back.services.bussines.UserService;
using Microsoft.AspNetCore.Mvc;
namespace back.controllers;
public record UserLoginFromModel(string Email, string Password, string? SystemKey);
public record ForgotPasswordFromModel(string Email);
public record RegisterFromModel(string Name, string Email, string Password);
[ApiController, Route("api/[controller]")]
public class UsersController(IUserService user) : ControllerBase
{
private readonly IUserService _user = user;
// GET: api/<UsersController>
//[HttpGet]
//public async Task<ActionResult<IEnumerable<UserModel>>> Get([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
//{
// var users = await _userContext.GetPage(page, pageSize);
// var totalItems = await _userContext.GetTotalItems();
// Response.Headers.Append("X-Total-Count", totalItems.ToString());
// return Ok(users);
//}
//// GET api/<UsersController>/5
//[HttpGet("{id}")]
//public async Task<IActionResult> Get(Guid id)
//{
// var user = await _userContext.GetById(id);
// if (user == null)
// return NotFound();
// return Ok(user);
//}
[HttpPost("[action]")]
public async Task<IActionResult> Login(
[FromHeader(Name = "X-client-thumbprint")] string clientId,
[FromBody] UserLoginFromModel user
)
{
if (string.IsNullOrEmpty(clientId))
return BadRequest("Client ID cannot be null or empty");
if (user == null || string.IsNullOrEmpty(user.Email) || string.IsNullOrEmpty(user.Password))
return BadRequest(Errors.BadRequest.Description);
if (user.Email.Equals(DataModels.User.SystemUser.Email, StringComparison.InvariantCultureIgnoreCase))
{
if (string.IsNullOrEmpty(user.SystemKey))
return Unauthorized(Errors.Unauthorized.Description);
var systemUser = await _user.ValidateSystemUser(user.Email, user.Password, user.SystemKey, clientId);
if (systemUser == null)
return Unauthorized(Errors.Unauthorized.Description);
return Ok(systemUser.ToDto());
}
var existingUser = await _user.Login(user.Email, user.Password, clientId);
if (existingUser == null)
return Unauthorized(Errors.Unauthorized.Description);
return Ok(existingUser);
}
[HttpPost("forgot-password")]
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordFromModel user)
{
if (string.IsNullOrEmpty(user.Email))
return BadRequest("Email cannot be null or empty");
await _user.SendResetPassword(user.Email);
return Ok("If the email exists, a reset password link has been sent.");
}
// POST api/<UsersController>
[HttpPost("[action]")]
public async Task<IActionResult> Register(
[FromHeader(Name = "X-client-thumbprint")] string clientId,
[FromBody] RegisterFromModel user)
{
if (user == null)
return BadRequest("User cannot be null");
try
{
var createdUser = await _user.Create(clientId, new User() { Email = user.Email, Password = user.Password });
return Created();
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}