UDT-008: Gestión completa de usuarios #11

Merged
dmolinari merged 16 commits from feature/UDT-008 into main 2026-04-16 00:01:36 +00:00
3 changed files with 311 additions and 0 deletions
Showing only changes of commit 7d96d5ff18 - Show all commits

View File

@@ -0,0 +1,153 @@
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 POST /api/v1/users/{id}/password/reset (UDT-008 B7).
/// </summary>
[Collection("ApiIntegration")]
public sealed class ResetPasswordEndpointTests : 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 ResetPasswordEndpointTests(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)
{
await using var conn = new SqlConnection(TestConnectionString);
await conn.OpenAsync();
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', 'User', 'cajero', '[]', 1, 0);
SELECT Id FROM dbo.Usuario WHERE Username = '{username}'
""");
}
private async Task<string> GetCajeroTokenAsync()
{
await SeedCajeroAsync("cajero_reset_auth");
var response = await _client.PostAsJsonAsync("/api/v1/auth/login",
new { username = "cajero_reset_auth", password = "@Diego550@" });
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
return json.GetProperty("accessToken").GetString()!;
}
[Fact]
public async Task POST_Password_Reset_200_Returns_TempPassword()
{
var adminToken = await GetAdminTokenAsync();
var targetId = await SeedCajeroAsync("cajero_reset_happy");
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/users/{targetId}/password/reset");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
Assert.True(json.TryGetProperty("tempPassword", out var tempProp));
Assert.False(string.IsNullOrWhiteSpace(tempProp.GetString()));
}
[Fact]
public async Task POST_Password_Reset_TempPassword_Length_Gte_12()
{
var adminToken = await GetAdminTokenAsync();
var targetId = await SeedCajeroAsync("cajero_reset_length");
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/users/{targetId}/password/reset");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
var tempPassword = json.GetProperty("tempPassword").GetString()!;
Assert.True(tempPassword.Length >= 12, $"TempPassword too short: {tempPassword.Length}");
}
[Fact]
public async Task POST_Password_Reset_400_Cannot_Self_Reset()
{
var adminToken = await GetAdminTokenAsync();
var adminId = await GetAdminIdAsync();
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/users/{adminId}/password/reset");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Contains("cannot-self-reset", body, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task POST_Password_Reset_404_Target_Not_Found()
{
var adminToken = await GetAdminTokenAsync();
var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/users/9999/password/reset");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task POST_Password_Reset_401_No_Auth()
{
var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Post, "/api/v1/users/1/password/reset"));
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task POST_Password_Reset_403_No_Permission()
{
var cajeroToken = await GetCajeroTokenAsync();
var targetId = await SeedCajeroAsync("cajero_reset_403_target");
var request = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/users/{targetId}/password/reset");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", cajeroToken);
var response = await _client.SendAsync(request);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
}

View File

@@ -0,0 +1,82 @@
using SIGCM2.Application.Common;
namespace SIGCM2.Application.Tests.Common;
public class TempPasswordGeneratorTests
{
[Fact]
public void Generate_Default_Length_Is_12()
{
var pwd = TempPasswordGenerator.Generate();
Assert.Equal(12, pwd.Length);
}
[Fact]
public void Generate_Always_Has_Uppercase_Letter()
{
for (int i = 0; i < 20; i++)
{
var pwd = TempPasswordGenerator.Generate();
Assert.True(pwd.Any(char.IsUpper), $"No uppercase found in: {pwd}");
}
}
[Fact]
public void Generate_Always_Has_Lowercase_Letter()
{
for (int i = 0; i < 20; i++)
{
var pwd = TempPasswordGenerator.Generate();
Assert.True(pwd.Any(char.IsLower), $"No lowercase found in: {pwd}");
}
}
[Fact]
public void Generate_Always_Has_Digit()
{
for (int i = 0; i < 20; i++)
{
var pwd = TempPasswordGenerator.Generate();
Assert.True(pwd.Any(char.IsDigit), $"No digit found in: {pwd}");
}
}
[Fact]
public void Generate_Always_Has_Special_Char()
{
const string symbols = "!@#$%&*+-=?";
for (int i = 0; i < 20; i++)
{
var pwd = TempPasswordGenerator.Generate();
Assert.True(pwd.Any(c => symbols.Contains(c)), $"No symbol found in: {pwd}");
}
}
[Fact]
public void Generate_Below_8_Throws_ArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>(() => TempPasswordGenerator.Generate(7));
}
[Fact]
public void Generate_100_Samples_All_Pass_Diversity()
{
const string symbols = "!@#$%&*+-=?";
for (int i = 0; i < 100; i++)
{
var pwd = TempPasswordGenerator.Generate(12);
Assert.True(pwd.Length >= 12);
Assert.True(pwd.Any(char.IsUpper));
Assert.True(pwd.Any(char.IsLower));
Assert.True(pwd.Any(char.IsDigit));
Assert.True(pwd.Any(c => symbols.Contains(c)));
}
}
[Fact]
public void Generate_Custom_Length_Respects_Length()
{
var pwd = TempPasswordGenerator.Generate(16);
Assert.Equal(16, pwd.Length);
}
}

View File

@@ -0,0 +1,76 @@
using NSubstitute;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Abstractions.Security;
using SIGCM2.Application.Usuarios.ResetPassword;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;
namespace SIGCM2.Application.Tests.Usuarios;
public class ResetUsuarioPasswordCommandHandlerTests
{
private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
private readonly IPasswordHasher _hasher = Substitute.For<IPasswordHasher>();
private readonly IRefreshTokenRepository _refreshRepo = Substitute.For<IRefreshTokenRepository>();
private readonly ResetUsuarioPasswordCommandHandler _handler;
public ResetUsuarioPasswordCommandHandlerTests()
{
_handler = new ResetUsuarioPasswordCommandHandler(_repo, _hasher, _refreshRepo);
_hasher.Hash(Arg.Any<string>()).Returns(args => "$2a$12$hashof_" + args[0]);
}
private static Usuario MakeUser(int id = 5)
=> new(id, "user" + id, "$2a$12$hash", "Test", "User", null, "cajero", "[]", true);
[Fact]
public async Task Handle_Returns_TempPassword_MinLength12_With_Diversity()
{
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeUser(5));
var result = await _handler.Handle(new ResetUsuarioPasswordCommand(TargetId: 5, CallerId: 1));
Assert.True(result.TempPassword.Length >= 12, $"TempPassword too short: {result.TempPassword.Length}");
Assert.True(result.MustChangeOnLogin);
}
[Fact]
public async Task Handle_Calls_UpdatePasswordAsync_With_MustChange_True()
{
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeUser(5));
await _handler.Handle(new ResetUsuarioPasswordCommand(TargetId: 5, CallerId: 1));
await _repo.Received(1).UpdatePasswordAsync(
5,
Arg.Any<string>(),
mustChangePassword: true,
Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Revokes_All_Refresh_Tokens_Of_Target()
{
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeUser(5));
await _handler.Handle(new ResetUsuarioPasswordCommand(TargetId: 5, CallerId: 1));
await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Throws_UsuarioNotFoundException_When_Target_Not_Found()
{
_repo.GetByIdAsync(9999, Arg.Any<CancellationToken>()).Returns((Usuario?)null);
await Assert.ThrowsAsync<UsuarioNotFoundException>(
() => _handler.Handle(new ResetUsuarioPasswordCommand(TargetId: 9999, CallerId: 1)));
}
[Fact]
public async Task Handle_Throws_CannotSelfResetException_When_Caller_Equals_Target()
{
await Assert.ThrowsAsync<CannotSelfResetException>(
() => _handler.Handle(new ResetUsuarioPasswordCommand(TargetId: 1, CallerId: 1)));
}
}