239 lines
		
	
	
		
			11 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
		
		
			
		
	
	
			239 lines
		
	
	
		
			11 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/perfiles
 | ||
|  |     [ApiController] | ||
|  |     [Authorize] | ||
|  |     public class PerfilesController : ControllerBase | ||
|  |     { | ||
|  |         private readonly IPerfilService _perfilService; | ||
|  |         private readonly ILogger<PerfilesController> _logger; | ||
|  | 
 | ||
|  |         // Códigos de permiso para Perfiles (PU001-PU004) | ||
|  |         private const string PermisoVer = "PU001"; | ||
|  |         private const string PermisoCrear = "PU002"; | ||
|  |         private const string PermisoModificar = "PU003"; | ||
|  |         private const string PermisoEliminar = "PU003"; | ||
|  |         private const string PermisoAsignar = "PU004"; | ||
|  | 
 | ||
|  |         public PerfilesController(IPerfilService perfilService, ILogger<PerfilesController> logger) | ||
|  |         { | ||
|  |             _perfilService = perfilService ?? throw new ArgumentNullException(nameof(perfilService)); | ||
|  |             _logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
|  |         } | ||
|  | 
 | ||
|  |         private bool TienePermiso(string codAccRequerido) | ||
|  |         { | ||
|  |             if (User.IsInRole("SuperAdmin")) return true; | ||
|  |             return User.HasClaim(c => c.Type == "permission" && c.Value == codAccRequerido); | ||
|  |         } | ||
|  | 
 | ||
|  |         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 PerfilesController."); | ||
|  |             return null; | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/perfiles | ||
|  |         [HttpGet] | ||
|  |         [ProducesResponseType(typeof(IEnumerable<PerfilDto>), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         public async Task<IActionResult> GetAllPerfiles([FromQuery] string? nombre) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoVer)) return Forbid(); | ||
|  |             try | ||
|  |             { | ||
|  |                 var perfiles = await _perfilService.ObtenerTodosAsync(nombre); | ||
|  |                 return Ok(perfiles); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener todos los Perfiles. Filtro: {Nombre}", nombre); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/perfiles/{id} | ||
|  |         [HttpGet("{id:int}", Name = "GetPerfilById")] | ||
|  |         [ProducesResponseType(typeof(PerfilDto), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         public async Task<IActionResult> GetPerfilById(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoVer)) return Forbid(); | ||
|  |             try | ||
|  |             { | ||
|  |                 var perfil = await _perfilService.ObtenerPorIdAsync(id); | ||
|  |                 if (perfil == null) return NotFound(new { message = $"Perfil con ID {id} no encontrado." }); | ||
|  |                 return Ok(perfil); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener Perfil por ID: {Id}", id); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // POST: api/perfiles | ||
|  |         [HttpPost] | ||
|  |         [ProducesResponseType(typeof(PerfilDto), StatusCodes.Status201Created)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         public async Task<IActionResult> CreatePerfil([FromBody] CreatePerfilDto createDto) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoCrear)) return Forbid(); | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  |             var idUsuario = GetCurrentUserId(); // Necesario para auditoría si se implementa | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (perfilCreado, error) = await _perfilService.CrearAsync(createDto, idUsuario.Value); | ||
|  |                 if (error != null) return BadRequest(new { message = error }); | ||
|  |                 if (perfilCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el perfil."); | ||
|  |                 return CreatedAtRoute("GetPerfilById", new { id = perfilCreado.Id }, perfilCreado); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al crear Perfil. Nombre: {Nombre}, UserID: {UsuarioId}", createDto.NombrePerfil, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // PUT: api/perfiles/{id} | ||
|  |         [HttpPut("{id:int}")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         public async Task<IActionResult> UpdatePerfil(int id, [FromBody] UpdatePerfilDto updateDto) | ||
|  |         { | ||
|  |             // Asumo que PU003 es para modificar el perfil (nombre/descripción) | ||
|  |             if (!TienePermiso(PermisoModificar)) return Forbid(); | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _perfilService.ActualizarAsync(id, updateDto, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Perfil no encontrado.") return NotFound(new { message = error }); | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al actualizar Perfil ID: {Id}, UserID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // DELETE: api/perfiles/{id} | ||
|  |         [HttpDelete("{id:int}")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         public async Task<IActionResult> DeletePerfil(int id) | ||
|  |         { | ||
|  |             // El Excel dice PU003 para eliminar. | ||
|  |             if (!TienePermiso(PermisoEliminar)) return Forbid(); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _perfilService.EliminarAsync(id, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Perfil no encontrado.") return NotFound(new { message = error }); | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al eliminar Perfil ID: {Id}, UserID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  |         // GET: api/perfiles/{idPerfil}/permisos | ||
|  |         [HttpGet("{idPerfil:int}/permisos")] | ||
|  |         [ProducesResponseType(typeof(IEnumerable<PermisoAsignadoDto>), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] // Si no tiene permiso PU001 o PU004 | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetPermisosPorPerfil(int idPerfil) | ||
|  |         { | ||
|  |             // Para ver los permisos de un perfil, podría ser PU001 (ver perfil) o PU004 (asignar) | ||
|  |             if (!TienePermiso(PermisoVer) && !TienePermiso(PermisoAsignar)) return Forbid(); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var perfil = await _perfilService.ObtenerPorIdAsync(idPerfil); // Verificar si el perfil existe | ||
|  |                 if (perfil == null) | ||
|  |                 { | ||
|  |                     return NotFound(new { message = $"Perfil con ID {idPerfil} no encontrado." }); | ||
|  |                 } | ||
|  | 
 | ||
|  |                 var permisos = await _perfilService.ObtenerPermisosAsignadosAsync(idPerfil); | ||
|  |                 return Ok(permisos); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener permisos para el Perfil ID: {IdPerfil}", idPerfil); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener los permisos del perfil."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // PUT: api/perfiles/{idPerfil}/permisos | ||
|  |         [HttpPut("{idPerfil:int}/permisos")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] // Si no tiene permiso PU004 | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> UpdatePermisosDelPerfil(int idPerfil, [FromBody] ActualizarPermisosPerfilRequestDto request) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoAsignar)) return Forbid(); | ||
|  | 
 | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  | 
 | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _perfilService.ActualizarPermisosAsignadosAsync(idPerfil, request, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Perfil no encontrado.") return NotFound(new { message = error }); | ||
|  |                     // Otros errores como "permiso inválido" | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al actualizar permisos para Perfil ID: {IdPerfil} por Usuario ID: {UsuarioId}", idPerfil, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al actualizar los permisos del perfil."); | ||
|  |             } | ||
|  |         } | ||
|  |     } | ||
|  | } |