Fase 2: Gestión de Usuarios (CRUD Completo) - Backend & Frontend

This commit is contained in:
2025-12-17 13:37:06 -03:00
parent b3b553495b
commit dff7a377a4
9 changed files with 387 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SIGCM.Application.DTOs;
using SIGCM.Domain.Entities;
using SIGCM.Domain.Interfaces;
namespace SIGCM.API.Controllers;
[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "Admin")] // Only admins can manage users
public class UsersController : ControllerBase
{
private readonly IUserRepository _repository;
public UsersController(IUserRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var users = await _repository.GetAllAsync();
// Don't expose password hashes
var sanitized = users.Select(u => new {
u.Id, u.Username, u.Role, u.Email, u.CreatedAt
});
return Ok(sanitized);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
var user = await _repository.GetByIdAsync(id);
if (user == null) return NotFound();
return Ok(new { user.Id, user.Username, user.Role, user.Email, user.CreatedAt });
}
[HttpPost]
public async Task<IActionResult> Create(CreateUserDto dto)
{
// Check if exists
var existing = await _repository.GetByUsernameAsync(dto.Username);
if (existing != null) return BadRequest("El nombre de usuario ya existe.");
var passwordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
var user = new User
{
Username = dto.Username,
PasswordHash = passwordHash,
Role = dto.Role,
Email = dto.Email,
CreatedAt = DateTime.UtcNow
};
var id = await _repository.CreateAsync(user);
return CreatedAtAction(nameof(GetById), new { id }, new { id, user.Username });
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, UpdateUserDto dto)
{
var user = await _repository.GetByIdAsync(id);
if (user == null) return NotFound();
user.Username = dto.Username;
user.Role = dto.Role;
user.Email = dto.Email;
if (!string.IsNullOrEmpty(dto.Password))
{
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
}
await _repository.UpdateAsync(user);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
// Safe check: prevent deleting yourself optional but good practice
// For now simple delete
await _repository.DeleteAsync(id);
return NoContent();
}
}

View File

@@ -0,0 +1,17 @@
namespace SIGCM.Application.DTOs;
public class CreateUserDto
{
public required string Username { get; set; }
public required string Password { get; set; }
public required string Role { get; set; }
public string? Email { get; set; }
}
public class UpdateUserDto
{
public required string Username { get; set; }
public string? Password { get; set; } // Opcional, solo si se quiere cambiar
public required string Role { get; set; }
public string? Email { get; set; }
}

View File

@@ -4,5 +4,9 @@ using SIGCM.Domain.Entities;
public interface IUserRepository
{
Task<User?> GetByUsernameAsync(string username);
Task<IEnumerable<User>> GetAllAsync();
Task<User?> GetByIdAsync(int id);
Task<int> CreateAsync(User user);
Task UpdateAsync(User user);
Task DeleteAsync(int id);
}

View File

@@ -31,4 +31,32 @@ public class UserRepository : IUserRepository
SELECT CAST(SCOPE_IDENTITY() as int);";
return await conn.QuerySingleAsync<int>(sql, user);
}
public async Task<IEnumerable<User>> GetAllAsync()
{
using var conn = _connectionFactory.CreateConnection();
return await conn.QueryAsync<User>("SELECT Id, Username, Role, Email, CreatedAt, PasswordHash FROM Users");
}
public async Task<User?> GetByIdAsync(int id)
{
using var conn = _connectionFactory.CreateConnection();
return await conn.QuerySingleOrDefaultAsync<User>("SELECT * FROM Users WHERE Id = @Id", new { Id = id });
}
public async Task UpdateAsync(User user)
{
using var conn = _connectionFactory.CreateConnection();
var sql = @"
UPDATE Users
SET Username = @Username, Role = @Role, Email = @Email, PasswordHash = @PasswordHash
WHERE Id = @Id";
await conn.ExecuteAsync(sql, user);
}
public async Task DeleteAsync(int id)
{
using var conn = _connectionFactory.CreateConnection();
await conn.ExecuteAsync("DELETE FROM Users WHERE Id = @Id", new { Id = id });
}
}