| | | 1 | | using FAU.DataAccess.Repositories; |
| | | 2 | | using FAU.Entidades; |
| | | 3 | | using FAU.Logica.Validadores; |
| | | 4 | | |
| | | 5 | | namespace FAU.Logica.Services; |
| | | 6 | | |
| | | 7 | | public class UsuarioService : IUsuarioService |
| | | 8 | | { |
| | | 9 | | private readonly IUsuarioRepository _usuarioRepository; |
| | | 10 | | private readonly IRolRepository _rolRepository; |
| | | 11 | | private readonly IAuditoriaService _auditoriaService; |
| | | 12 | | private readonly ICurrentUserContext _currentUser; |
| | | 13 | | |
| | 25 | 14 | | public UsuarioService(IUsuarioRepository usuarioRepository, IRolRepository rolRepository, IAuditoriaService auditori |
| | | 15 | | { |
| | 25 | 16 | | _usuarioRepository = usuarioRepository; |
| | 25 | 17 | | _rolRepository = rolRepository; |
| | 25 | 18 | | _auditoriaService = auditoriaService; |
| | 25 | 19 | | _currentUser = currentUser; |
| | 25 | 20 | | } |
| | | 21 | | |
| | | 22 | | public async Task<Usuario?> GetByIdAsync(long id) |
| | | 23 | | { |
| | 2 | 24 | | return await _usuarioRepository.GetByIdAsync(id); |
| | 2 | 25 | | } |
| | | 26 | | |
| | | 27 | | public async Task<Usuario?> GetByUsernameWithRolesAsync(string username) |
| | | 28 | | { |
| | 1 | 29 | | return await _usuarioRepository.GetByUsernameWithRolesAsync(username); |
| | 1 | 30 | | } |
| | | 31 | | |
| | | 32 | | public async Task<IEnumerable<Usuario>> GetAllAsync() |
| | | 33 | | { |
| | 1 | 34 | | return await _usuarioRepository.GetAllAsync(); |
| | 1 | 35 | | } |
| | | 36 | | |
| | | 37 | | public async Task<(bool Success, Usuario? Usuario, string? Error)> CreateAsync(string username, string password, lon |
| | | 38 | | { |
| | | 39 | | try |
| | | 40 | | { |
| | 2 | 41 | | if (await _usuarioRepository.ExistsAsync(username)) |
| | | 42 | | { |
| | 1 | 43 | | return (false, null, "El nombre de usuario ya está en uso"); |
| | | 44 | | } |
| | | 45 | | |
| | 1 | 46 | | var (isValid, error) = PasswordPolicy.Validate(password); |
| | 1 | 47 | | if (!isValid) |
| | | 48 | | { |
| | 0 | 49 | | return (false, null, error); |
| | | 50 | | } |
| | | 51 | | |
| | 1 | 52 | | var passwordHash = BCrypt.Net.BCrypt.HashPassword(password); |
| | | 53 | | |
| | 1 | 54 | | var nuevoUsuario = new Usuario |
| | 1 | 55 | | { |
| | 1 | 56 | | Username = username, |
| | 1 | 57 | | PasswordHash = passwordHash, |
| | 1 | 58 | | Estado = "activo", |
| | 1 | 59 | | IntentosFallidos = 0, |
| | 1 | 60 | | PersonaId = personaId, |
| | 1 | 61 | | FechaActualizacion = DateTime.Now |
| | 1 | 62 | | }; |
| | | 63 | | |
| | 1 | 64 | | var usuarioCreado = await _usuarioRepository.CreateAsync(nuevoUsuario); |
| | 1 | 65 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.CrearUsuario, ContextoEnum.Us |
| | 1 | 66 | | return (true, usuarioCreado, null); |
| | | 67 | | } |
| | 0 | 68 | | catch (Exception ex) |
| | | 69 | | { |
| | 0 | 70 | | return (false, null, $"Error al crear usuario: {ex.Message}"); |
| | | 71 | | } |
| | 2 | 72 | | } |
| | | 73 | | |
| | | 74 | | public async Task<(bool Success, Usuario? Usuario, string? Error)> UpdateAsync(long id, string? newPassword = null) |
| | | 75 | | { |
| | | 76 | | try |
| | | 77 | | { |
| | 3 | 78 | | var usuario = await _usuarioRepository.GetByIdAsync(id); |
| | 3 | 79 | | if (usuario == null) |
| | | 80 | | { |
| | 1 | 81 | | return (false, null, "Usuario no encontrado"); |
| | | 82 | | } |
| | | 83 | | |
| | 2 | 84 | | if (!string.IsNullOrWhiteSpace(newPassword)) |
| | | 85 | | { |
| | 1 | 86 | | var (isValid, error) = PasswordPolicy.Validate(newPassword); |
| | 1 | 87 | | if (!isValid) |
| | | 88 | | { |
| | 0 | 89 | | return (false, null, error); |
| | | 90 | | } |
| | | 91 | | |
| | 1 | 92 | | usuario.PasswordHash = BCrypt.Net.BCrypt.HashPassword(newPassword); |
| | | 93 | | } |
| | | 94 | | |
| | 2 | 95 | | var usuarioActualizado = await _usuarioRepository.UpdateAsync(usuario); |
| | 2 | 96 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.ActualizarUsuario, ContextoEn |
| | 2 | 97 | | return (true, usuarioActualizado, null); |
| | | 98 | | } |
| | 0 | 99 | | catch (Exception ex) |
| | | 100 | | { |
| | 0 | 101 | | return (false, null, $"Error al actualizar usuario: {ex.Message}"); |
| | | 102 | | } |
| | 3 | 103 | | } |
| | | 104 | | |
| | | 105 | | public async Task<(bool Success, string? Error)> CambiarEstadoAsync(long id, string nuevoEstado) |
| | | 106 | | { |
| | | 107 | | try |
| | | 108 | | { |
| | 4 | 109 | | var usuario = await _usuarioRepository.GetByIdAsync(id); |
| | 4 | 110 | | if (usuario == null) |
| | | 111 | | { |
| | 1 | 112 | | return (false, "Usuario no encontrado"); |
| | | 113 | | } |
| | | 114 | | |
| | | 115 | | // Validar estados permitidos |
| | 3 | 116 | | var estadosPermitidos = new[] { "Activo", "Bloqueado", "Inactivo" }; |
| | 3 | 117 | | if (!estadosPermitidos.Contains(nuevoEstado, StringComparer.OrdinalIgnoreCase)) |
| | | 118 | | { |
| | 1 | 119 | | return (false, "Estado inválido. Valores permitidos: Activo, Bloqueado, Inactivo"); |
| | | 120 | | } |
| | | 121 | | |
| | 2 | 122 | | var estadoAnterior = usuario.Estado; |
| | 2 | 123 | | usuario.Estado = nuevoEstado; |
| | 2 | 124 | | usuario.FechaActualizacion = DateTime.Now; |
| | | 125 | | |
| | | 126 | | // Cuando se desbloquea un usuario, limpiar bloqueado_hasta e intentos_fallidos |
| | 2 | 127 | | if (estadoAnterior.Equals("bloqueado", StringComparison.OrdinalIgnoreCase) && |
| | 2 | 128 | | nuevoEstado.Equals("activo", StringComparison.OrdinalIgnoreCase)) |
| | | 129 | | { |
| | 1 | 130 | | usuario.BloqueadoHasta = null; |
| | 1 | 131 | | usuario.IntentosFallidos = 0; |
| | | 132 | | } |
| | | 133 | | |
| | 2 | 134 | | await _usuarioRepository.UpdateAsync(usuario); |
| | 2 | 135 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.ActualizarUsuario, ContextoEn |
| | 2 | 136 | | return (true, null); |
| | | 137 | | } |
| | 0 | 138 | | catch (Exception ex) |
| | | 139 | | { |
| | 0 | 140 | | return (false, $"Error al cambiar estado del usuario: {ex.Message}"); |
| | | 141 | | } |
| | 4 | 142 | | } |
| | | 143 | | |
| | | 144 | | public async Task<(bool Success, string? Error)> CambiarPasswordAsync(long id, string nuevaPassword) |
| | | 145 | | { |
| | | 146 | | try |
| | | 147 | | { |
| | 4 | 148 | | var usuario = await _usuarioRepository.GetByIdAsync(id); |
| | 4 | 149 | | if (usuario == null) |
| | | 150 | | { |
| | 1 | 151 | | return (false, "Usuario no encontrado"); |
| | | 152 | | } |
| | | 153 | | |
| | 3 | 154 | | var (isValid, error) = PasswordPolicy.Validate(nuevaPassword); |
| | 3 | 155 | | if (!isValid) |
| | | 156 | | { |
| | 2 | 157 | | return (false, error); |
| | | 158 | | } |
| | | 159 | | |
| | 1 | 160 | | usuario.PasswordHash = BCrypt.Net.BCrypt.HashPassword(nuevaPassword); |
| | 1 | 161 | | usuario.FechaActualizacion = DateTime.Now; |
| | | 162 | | |
| | 1 | 163 | | await _usuarioRepository.UpdateAsync(usuario); |
| | 1 | 164 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.ActualizarUsuario, ContextoEn |
| | 1 | 165 | | return (true, null); |
| | | 166 | | } |
| | 0 | 167 | | catch (Exception ex) |
| | | 168 | | { |
| | 0 | 169 | | return (false, $"Error al cambiar contraseña: {ex.Message}"); |
| | | 170 | | } |
| | 4 | 171 | | } |
| | | 172 | | |
| | | 173 | | public async Task<(bool Success, string? Error)> AsignarRolAsync(long usuarioId, long rolId) |
| | | 174 | | { |
| | | 175 | | try |
| | | 176 | | { |
| | 4 | 177 | | var usuario = await _usuarioRepository.GetByIdAsync(usuarioId); |
| | 4 | 178 | | if (usuario == null) |
| | | 179 | | { |
| | 1 | 180 | | return (false, "Usuario no encontrado"); |
| | | 181 | | } |
| | | 182 | | |
| | 3 | 183 | | var rol = await _rolRepository.GetByIdAsync(rolId); |
| | 3 | 184 | | if (rol == null) |
| | | 185 | | { |
| | 1 | 186 | | return (false, "Rol no encontrado"); |
| | | 187 | | } |
| | | 188 | | |
| | | 189 | | // Check if role is already assigned (by ID to avoid tracking issues) |
| | 3 | 190 | | if (usuario.Roles.Any(r => r.Id == rolId)) |
| | | 191 | | { |
| | 1 | 192 | | return (false, "El usuario ya tiene este rol asignado"); |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | // Add the role to the collection |
| | 1 | 196 | | usuario.Roles.Add(rol); |
| | | 197 | | |
| | | 198 | | // Update the usuario (this will persist the role assignment) |
| | 1 | 199 | | await _usuarioRepository.UpdateAsync(usuario); |
| | | 200 | | |
| | | 201 | | // Log the audit |
| | 1 | 202 | | await _auditoriaService.LogAuditoriaAsync( |
| | 1 | 203 | | _currentUser.UserId ?? 0, |
| | 1 | 204 | | AccionEnum.ActualizarUsuario, |
| | 1 | 205 | | ContextoEnum.Usuarios, |
| | 1 | 206 | | _currentUser.Host, |
| | 1 | 207 | | entidad: nameof(Usuario), |
| | 1 | 208 | | entidadId: usuarioId, |
| | 1 | 209 | | detalle: new { evento = "asignar_rol", rolId, rolNombre = rol.Nombre }); |
| | | 210 | | |
| | 1 | 211 | | return (true, null); |
| | | 212 | | } |
| | 0 | 213 | | catch (Exception ex) |
| | | 214 | | { |
| | 0 | 215 | | return (false, $"Error al asignar rol: {ex.Message}"); |
| | | 216 | | } |
| | 4 | 217 | | } |
| | | 218 | | |
| | | 219 | | public async Task<(bool Success, string? Error)> RemoverRolAsync(long usuarioId, long rolId) |
| | | 220 | | { |
| | | 221 | | try |
| | | 222 | | { |
| | 3 | 223 | | var usuario = await _usuarioRepository.GetByIdAsync(usuarioId); |
| | 3 | 224 | | if (usuario == null) |
| | | 225 | | { |
| | 1 | 226 | | return (false, "Usuario no encontrado"); |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | // Find the role by ID to avoid tracking issues |
| | 3 | 230 | | var rol = usuario.Roles.FirstOrDefault(r => r.Id == rolId); |
| | 2 | 231 | | if (rol == null) |
| | | 232 | | { |
| | 1 | 233 | | return (false, "El usuario no tiene este rol asignado"); |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | // Remove the role from the collection |
| | 1 | 237 | | usuario.Roles.Remove(rol); |
| | | 238 | | |
| | | 239 | | // Update the usuario (this will persist the role removal) |
| | 1 | 240 | | await _usuarioRepository.UpdateAsync(usuario); |
| | | 241 | | |
| | | 242 | | // Log the audit |
| | 1 | 243 | | await _auditoriaService.LogAuditoriaAsync( |
| | 1 | 244 | | _currentUser.UserId ?? 0, |
| | 1 | 245 | | AccionEnum.ActualizarUsuario, |
| | 1 | 246 | | ContextoEnum.Usuarios, |
| | 1 | 247 | | _currentUser.Host, |
| | 1 | 248 | | entidad: nameof(Usuario), |
| | 1 | 249 | | entidadId: usuarioId, |
| | 1 | 250 | | detalle: new { evento = "remover_rol", rolId, rolNombre = rol.Nombre }); |
| | | 251 | | |
| | 1 | 252 | | return (true, null); |
| | | 253 | | } |
| | 0 | 254 | | catch (Exception ex) |
| | | 255 | | { |
| | 0 | 256 | | return (false, $"Error al remover rol: {ex.Message}"); |
| | | 257 | | } |
| | 3 | 258 | | } |
| | | 259 | | |
| | | 260 | | public async Task DeleteAsync(long id) |
| | | 261 | | { |
| | 1 | 262 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.ActualizarUsuario, ContextoEnum.U |
| | 1 | 263 | | await _usuarioRepository.DeleteAsync(id); |
| | 1 | 264 | | } |
| | | 265 | | } |
| | | 266 | | |