import jwt from "jsonwebtoken"; import dotenv from 'dotenv'; import { dbasistente } from "../../db.js"; // Configuración de variables de entorno dotenv.config(); async function autentificacion(req, res) { try { let username, password; // 1. Intentar obtener de cabecera Authorization (Basic Auth) const authHeader = req.headers.authorization; if (authHeader && authHeader.startsWith('Basic ')) { const base64Credentials = authHeader.split(' ')[1]; const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii'); [username, password] = credentials.split(':'); } // 2. Si no hay cabecera, intentar obtener del body (JSON) else if (req.body.username && req.body.password) { username = req.body.username; password = req.body.password; } // Validar que tengamos credenciales if (!username || !password) { return res.status(401).json({ error: "Credenciales faltantes", mensaje: "Se requiere autenticación básica o un cuerpo JSON con {username, password}" }); } // Consulta a la nueva tabla soporte_copy en dbasistente const [db_user] = await dbasistente.query( "SELECT CODIGO_SOP, NOMBRE_SOP, USUARIO_SOP, NIVEL_SOP FROM soporte_copy WHERE CORREO_SOP = ? AND CLAVE_SOP = ? AND ESTADO_SOP = 'V'", { replacements: [username, password] } ); // Verificar si se encontró el usuario if (db_user.length === 0) { return res.status(401).json({ error: "Credenciales inválidas", mensaje: "Usuario o contraseña incorrectos" }); } const userRecord = db_user[0]; // Determinar privilegio basado en NIVEL_SOP // NIVEL_SOP 1 = solo lectura (READ), 4 = admin (CRUD) let privilegio = "READ"; if (userRecord.NIVEL_SOP === 4 || userRecord.NIVEL_SOP === '4') { privilegio = "CRUD"; } // Verificar clave secreta JWT if (!process.env.SECRET) { throw new Error("La clave secreta JWT no está configurada"); } // Crear payload del token const payload = { id: userRecord.CODIGO_SOP, username: userRecord.USUARIO_SOP, nombre: userRecord.NOMBRE_SOP, privilegio: privilegio }; // Generar token JWT const token = jwt.sign( payload, process.env.SECRET, { expiresIn: '3h' } ); // Respuesta exitosa según el formato solicitado return res.status(200).json({ success: true, message: "Login exitoso", token: token, user: { id: userRecord.CODIGO_SOP, username: userRecord.USUARIO_SOP, nombre: userRecord.NOMBRE_SOP, privilegio: privilegio } }); } catch (error) { console.error("Error en autenticación:", error); // Error genérico return res.status(500).json({ error: "Error interno del servidor", detalles: process.env.NODE_ENV === 'development' ? error.message : undefined }); } } export { autentificacion };