Fase 2: Creatción de la UI (React + Vite). Implementación de Log In reemplazando texto plano. Y creación de tool para migrar contraseñas.
This commit is contained in:
109
Backend/GestionIntegral.Api/Services/AuthService.cs
Normal file
109
Backend/GestionIntegral.Api/Services/AuthService.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Dtos;
|
||||
using GestionIntegral.Api.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace GestionIntegral.Api.Services
|
||||
{
|
||||
public class AuthService : IAuthService
|
||||
{
|
||||
private readonly IAuthRepository _authRepository;
|
||||
private readonly PasswordHasherService _passwordHasher;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<AuthService> _logger; // Añadir logger
|
||||
|
||||
public AuthService(
|
||||
IAuthRepository authRepository,
|
||||
PasswordHasherService passwordHasher,
|
||||
IConfiguration configuration,
|
||||
ILogger<AuthService> logger) // Inyectar logger
|
||||
{
|
||||
_authRepository = authRepository;
|
||||
_passwordHasher = passwordHasher;
|
||||
_configuration = configuration;
|
||||
_logger = logger; // Asignar logger
|
||||
}
|
||||
|
||||
public async Task<LoginResponseDto?> LoginAsync(LoginRequestDto loginRequest)
|
||||
{
|
||||
var user = await _authRepository.GetUserByUsernameAsync(loginRequest.Username);
|
||||
|
||||
if (user == 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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Generar Token JWT
|
||||
var token = GenerateJwtToken(user);
|
||||
|
||||
// Determinar si debe cambiar clave (leyendo de la BD via el repo/modelo)
|
||||
bool debeCambiar = user.DebeCambiarClave;
|
||||
|
||||
_logger.LogInformation("User {Username} logged in successfully.", loginRequest.Username);
|
||||
|
||||
// Crear y devolver la respuesta
|
||||
return new LoginResponseDto
|
||||
{
|
||||
Token = token,
|
||||
UserId = user.Id,
|
||||
Username = user.User,
|
||||
NombreCompleto = $"{user.Nombre} {user.Apellido}",
|
||||
EsSuperAdmin = user.SupAdmin,
|
||||
DebeCambiarClave = debeCambiar
|
||||
};
|
||||
}
|
||||
|
||||
// --- GenerateJwtToken sin cambios ---
|
||||
private string GenerateJwtToken(Usuario user)
|
||||
{
|
||||
var jwtSettings = _configuration.GetSection("Jwt");
|
||||
var key = Encoding.ASCII.GetBytes(jwtSettings["Key"]
|
||||
?? throw new ArgumentNullException("Jwt:Key", "JWT Key not configured"));
|
||||
|
||||
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())
|
||||
}),
|
||||
Expires = DateTime.UtcNow.AddHours(Convert.ToInt32(jwtSettings["DurationInHours"] ?? "1")),
|
||||
Issuer = jwtSettings["Issuer"],
|
||||
Audience = jwtSettings["Audience"],
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
||||
};
|
||||
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
}
|
||||
|
||||
// TODO: Implementar ChangePasswordAsync
|
||||
}
|
||||
}
|
||||
10
Backend/GestionIntegral.Api/Services/IAuthService.cs
Normal file
10
Backend/GestionIntegral.Api/Services/IAuthService.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using GestionIntegral.Api.Dtos;
|
||||
|
||||
namespace GestionIntegral.Api.Services
|
||||
{
|
||||
public interface IAuthService
|
||||
{
|
||||
Task<LoginResponseDto?> LoginAsync(LoginRequestDto loginRequest);
|
||||
// Añadiremos cambio de clave, etc.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GestionIntegral.Api.Services
|
||||
{
|
||||
public class PasswordHasherService
|
||||
{
|
||||
private const int SaltSize = 16; // 128 bit
|
||||
private const int HashSize = 32; // 256 bit
|
||||
private const int Iterations = 10000; // Número de iteraciones (ajustable)
|
||||
|
||||
// Genera un hash y una salt para una contraseña dada
|
||||
public (string hash, string salt) HashPassword(string password)
|
||||
{
|
||||
// Generar una salt aleatoria
|
||||
byte[] saltBytes = RandomNumberGenerator.GetBytes(SaltSize);
|
||||
|
||||
// Crear el hash usando PBKDF2
|
||||
var pbkdf2 = new Rfc2898DeriveBytes(password, saltBytes, Iterations, HashAlgorithmName.SHA256);
|
||||
byte[] hashBytes = pbkdf2.GetBytes(HashSize);
|
||||
|
||||
// Convertir bytes a strings Base64 para almacenamiento
|
||||
string saltString = Convert.ToBase64String(saltBytes);
|
||||
string hashString = Convert.ToBase64String(hashBytes);
|
||||
|
||||
return (hashString, saltString);
|
||||
}
|
||||
|
||||
// Verifica si una contraseña coincide con un hash y salt almacenados
|
||||
public bool VerifyPassword(string password, string storedHash, string storedSalt)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Convertir strings Base64 de vuelta a bytes
|
||||
byte[] saltBytes = Convert.FromBase64String(storedSalt);
|
||||
byte[] storedHashBytes = Convert.FromBase64String(storedHash);
|
||||
|
||||
// Crear el hash de la contraseña ingresada usando la misma salt e iteraciones
|
||||
var pbkdf2 = new Rfc2898DeriveBytes(password, saltBytes, Iterations, HashAlgorithmName.SHA256);
|
||||
byte[] testHashBytes = pbkdf2.GetBytes(HashSize);
|
||||
|
||||
// Comparar los hashes de forma segura (evita timing attacks)
|
||||
return CryptographicOperations.FixedTimeEquals(storedHashBytes, testHashBytes);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// Manejar el caso donde las strings almacenadas no son Base64 válidas
|
||||
return false;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Loggear la excepción si es necesario
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user