Files
GestionIntegralWeb/Backend/GestionIntegral.Api/Services/AuthService.cs

174 lines
7.5 KiB
C#
Raw Normal View History

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;
}
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;
}
// --- 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 ---
var token = GenerateJwtToken(user, permisosDelUsuario); // Pasar permisos
bool debeCambiar = user.DebeCambiarClave;
_logger.LogInformation("User {Username} logged in successfully.", loginRequest.Username);
return new LoginResponseDto
{
Token = token,
UserId = user.Id,
Username = user.User,
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, 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(claims),
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);
}
}
}