- Backend API: Autenticación y autorización básicas con JWT implementadas. Cambio de contraseña funcional. Módulo "Tipos de Pago" (CRUD completo) implementado en el backend (Controlador, Servicio, Repositorio) usando Dapper, transacciones y con lógica de historial. Se incluyen permisos en el token JWT. - Frontend React: Estructura base con Vite, TypeScript, MUI. Contexto de autenticación (AuthContext) que maneja el estado del usuario y el token. Página de Login. Modal de Cambio de Contraseña (forzado y opcional). Hook usePermissions para verificar permisos. Página GestionarTiposPagoPage con tabla, paginación, filtro, modal para crear/editar, y menú de acciones, respetando permisos. Layout principal (MainLayout) con navegación por Tabs (funcionalidad básica de navegación). Estructura de enrutamiento (AppRoutes) que maneja rutas públicas, protegidas y anidadas para módulos.
113 lines
4.3 KiB
C#
113 lines
4.3 KiB
C#
using Dapper;
|
|
using GestionIntegral.Api.Models;
|
|
using System.Data;
|
|
|
|
namespace GestionIntegral.Api.Data
|
|
{
|
|
public class AuthRepository : IAuthRepository
|
|
{
|
|
private readonly DbConnectionFactory _connectionFactory;
|
|
private readonly ILogger<AuthRepository> _logger;
|
|
|
|
public AuthRepository(DbConnectionFactory connectionFactory, ILogger<AuthRepository> logger)
|
|
{
|
|
_connectionFactory = connectionFactory;
|
|
_logger = logger;
|
|
|
|
}
|
|
|
|
public async Task<Usuario?> GetUserByUsernameAsync(string username)
|
|
{
|
|
var sql = @"SELECT Id, [User], ClaveHash, ClaveSalt, Habilitada,
|
|
SupAdmin, Nombre, Apellido, IdPerfil, VerLog, DebeCambiarClave
|
|
FROM gral_Usuarios
|
|
WHERE [User] = @Username";
|
|
|
|
try
|
|
{
|
|
using (var connection = _connectionFactory.CreateConnection())
|
|
{
|
|
var user = await connection.QuerySingleOrDefaultAsync<Usuario>(sql, new { Username = username });
|
|
return user;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error fetching user by username: {ex.Message}");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task<Usuario?> GetUserByIdAsync(int userId)
|
|
{
|
|
var sql = @"SELECT Id, [User], ClaveHash, ClaveSalt, Habilitada,
|
|
SupAdmin, Nombre, Apellido, IdPerfil, VerLog, DebeCambiarClave
|
|
FROM gral_Usuarios
|
|
WHERE Id = @UserId";
|
|
try
|
|
{
|
|
using (var connection = _connectionFactory.CreateConnection())
|
|
{
|
|
var user = await connection.QuerySingleOrDefaultAsync<Usuario>(sql, new { UserId = userId });
|
|
Console.WriteLine($"Repo - User {user?.Id} - DebeCambiarClave leído de BD: {user?.DebeCambiarClave}");
|
|
return user;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error fetching user by ID: {ex.Message}");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> UpdatePasswordAsync(int userId, string newHash, string newSalt)
|
|
{
|
|
// Actualiza hash, salt y pone DebeCambiarClave a 0 (false)
|
|
var sql = @"UPDATE dbo.gral_Usuarios
|
|
SET ClaveHash = @HashedPassword, ClaveSalt = @Salt, DebeCambiarClave = 0
|
|
WHERE Id = @UserId";
|
|
|
|
try
|
|
{
|
|
using (var connection = _connectionFactory.CreateConnection())
|
|
{
|
|
var parameters = new
|
|
{
|
|
HashedPassword = newHash,
|
|
Salt = newSalt,
|
|
UserId = userId
|
|
};
|
|
int rowsAffected = await connection.ExecuteAsync(sql, parameters);
|
|
return rowsAffected == 1; // Devuelve true si se actualizó exactamente una fila
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error updating password for user {userId}: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
public async Task<IEnumerable<string>> GetPermisosCodAccByPerfilIdAsync(int idPerfil)
|
|
{
|
|
// Esta consulta es similar a la que tenías en gestion.vb -> verPermisosPerfil
|
|
var sql = @"
|
|
SELECT p.codAcc
|
|
FROM dbo.gral_Perfiles pf
|
|
INNER JOIN dbo.gral_PermisosPerfiles pp ON pf.id = pp.idPerfil
|
|
INNER JOIN dbo.gral_Permisos p ON pp.idPermiso = p.id
|
|
WHERE pf.id = @IdPerfil;";
|
|
try
|
|
{
|
|
using (var connection = _connectionFactory.CreateConnection())
|
|
{
|
|
return await connection.QueryAsync<string>(sql, new { IdPerfil = idPerfil });
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error al obtener códigos de acceso para el perfil ID: {IdPerfil}", idPerfil); // Asumiendo que tienes _logger en AuthRepository
|
|
return Enumerable.Empty<string>();
|
|
}
|
|
}
|
|
}
|
|
} |