- Backend API:
Autenticación y autorización básicas con JWT implementadas.
Cambio de contraseña funcional.
Módulo "Tipos de Pago" (CRUD completo) implementado en el backend (Controlador, Servicio, Repositorio) usando Dapper, transacciones y con lógica de historial.
Se incluyen permisos en el token JWT.
- Frontend React:
Estructura base con Vite, TypeScript, MUI.
Contexto de autenticación (AuthContext) que maneja el estado del usuario y el token.
Página de Login.
Modal de Cambio de Contraseña (forzado y opcional).
Hook usePermissions para verificar permisos.
Página GestionarTiposPagoPage con tabla, paginación, filtro, modal para crear/editar, y menú de acciones, respetando permisos.
Layout principal (MainLayout) con navegación por Tabs (funcionalidad básica de navegación).
Estructura de enrutamiento (AppRoutes) que maneja rutas públicas, protegidas y anidadas para módulos.
This commit is contained in:
2025-05-07 13:41:18 -03:00
parent da7b544372
commit 5c4b961073
49 changed files with 2552 additions and 491 deletions

View File

@@ -34,34 +34,35 @@ namespace GestionIntegral.Api.Services
if (user == null)
{
_logger.LogWarning("Login attempt failed: User {Username} not found.", loginRequest.Username);
return null;
_logger.LogWarning("Login attempt failed: User {Username} not found.", loginRequest.Username);
return null;
}
if (!user.Habilitada)
{
_logger.LogWarning("Login attempt failed: User {Username} is disabled.", loginRequest.Username);
return null;
_logger.LogWarning("Login attempt failed: User {Username} is disabled.", loginRequest.Username);
return null;
}
// Verificar contraseña usando el hash y salt de la BD
bool isPasswordValid = _passwordHasher.VerifyPassword(loginRequest.Password, user.ClaveHash, user.ClaveSalt);
if (!isPasswordValid)
{
_logger.LogWarning("Login attempt failed: Invalid password for user {Username}.", loginRequest.Username);
return null;
_logger.LogWarning("Login attempt failed: Invalid password for user {Username}.", loginRequest.Username);
return null;
}
// Generar Token JWT
var token = GenerateJwtToken(user);
// --- OBTENER PERMISOS ---
IEnumerable<string> permisosDelUsuario = new List<string>();
if (!user.SupAdmin && user.IdPerfil > 0) // Solo si no es SuperAdmin y tiene un perfil válido
{
permisosDelUsuario = await _authRepository.GetPermisosCodAccByPerfilIdAsync(user.IdPerfil);
}
// --- FIN OBTENER PERMISOS ---
// Determinar si debe cambiar clave (leyendo de la BD via el repo/modelo)
var token = GenerateJwtToken(user, permisosDelUsuario); // Pasar permisos
bool debeCambiar = user.DebeCambiarClave;
_logger.LogInformation("User {Username} logged in successfully.", loginRequest.Username);
_logger.LogInformation("User {Username} logged in successfully.", loginRequest.Username);
// Crear y devolver la respuesta
return new LoginResponseDto
{
Token = token,
@@ -70,30 +71,96 @@ namespace GestionIntegral.Api.Services
NombreCompleto = $"{user.Nombre} {user.Apellido}",
EsSuperAdmin = user.SupAdmin,
DebeCambiarClave = debeCambiar
// No necesitamos pasar la lista de permisos aquí, ya irán en el token
};
}
public async Task<bool> ChangePasswordAsync(int userId, ChangePasswordRequestDto changePasswordRequest)
{
// 1. Obtener el usuario actual (necesitamos su hash/salt actual)
var user = await _authRepository.GetUserByIdAsync(userId);
if (user == null)
{
_logger.LogWarning("ChangePassword attempt failed: User with ID {UserId} not found.", userId);
return false; // Usuario no encontrado
}
// 2. Verificar la contraseña ACTUAL
if (!_passwordHasher.VerifyPassword(changePasswordRequest.CurrentPassword, user.ClaveHash, user.ClaveSalt))
{
_logger.LogWarning("ChangePassword attempt failed: Invalid current password for user ID {UserId}.", userId);
return false; // Contraseña actual incorrecta
}
// 3. Verificar que la nueva contraseña no sea igual al nombre de usuario
if (user.User == changePasswordRequest.NewPassword)
{
_logger.LogWarning("ChangePassword attempt failed: New password cannot be the same as username for user ID {UserId}.", userId);
// Podrías lanzar una excepción o devolver un código de error específico
// Por simplicidad, devolvemos false
return false;
}
// 4. Generar nuevo hash y salt para la NUEVA contraseña
(string newHash, string newSalt) = _passwordHasher.HashPassword(changePasswordRequest.NewPassword);
// 5. Actualizar en la base de datos (el repositorio también pone DebeCambiarClave = 0)
bool success = await _authRepository.UpdatePasswordAsync(userId, newHash, newSalt);
if (success)
{
_logger.LogInformation("Password changed successfully for user ID {UserId}.", userId);
}
else
{
_logger.LogError("Failed to update password in database for user ID {UserId}.", userId);
}
return success;
}
// --- GenerateJwtToken sin cambios ---
private string GenerateJwtToken(Usuario user)
private string GenerateJwtToken(Usuario user, IEnumerable<string> permisosCodAcc) // Recibir permisos
{
var jwtSettings = _configuration.GetSection("Jwt");
var key = Encoding.ASCII.GetBytes(jwtSettings["Key"]
?? throw new ArgumentNullException("Jwt:Key", "JWT Key not configured"));
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Name, user.User),
new Claim(JwtRegisteredClaimNames.GivenName, user.Nombre),
new Claim(JwtRegisteredClaimNames.FamilyName, user.Apellido),
new Claim("idPerfil", user.IdPerfil.ToString()),
new Claim("debeCambiarClave", user.DebeCambiarClave.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
// Añadir rol basado en SupAdmin o IdPerfil
if (user.SupAdmin)
{
claims.Add(new Claim(ClaimTypes.Role, "SuperAdmin"));
// Opcional: Si SuperAdmin tiene todos los permisos, podrías añadir un claim especial
// claims.Add(new Claim("permission", "*"));
}
else
{
claims.Add(new Claim(ClaimTypes.Role, $"Perfil_{user.IdPerfil}"));
// Añadir cada código de permiso como un claim "permission"
if (permisosCodAcc != null)
{
foreach (var codAcc in permisosCodAcc)
{
claims.Add(new Claim("permission", codAcc)); // Usar "permission" como tipo de claim
}
}
}
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Name, user.User),
new Claim(JwtRegisteredClaimNames.GivenName, user.Nombre),
new Claim(JwtRegisteredClaimNames.FamilyName, user.Apellido),
new Claim(ClaimTypes.Role, user.SupAdmin ? "SuperAdmin" : $"Perfil_{user.IdPerfil}"),
new Claim("idPerfil", user.IdPerfil.ToString()), // Añadir IdPerfil como claim explícito
new Claim("debeCambiarClave", user.DebeCambiarClave.ToString()), // Añadir flag como claim
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}),
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(Convert.ToInt32(jwtSettings["DurationInHours"] ?? "1")),
Issuer = jwtSettings["Issuer"],
Audience = jwtSettings["Audience"],
@@ -103,7 +170,5 @@ namespace GestionIntegral.Api.Services
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
// TODO: Implementar ChangePasswordAsync
}
}