using AutoMapper; using CuentasCobrar.CORE.DTOs; using CuentasCobrar.CORE.Entities; using CuentasCobrar.CORE.Exceptions; using CuentasCobrar.CORE.Interfaces; using CuentasCobrar.CORE.QueryFilters; using CuentasCobrar.CORE.ResponseObjects; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using System.IdentityModel.Tokens.Jwt; using System.Net; using System.Security.Claims; namespace CuentasCobrar.API.Controllers { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class UsuarioController : ControllerBase { private readonly IUsuarioRepo _UsuarioRepo; private readonly IRolDeUsuarioRepo _rolDeUsuarioRepo; private readonly IMapper _mapper; private readonly IConfiguration _configuration; public UsuarioController(IUsuarioRepo usuarioRepo, IRolDeUsuarioRepo rolDeUsuarioRepo, IMapper mapper, IConfiguration configuration) { _UsuarioRepo = usuarioRepo; _rolDeUsuarioRepo = rolDeUsuarioRepo; _mapper = mapper; _configuration = configuration; } /// /// Obtiene todos los usuarios /// /// /// Retorna todos los usuarios de la base de datos /// [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet("obtenerTodos/"), Authorize(Roles = "ADMINISTRADOR")] public async Task Get() { try { var usuarios = await _UsuarioRepo.Get(); if (usuarios == null) { throw new BadRequestException("Hubo un problema al obtener los usuarios"); } var UsuariosDto = _mapper.Map>(usuarios); return Ok(UsuariosDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Obtiene los usuarios aplicando los filtros de paginación         ///         ///         /// Retorna los usuarios de la base de datos paginados         /// [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet, Authorize(Roles = "ADMINISTRADOR")] public async Task Get([FromQuery] PaginacionQueryFilter filters) { try { int NumeroDePagina = _configuration.GetValue("PaginationDefaultConfig:NumeroDePagina"); int RegistrosPorPagina = _configuration.GetValue("PaginationDefaultConfig:RegistrosPorPagina"); filters.NumeroDePagina = filters.NumeroDePagina == 0 ? NumeroDePagina : filters.NumeroDePagina; filters.RegistrosPorPagina = filters.RegistrosPorPagina == 0 ? RegistrosPorPagina : filters.RegistrosPorPagina; var usuarios = await _UsuarioRepo.Get(filters); if (usuarios == null) { throw new BadRequestException("Hubo un problema al obtener los usuarios"); } var usuariosDto = _mapper.Map>(usuarios); var metadata = new { usuarios.NumeroDePagina, usuarios.RegistrosTotales, usuarios.RegistrosPorPagina, usuarios.PaginasTotales, usuarios.HayPaginaSiguiente, usuarios.HayPaginaAnterior, usuarios.NumeroPaginaSiguiente, usuarios.NumeroPaginaAnterior }; Response.Headers.Add("Pagination-Info", JsonConvert.SerializeObject(metadata)); return Ok(usuariosDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } /// /// Obtiene el usuario especificado por su id /// /// /// Retorna los datos del usuario especificado [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(UsuarioDTO))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet("{idUsuario}"), Authorize(Roles = "ADMINISTRADOR")] public async Task Get(string idUsuario) { try { var usuario = await _UsuarioRepo.Get(idUsuario); if (usuario == null) { throw new BadRequestException("El usuario no existe"); } var UsuarioDto = _mapper.Map(usuario); return Ok(UsuarioDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } /// /// Agrega el usuario especificado por su id /// /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpPost, Authorize(Roles = "ADMINISTRADOR")] public async Task Post(UsuarioDTO usuarioDto) { try { var usuario = _mapper.Map(usuarioDto); Usuario? usuarioExistenteId = await _UsuarioRepo.Get(usuario.IdUsuario); Usuario? usuarioExistenteCorreo = await _UsuarioRepo.GetUsuarioPorCorreo(usuario.Correo); if (usuarioExistenteId != null || usuarioExistenteCorreo != null) { throw new BadRequestException("El usuario ingresado ya existe"); } bool agregado = await _UsuarioRepo.Post(usuario); if (agregado == false) { throw new BadRequestException("Hubo un problema al agregar el usuario"); } return Ok(agregado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } /// /// Actualiza el usuario especificado por su id /// /// /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpPut("{idUsuario}"), Authorize(Roles = "ADMINISTRADOR")] public async Task Put(string idUsuario, UsuarioDTO usuarioDto) { try { var usuarioTemp = await _UsuarioRepo.Get(idUsuario); if (usuarioTemp == null) { throw new BadRequestException("El usuario a modificar no existe"); } var usuario = _mapper.Map(usuarioDto); usuario.IdUsuario = idUsuario; bool modificado = await _UsuarioRepo.Put(usuario); if (modificado == false) { throw new BadRequestException("Hubo un problema al modificar el usuario"); } return Ok(modificado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } /// /// Elimina el usuario especificado por su id /// /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpDelete("{idUsuario}"), Authorize(Roles = "ADMINISTRADOR")] public async Task Delete(string idUsuario) { try { var usuarioTemp = await _UsuarioRepo.Get(idUsuario); if (usuarioTemp == null) { throw new BadRequestException("El usuario a eliminar no existe"); } bool eliminado = await _UsuarioRepo.Delete(idUsuario); if (eliminado == false) { throw new BadRequestException("Hubo un problema al eliminar el usuario"); } return Ok(eliminado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } /// /// Crea un token para un usuario /// /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet("GenerarToken/{correoUsuario}")] public async Task CreateToken(string correoUsuario) { try { string jkt = await CrearToken(correoUsuario); return Ok(jkt); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } #region Metodos privados //este metodo genera los tokens private async Task CrearToken(string correo) { try { var usuario = await _UsuarioRepo.GetUsuarioPorCorreo(correo); if (usuario == null) { throw new BadRequestException($"El usuario {correo} no está registrado en la aplicación \n Por favor contacte con soporte técnico"); } List claims = new List { new Claim(ClaimTypes.NameIdentifier,usuario.IdUsuario), new Claim(ClaimTypes.Name,usuario.Nombre), }; List rolesDeUsuario = await _rolDeUsuarioRepo.Get(usuario.IdUsuario); if (rolesDeUsuario.Count == 0) { throw new BadRequestException("El usuario no está asociado a un rol"); } foreach (RolDeUsuario rolDeUsuario in rolesDeUsuario) { claims.Add(new Claim(ClaimTypes.Role, rolDeUsuario.DescripcionDeRol)); } var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes( _configuration.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var Token = new JwtSecurityToken( claims: claims, expires: DateTime.Now.AddDays(1), signingCredentials: creds); var jwt = new JwtSecurityTokenHandler().WriteToken(Token); return jwt; } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } #endregion } }