153 lines
6.8 KiB
C#
153 lines
6.8 KiB
C#
|
|
using GestionIntegral.Api.Dtos.Usuarios;
|
||
|
|
using GestionIntegral.Api.Services.Usuarios;
|
||
|
|
using Microsoft.AspNetCore.Authorization;
|
||
|
|
using Microsoft.AspNetCore.Mvc;
|
||
|
|
using Microsoft.Extensions.Logging;
|
||
|
|
using System;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using System.Security.Claims;
|
||
|
|
using System.Threading.Tasks;
|
||
|
|
|
||
|
|
namespace GestionIntegral.Api.Controllers.Usuarios
|
||
|
|
{
|
||
|
|
[Route("api/[controller]")] // Ruta base: /api/permisos
|
||
|
|
[ApiController]
|
||
|
|
[Authorize(Roles = "SuperAdmin")] // Solo SuperAdmin puede gestionar la definición de permisos
|
||
|
|
public class PermisosController : ControllerBase
|
||
|
|
{
|
||
|
|
private readonly IPermisoService _permisoService;
|
||
|
|
private readonly ILogger<PermisosController> _logger;
|
||
|
|
|
||
|
|
public PermisosController(IPermisoService permisoService, ILogger<PermisosController> logger)
|
||
|
|
{
|
||
|
|
_permisoService = permisoService ?? throw new ArgumentNullException(nameof(permisoService));
|
||
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||
|
|
}
|
||
|
|
|
||
|
|
// Helper para User ID (aunque en SuperAdmin puede no ser tan crítico para auditoría de *definición* de permisos)
|
||
|
|
private int? GetCurrentUserId()
|
||
|
|
{
|
||
|
|
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||
|
|
if (int.TryParse(userIdClaim, out int userId)) return userId;
|
||
|
|
_logger.LogWarning("No se pudo obtener el UserId del token JWT en PermisosController.");
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
// GET: api/permisos
|
||
|
|
[HttpGet]
|
||
|
|
[ProducesResponseType(typeof(IEnumerable<PermisoDto>), StatusCodes.Status200OK)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||
|
|
public async Task<IActionResult> GetAllPermisos([FromQuery] string? modulo, [FromQuery] string? codAcc)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var permisos = await _permisoService.ObtenerTodosAsync(modulo, codAcc);
|
||
|
|
return Ok(permisos);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al obtener todos los Permisos. Filtros: Modulo={Modulo}, CodAcc={CodAcc}", modulo, codAcc);
|
||
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// GET: api/permisos/{id}
|
||
|
|
[HttpGet("{id:int}", Name = "GetPermisoById")]
|
||
|
|
[ProducesResponseType(typeof(PermisoDto), StatusCodes.Status200OK)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||
|
|
public async Task<IActionResult> GetPermisoById(int id)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var permiso = await _permisoService.ObtenerPorIdAsync(id);
|
||
|
|
if (permiso == null) return NotFound(new { message = $"Permiso con ID {id} no encontrado." });
|
||
|
|
return Ok(permiso);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al obtener Permiso por ID: {Id}", id);
|
||
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// POST: api/permisos
|
||
|
|
[HttpPost]
|
||
|
|
[ProducesResponseType(typeof(PermisoDto), StatusCodes.Status201Created)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||
|
|
public async Task<IActionResult> CreatePermiso([FromBody] CreatePermisoDto createDto)
|
||
|
|
{
|
||
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||
|
|
var idUsuario = GetCurrentUserId() ?? 0; // SuperAdmin puede no necesitar auditoría estricta aquí
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var (permisoCreado, error) = await _permisoService.CrearAsync(createDto, idUsuario);
|
||
|
|
if (error != null) return BadRequest(new { message = error });
|
||
|
|
if (permisoCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el permiso.");
|
||
|
|
return CreatedAtRoute("GetPermisoById", new { id = permisoCreado.Id }, permisoCreado);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al crear Permiso. CodAcc: {CodAcc}, UserID: {UsuarioId}", createDto.CodAcc, idUsuario);
|
||
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// PUT: api/permisos/{id}
|
||
|
|
[HttpPut("{id:int}")]
|
||
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||
|
|
public async Task<IActionResult> UpdatePermiso(int id, [FromBody] UpdatePermisoDto updateDto)
|
||
|
|
{
|
||
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||
|
|
var idUsuario = GetCurrentUserId() ?? 0;
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var (exito, error) = await _permisoService.ActualizarAsync(id, updateDto, idUsuario);
|
||
|
|
if (!exito)
|
||
|
|
{
|
||
|
|
if (error == "Permiso no encontrado.") return NotFound(new { message = error });
|
||
|
|
return BadRequest(new { message = error });
|
||
|
|
}
|
||
|
|
return NoContent();
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al actualizar Permiso ID: {Id}, UserID: {UsuarioId}", id, idUsuario);
|
||
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// DELETE: api/permisos/{id}
|
||
|
|
[HttpDelete("{id:int}")]
|
||
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||
|
|
public async Task<IActionResult> DeletePermiso(int id)
|
||
|
|
{
|
||
|
|
var idUsuario = GetCurrentUserId() ?? 0;
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var (exito, error) = await _permisoService.EliminarAsync(id, idUsuario);
|
||
|
|
if (!exito)
|
||
|
|
{
|
||
|
|
if (error == "Permiso no encontrado.") return NotFound(new { message = error });
|
||
|
|
return BadRequest(new { message = error }); // Ej: "En uso"
|
||
|
|
}
|
||
|
|
return NoContent();
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al eliminar Permiso ID: {Id}, UserID: {UsuarioId}", id, idUsuario);
|
||
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|