| | | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using System.Text; |
| | | 4 | | using FAU.DataAccess.Repositories; |
| | | 5 | | using FAU.Entidades; |
| | | 6 | | using Microsoft.Extensions.Configuration; |
| | | 7 | | using Microsoft.IdentityModel.Tokens; |
| | | 8 | | using BCrypt.Net; |
| | | 9 | | using FAU.Logica.Validadores; |
| | | 10 | | |
| | | 11 | | namespace FAU.Logica.Services; |
| | | 12 | | |
| | | 13 | | public class AuthService : IAuthService |
| | | 14 | | { |
| | | 15 | | private readonly IUsuarioRepository _usuarioRepository; |
| | | 16 | | private readonly IConfiguration _configuration; |
| | | 17 | | private readonly IAuditoriaService _auditoriaService; |
| | | 18 | | private readonly ICurrentUserContext _currentUser; |
| | 21 | 19 | | private readonly int _maxIntentosFallidos = 5; |
| | 21 | 20 | | private readonly int _tiempoBloqueoMinutos = 30; |
| | | 21 | | |
| | 21 | 22 | | public AuthService(IUsuarioRepository usuarioRepository, IConfiguration configuration, IAuditoriaService auditoriaSe |
| | | 23 | | { |
| | 21 | 24 | | _usuarioRepository = usuarioRepository; |
| | 21 | 25 | | _configuration = configuration; |
| | 21 | 26 | | _auditoriaService = auditoriaService; |
| | 21 | 27 | | _currentUser = currentUser; |
| | 21 | 28 | | } |
| | | 29 | | |
| | | 30 | | public async Task<(bool Success, string? Token, string? Error)> LoginAsync(string username, string password) |
| | | 31 | | { |
| | | 32 | | try |
| | | 33 | | { |
| | 11 | 34 | | var usuario = await _usuarioRepository.GetByUsernameWithRolesAsync(username); |
| | | 35 | | |
| | 11 | 36 | | if (usuario == null) |
| | | 37 | | { |
| | 1 | 38 | | return (false, null, "Usuario o contraseña incorrectos"); |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | // Verificar si el usuario está bloqueado |
| | 10 | 42 | | if (usuario.Estado == "bloqueado" && usuario.BloqueadoHasta.HasValue) |
| | | 43 | | { |
| | 2 | 44 | | if (usuario.BloqueadoHasta.Value > DateTime.Now) |
| | | 45 | | { |
| | 1 | 46 | | var minutosRestantes = (usuario.BloqueadoHasta.Value - DateTime.Now).Minutes; |
| | 1 | 47 | | return (false, null, $"Usuario bloqueado. Intente nuevamente en {minutosRestantes} minutos"); |
| | | 48 | | } |
| | | 49 | | else |
| | | 50 | | { |
| | | 51 | | // Desbloquear usuario |
| | 1 | 52 | | usuario.Estado = "activo"; |
| | 1 | 53 | | usuario.BloqueadoHasta = null; |
| | 1 | 54 | | usuario.IntentosFallidos = 0; |
| | 1 | 55 | | await _usuarioRepository.UpdateAsync(usuario); |
| | | 56 | | } |
| | | 57 | | } |
| | | 58 | | |
| | | 59 | | // Verificar contraseña |
| | 9 | 60 | | if (!BCrypt.Net.BCrypt.Verify(password, usuario.PasswordHash)) |
| | | 61 | | { |
| | | 62 | | // Incrementar intentos fallidos |
| | 3 | 63 | | usuario.IntentosFallidos++; |
| | | 64 | | |
| | 3 | 65 | | if (usuario.IntentosFallidos >= _maxIntentosFallidos) |
| | | 66 | | { |
| | 1 | 67 | | usuario.Estado = "bloqueado"; |
| | 1 | 68 | | usuario.BloqueadoHasta = DateTime.Now.AddMinutes(_tiempoBloqueoMinutos); |
| | 1 | 69 | | await _usuarioRepository.UpdateAsync(usuario); |
| | 1 | 70 | | await _auditoriaService.LogAuditoriaAsync(usuario.Id, AccionEnum.ActualizarUsuario, ContextoEnum.Aut |
| | 1 | 71 | | return (false, null, $"Usuario bloqueado por {_tiempoBloqueoMinutos} minutos debido a múltiples inte |
| | | 72 | | } |
| | | 73 | | |
| | 2 | 74 | | await _usuarioRepository.UpdateAsync(usuario); |
| | 2 | 75 | | return (false, null, "Usuario o contraseña incorrectos"); |
| | | 76 | | } |
| | | 77 | | |
| | | 78 | | // Login exitoso - resetear intentos fallidos |
| | 6 | 79 | | if (usuario.IntentosFallidos > 0) |
| | | 80 | | { |
| | 1 | 81 | | usuario.IntentosFallidos = 0; |
| | 1 | 82 | | await _usuarioRepository.UpdateAsync(usuario); |
| | | 83 | | } |
| | | 84 | | |
| | 6 | 85 | | await _auditoriaService.LogAuditoriaAsync( |
| | 6 | 86 | | usuario.Id, |
| | 6 | 87 | | AccionEnum.IniciarSesion, |
| | 6 | 88 | | ContextoEnum.Autenticacion, |
| | 6 | 89 | | host: _currentUser.Host, |
| | 6 | 90 | | detalle: new { username = usuario.Username, ip = _currentUser.Host }); |
| | | 91 | | |
| | | 92 | | // Generar token |
| | 6 | 93 | | var token = GenerateToken(usuario); |
| | | 94 | | |
| | 6 | 95 | | return (true, token, null); |
| | | 96 | | } |
| | 0 | 97 | | catch (Exception ex) |
| | | 98 | | { |
| | 0 | 99 | | return (false, null, $"Error durante el login: {ex.Message}"); |
| | | 100 | | } |
| | 11 | 101 | | } |
| | | 102 | | |
| | | 103 | | public async Task<(bool Success, Usuario? Usuario, string? Error)> RegisterAsync(string username, string password, l |
| | | 104 | | { |
| | | 105 | | try |
| | | 106 | | { |
| | | 107 | | // Verificar si el usuario ya existe |
| | 5 | 108 | | if (await _usuarioRepository.ExistsAsync(username)) |
| | | 109 | | { |
| | 1 | 110 | | return (false, null, "El nombre de usuario ya está en uso"); |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | // Validar la contraseña (política unificada) |
| | 4 | 114 | | var (isValid, error) = PasswordPolicy.Validate(password); |
| | 4 | 115 | | if (!isValid) |
| | | 116 | | { |
| | 3 | 117 | | return (false, null, error); |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | // Hash de la contraseña |
| | 1 | 121 | | var passwordHash = BCrypt.Net.BCrypt.HashPassword(password); |
| | | 122 | | |
| | | 123 | | // Crear nuevo usuario |
| | 1 | 124 | | var nuevoUsuario = new Usuario |
| | 1 | 125 | | { |
| | 1 | 126 | | Username = username, |
| | 1 | 127 | | PasswordHash = passwordHash, |
| | 1 | 128 | | Estado = "activo", |
| | 1 | 129 | | IntentosFallidos = 0, |
| | 1 | 130 | | PersonaId = personaId, |
| | 1 | 131 | | FechaActualizacion = DateTime.Now |
| | 1 | 132 | | }; |
| | | 133 | | |
| | 1 | 134 | | var usuarioCreado = await _usuarioRepository.CreateAsync(nuevoUsuario); |
| | 1 | 135 | | await _auditoriaService.LogAuditoriaAsync(usuarioCreado.Id, AccionEnum.CrearUsuario, ContextoEnum.Autenticac |
| | | 136 | | |
| | 1 | 137 | | return (true, usuarioCreado, null); |
| | | 138 | | } |
| | 0 | 139 | | catch (Exception ex) |
| | | 140 | | { |
| | 0 | 141 | | return (false, null, $"Error durante el registro: {ex.Message}"); |
| | | 142 | | } |
| | 5 | 143 | | } |
| | | 144 | | |
| | | 145 | | public Task<bool> ValidateTokenAsync(string token) |
| | | 146 | | { |
| | | 147 | | try |
| | | 148 | | { |
| | 3 | 149 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| | 3 | 150 | | var key = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key n |
| | | 151 | | |
| | 3 | 152 | | tokenHandler.ValidateToken(token, new TokenValidationParameters |
| | 3 | 153 | | { |
| | 3 | 154 | | ValidateIssuerSigningKey = true, |
| | 3 | 155 | | IssuerSigningKey = new SymmetricSecurityKey(key), |
| | 3 | 156 | | ValidateIssuer = true, |
| | 3 | 157 | | ValidIssuer = _configuration["Jwt:Issuer"], |
| | 3 | 158 | | ValidateAudience = true, |
| | 3 | 159 | | ValidAudience = _configuration["Jwt:Audience"], |
| | 3 | 160 | | ValidateLifetime = true, |
| | 3 | 161 | | ClockSkew = TimeSpan.Zero |
| | 3 | 162 | | }, out SecurityToken validatedToken); |
| | | 163 | | |
| | 1 | 164 | | return Task.FromResult(true); |
| | | 165 | | } |
| | 2 | 166 | | catch |
| | | 167 | | { |
| | 2 | 168 | | return Task.FromResult(false); |
| | | 169 | | } |
| | 3 | 170 | | } |
| | | 171 | | |
| | | 172 | | public string GenerateToken(Usuario usuario) |
| | | 173 | | { |
| | 9 | 174 | | var key = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no co |
| | 9 | 175 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| | | 176 | | |
| | 9 | 177 | | var claims = new List<Claim> |
| | 9 | 178 | | { |
| | 9 | 179 | | new Claim(ClaimTypes.NameIdentifier, usuario.Id.ToString()), |
| | 9 | 180 | | new Claim(ClaimTypes.Name, usuario.Username), |
| | 9 | 181 | | }; |
| | | 182 | | |
| | | 183 | | // Agregar roles como claims |
| | 22 | 184 | | foreach (var rol in usuario.Roles) |
| | | 185 | | { |
| | 2 | 186 | | claims.Add(new Claim(ClaimTypes.Role, rol.Nombre)); |
| | | 187 | | |
| | | 188 | | // Agregar permisos del rol |
| | 8 | 189 | | foreach (var permiso in rol.Permisos) |
| | | 190 | | { |
| | 2 | 191 | | claims.Add(new Claim("Permission", permiso.Nombre)); |
| | | 192 | | } |
| | | 193 | | } |
| | | 194 | | |
| | 9 | 195 | | var tokenDescriptor = new SecurityTokenDescriptor |
| | 9 | 196 | | { |
| | 9 | 197 | | Subject = new ClaimsIdentity(claims), |
| | 9 | 198 | | Expires = DateTime.Now.AddHours(int.Parse(_configuration["Jwt:ExpirationHours"] ?? "8")), |
| | 9 | 199 | | Issuer = _configuration["Jwt:Issuer"], |
| | 9 | 200 | | Audience = _configuration["Jwt:Audience"], |
| | 9 | 201 | | SigningCredentials = new SigningCredentials( |
| | 9 | 202 | | new SymmetricSecurityKey(key), |
| | 9 | 203 | | SecurityAlgorithms.HmacSha256Signature) |
| | 9 | 204 | | }; |
| | | 205 | | |
| | 9 | 206 | | var token = tokenHandler.CreateToken(tokenDescriptor); |
| | 9 | 207 | | return tokenHandler.WriteToken(token); |
| | | 208 | | } |
| | | 209 | | } |
| | | 210 | | |