UDT-008: Gestión completa de usuarios #11
@@ -0,0 +1,216 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Dapper;
|
||||||
|
using Microsoft.Data.SqlClient;
|
||||||
|
using SIGCM2.TestSupport;
|
||||||
|
|
||||||
|
namespace SIGCM2.Api.Tests.Usuarios;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Integration tests for PATCH /api/v1/users/{id}/deactivate and /reactivate (UDT-008 B5).
|
||||||
|
/// </summary>
|
||||||
|
[Collection("ApiIntegration")]
|
||||||
|
public sealed class DeactivateReactivateEndpointTests : IAsyncLifetime
|
||||||
|
{
|
||||||
|
private const string TestConnectionString =
|
||||||
|
"Server=TECNICA3;Database=SIGCM2_Test;User Id=desarrollo;Password=desarrollo2026;TrustServerCertificate=True;";
|
||||||
|
|
||||||
|
private readonly HttpClient _client;
|
||||||
|
private readonly SqlTestFixture _db;
|
||||||
|
|
||||||
|
public DeactivateReactivateEndpointTests(TestWebAppFactory factory)
|
||||||
|
{
|
||||||
|
_client = factory.CreateClient();
|
||||||
|
_db = new SqlTestFixture(TestConnectionString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync() => await _db.InitializeAsync();
|
||||||
|
public async Task DisposeAsync() => await _db.DisposeAsync();
|
||||||
|
|
||||||
|
private async Task<string> GetAdminTokenAsync()
|
||||||
|
{
|
||||||
|
var response = await _client.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new { username = "admin", password = "@Diego550@" });
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||||
|
return json.GetProperty("accessToken").GetString()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<int> GetAdminIdAsync()
|
||||||
|
{
|
||||||
|
await using var conn = new SqlConnection(TestConnectionString);
|
||||||
|
await conn.OpenAsync();
|
||||||
|
return await conn.ExecuteScalarAsync<int>("SELECT Id FROM dbo.Usuario WHERE Username = 'admin'");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<int> SeedCajeroAsync(string username, bool activo = true)
|
||||||
|
{
|
||||||
|
await using var conn = new SqlConnection(TestConnectionString);
|
||||||
|
await conn.OpenAsync();
|
||||||
|
var activoVal = activo ? 1 : 0;
|
||||||
|
return await conn.ExecuteScalarAsync<int>($"""
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM dbo.Usuario WHERE Username = '{username}')
|
||||||
|
INSERT INTO dbo.Usuario (Username, PasswordHash, Nombre, Apellido, Rol, PermisosJson, Activo, MustChangePassword)
|
||||||
|
VALUES ('{username}', '$2a$12$rmq6tlSAQ8WXhR2CwLCSeuwCJKz/.8Eab95UQCUNfwe4dokeOqMcW', 'Test', 'Usuario', 'cajero', '[]', {activoVal}, 0);
|
||||||
|
SELECT Id FROM dbo.Usuario WHERE Username = '{username}'
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string> GetCajeroTokenAsync()
|
||||||
|
{
|
||||||
|
await SeedCajeroAsync("cajero_deact_auth");
|
||||||
|
var response = await _client.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new { username = "cajero_deact_auth", password = "@Diego550@" });
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||||
|
return json.GetProperty("accessToken").GetString()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── deactivate ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Deactivate_200_Returns_UserDetail_Activo_False()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var targetId = await SeedCajeroAsync("cajero_deact_happy", true);
|
||||||
|
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/v1/users/{targetId}/deactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||||
|
Assert.False(json.GetProperty("activo").GetBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Deactivate_Idempotent_Returns_200()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var targetId = await SeedCajeroAsync("cajero_deact_idempotent", false); // already inactive
|
||||||
|
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/v1/users/{targetId}/deactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||||
|
Assert.False(json.GetProperty("activo").GetBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Deactivate_400_Last_Admin_Lockout()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var adminId = await GetAdminIdAsync();
|
||||||
|
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/v1/users/{adminId}/deactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
var body = await response.Content.ReadAsStringAsync();
|
||||||
|
Assert.Contains("last-admin-lockout", body, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Deactivate_404_Not_Found()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, "/api/v1/users/9999/deactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Deactivate_401_No_Auth()
|
||||||
|
{
|
||||||
|
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Patch, "/api/v1/users/1/deactivate"));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Deactivate_403_No_Permission()
|
||||||
|
{
|
||||||
|
var token = await GetCajeroTokenAsync();
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, "/api/v1/users/1/deactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── reactivate ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Reactivate_200_Returns_UserDetail_Activo_True()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var targetId = await SeedCajeroAsync("cajero_react_happy", false); // inactive
|
||||||
|
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/v1/users/{targetId}/reactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||||
|
Assert.True(json.GetProperty("activo").GetBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Reactivate_Idempotent_Returns_200()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var targetId = await SeedCajeroAsync("cajero_react_idempotent", true); // already active
|
||||||
|
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/v1/users/{targetId}/reactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||||
|
Assert.True(json.GetProperty("activo").GetBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Reactivate_404_Not_Found()
|
||||||
|
{
|
||||||
|
var token = await GetAdminTokenAsync();
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, "/api/v1/users/9999/reactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Reactivate_401_No_Auth()
|
||||||
|
{
|
||||||
|
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Patch, "/api/v1/users/1/reactivate"));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PATCH_Reactivate_403_No_Permission()
|
||||||
|
{
|
||||||
|
var token = await GetCajeroTokenAsync();
|
||||||
|
var request = new HttpRequestMessage(HttpMethod.Patch, "/api/v1/users/1/reactivate");
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
|
||||||
|
var response = await _client.SendAsync(request);
|
||||||
|
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
using NSubstitute;
|
||||||
|
using SIGCM2.Application.Abstractions.Persistence;
|
||||||
|
using SIGCM2.Application.Common;
|
||||||
|
using SIGCM2.Application.Usuarios.Deactivate;
|
||||||
|
using SIGCM2.Domain.Entities;
|
||||||
|
using SIGCM2.Domain.Exceptions;
|
||||||
|
|
||||||
|
namespace SIGCM2.Application.Tests.Usuarios;
|
||||||
|
|
||||||
|
public class DeactivateUsuarioCommandHandlerTests
|
||||||
|
{
|
||||||
|
private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
|
||||||
|
private readonly IRefreshTokenRepository _refreshRepo = Substitute.For<IRefreshTokenRepository>();
|
||||||
|
private readonly DeactivateUsuarioCommandHandler _handler;
|
||||||
|
|
||||||
|
public DeactivateUsuarioCommandHandlerTests()
|
||||||
|
{
|
||||||
|
_handler = new DeactivateUsuarioCommandHandler(_repo, _refreshRepo);
|
||||||
|
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Usuario MakeUser(int id = 5, string rol = "cajero", bool activo = true)
|
||||||
|
=> new(id, "user" + id, "$2a$12$hash", "Test", "User", null, rol, "[]", activo);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Deactivates_Active_User_Returns_Activo_False()
|
||||||
|
{
|
||||||
|
var target = MakeUser(5, "cajero", true);
|
||||||
|
var deactivated = MakeUser(5, "cajero", false);
|
||||||
|
|
||||||
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
||||||
|
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(deactivated);
|
||||||
|
|
||||||
|
var result = await _handler.Handle(new DeactivateUsuarioCommand(5));
|
||||||
|
|
||||||
|
Assert.False(result.Activo);
|
||||||
|
await _repo.Received(1).UpdateAsync(5, Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Idempotent_When_Already_Inactive_No_FechaModificacion_Change()
|
||||||
|
{
|
||||||
|
var target = MakeUser(5, "cajero", false); // already inactive
|
||||||
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
||||||
|
|
||||||
|
var result = await _handler.Handle(new DeactivateUsuarioCommand(5));
|
||||||
|
|
||||||
|
// Idempotent: should NOT call UpdateAsync
|
||||||
|
await _repo.DidNotReceive().UpdateAsync(Arg.Any<int>(), Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
||||||
|
Assert.False(result.Activo);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Throws_LastAdminLockoutException_When_Last_Admin()
|
||||||
|
{
|
||||||
|
var lastAdmin = MakeUser(1, "admin", true);
|
||||||
|
_repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
|
||||||
|
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<LastAdminLockoutException>(
|
||||||
|
() => _handler.Handle(new DeactivateUsuarioCommand(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Revokes_Refresh_Tokens_When_Deactivating_Active_User()
|
||||||
|
{
|
||||||
|
var target = MakeUser(5, "cajero", true);
|
||||||
|
var deactivated = MakeUser(5, "cajero", false);
|
||||||
|
|
||||||
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
||||||
|
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(deactivated);
|
||||||
|
|
||||||
|
await _handler.Handle(new DeactivateUsuarioCommand(5));
|
||||||
|
|
||||||
|
await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Does_NOT_Revoke_Tokens_When_Already_Inactive_Idempotent()
|
||||||
|
{
|
||||||
|
var target = MakeUser(5, "cajero", false); // already inactive
|
||||||
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
||||||
|
|
||||||
|
await _handler.Handle(new DeactivateUsuarioCommand(5));
|
||||||
|
|
||||||
|
await _refreshRepo.DidNotReceive().RevokeAllActiveForUserAsync(Arg.Any<int>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Throws_UsuarioNotFoundException_When_Not_Found()
|
||||||
|
{
|
||||||
|
_repo.GetByIdAsync(9999, Arg.Any<CancellationToken>()).Returns((Usuario?)null);
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<UsuarioNotFoundException>(
|
||||||
|
() => _handler.Handle(new DeactivateUsuarioCommand(9999)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
using NSubstitute;
|
||||||
|
using SIGCM2.Application.Abstractions.Persistence;
|
||||||
|
using SIGCM2.Application.Common;
|
||||||
|
using SIGCM2.Application.Usuarios.Reactivate;
|
||||||
|
using SIGCM2.Domain.Entities;
|
||||||
|
using SIGCM2.Domain.Exceptions;
|
||||||
|
|
||||||
|
namespace SIGCM2.Application.Tests.Usuarios;
|
||||||
|
|
||||||
|
public class ReactivateUsuarioCommandHandlerTests
|
||||||
|
{
|
||||||
|
private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
|
||||||
|
private readonly ReactivateUsuarioCommandHandler _handler;
|
||||||
|
|
||||||
|
public ReactivateUsuarioCommandHandlerTests()
|
||||||
|
{
|
||||||
|
_handler = new ReactivateUsuarioCommandHandler(_repo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Usuario MakeUser(int id = 5, bool activo = false)
|
||||||
|
=> new(id, "user" + id, "$2a$12$hash", "Test", "User", null, "cajero", "[]", activo);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Reactivates_Inactive_User_Returns_Activo_True()
|
||||||
|
{
|
||||||
|
var target = MakeUser(5, false);
|
||||||
|
var reactivated = MakeUser(5, true);
|
||||||
|
|
||||||
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
||||||
|
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(reactivated);
|
||||||
|
|
||||||
|
var result = await _handler.Handle(new ReactivateUsuarioCommand(5));
|
||||||
|
|
||||||
|
Assert.True(result.Activo);
|
||||||
|
await _repo.Received(1).UpdateAsync(5, Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Idempotent_When_Already_Active()
|
||||||
|
{
|
||||||
|
var target = MakeUser(5, true); // already active
|
||||||
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
||||||
|
|
||||||
|
var result = await _handler.Handle(new ReactivateUsuarioCommand(5));
|
||||||
|
|
||||||
|
await _repo.DidNotReceive().UpdateAsync(Arg.Any<int>(), Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
||||||
|
Assert.True(result.Activo);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Handle_Throws_UsuarioNotFoundException_When_Not_Found()
|
||||||
|
{
|
||||||
|
_repo.GetByIdAsync(9999, Arg.Any<CancellationToken>()).Returns((Usuario?)null);
|
||||||
|
|
||||||
|
await Assert.ThrowsAsync<UsuarioNotFoundException>(
|
||||||
|
() => _handler.Handle(new ReactivateUsuarioCommand(9999)));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user