TFS_ANTIGUO/TPAtesa_CuentasCobrar/CuentasCobrar.API/Controllers/UsuarioController.cs

364 lines
14 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
/// <summary>
/// Obtiene todos los usuarios
/// </summary>
/// <returns>
/// Retorna todos los usuarios de la base de datos
/// </returns>
[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable<UsuarioDTO>))]
[ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))]
[ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))]
[HttpGet("obtenerTodos/"), Authorize(Roles = "ADMINISTRADOR")]
public async Task<IActionResult> Get()
{
try
{
var usuarios = await _UsuarioRepo.Get();
if (usuarios == null)
{
throw new BadRequestException("Hubo un problema al obtener los usuarios");
}
var UsuariosDto = _mapper.Map<IEnumerable<UsuarioDTO>>(usuarios);
return Ok(UsuariosDto);
}
catch (Exception ex)
{
if (ex.GetType() != typeof(BadRequestException))
{
throw new InternalErrorException("Hubo un problema en el servidor");
}
else
{
throw;
}
}
}
/// <summary>
        /// Obtiene los usuarios aplicando los filtros de paginación
        /// </summary>
        /// <returns>
        /// Retorna los usuarios de la base de datos paginados
        /// </returns>
[ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable<UsuarioDTO>))]
[ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))]
[ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))]
[HttpGet, Authorize(Roles = "ADMINISTRADOR")]
public async Task<IActionResult> Get([FromQuery] PaginacionQueryFilter filters)
{
try
{
int NumeroDePagina = _configuration.GetValue<int>("PaginationDefaultConfig:NumeroDePagina");
int RegistrosPorPagina = _configuration.GetValue<int>("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<IEnumerable<UsuarioDTO>>(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;
}
}
}
/// <summary>
/// Obtiene el usuario especificado por su id
/// </summary>
/// <param name="idUsuario"></param>
/// <returns>Retorna los datos del usuario especificado</returns>
[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<IActionResult> Get(string idUsuario)
{
try
{
var usuario = await _UsuarioRepo.Get(idUsuario);
if (usuario == null)
{
throw new BadRequestException("El usuario no existe");
}
var UsuarioDto = _mapper.Map<UsuarioDTO>(usuario);
return Ok(UsuarioDto);
}
catch (Exception ex)
{
if (ex.GetType() != typeof(BadRequestException))
{
throw new InternalErrorException("Hubo un problema en el servidor");
}
else
{
throw;
}
}
}
/// <summary>
/// Agrega el usuario especificado por su id
/// </summary>
/// <param name="usuarioDto"></param>
[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<IActionResult> Post(UsuarioDTO usuarioDto)
{
try
{
var usuario = _mapper.Map<Usuario>(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;
}
}
}
/// <summary>
/// Actualiza el usuario especificado por su id
/// </summary>
/// <param name="idUsuario"></param>
/// <param name="usuarioDto"></param>
[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<IActionResult> 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<Usuario>(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;
}
}
}
/// <summary>
/// Elimina el usuario especificado por su id
/// </summary>
/// <param name="idUsuario"></param>
[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<IActionResult> 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;
}
}
}
/// <summary>
/// Crea un token para un usuario
/// </summary>
/// <param name="correoUsuario"></param>
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))]
[ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))]
[HttpGet("GenerarToken/{correoUsuario}")]
public async Task<IActionResult> 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<string> 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<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier,usuario.IdUsuario),
new Claim(ClaimTypes.Name,usuario.Nombre),
};
List<RolDeUsuario> 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
}
}