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