808 lines
36 KiB
JavaScript
808 lines
36 KiB
JavaScript
require('dotenv').config();
|
|
const express = require('express');
|
|
const nunjucks = require('nunjucks');
|
|
process.on('uncaughtException', (err) => {
|
|
console.error('Uncaught Exception:', err);
|
|
});
|
|
process.on('unhandledRejection', (reason, promise) => {
|
|
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
});
|
|
|
|
try {
|
|
require('nunjucks/src/jinja-compat').call(nunjucks);
|
|
} catch (e) {
|
|
console.warn('Jinja compat loader notice:', e.message);
|
|
}
|
|
const nunjucksRuntime = require('nunjucks/src/runtime');
|
|
const origMemberLookup = nunjucksRuntime.memberLookup;
|
|
nunjucksRuntime.memberLookup = function(obj, val) {
|
|
if (obj && val === 'items' && Array.isArray(obj.items)) {
|
|
return obj.items;
|
|
}
|
|
if (obj && val === 'get' && typeof obj.get !== 'function') {
|
|
return function(key, defaultVal) {
|
|
return (obj[key] !== undefined && obj[key] !== null) ? obj[key] : defaultVal;
|
|
};
|
|
}
|
|
const res = origMemberLookup(obj, val);
|
|
if (typeof res === 'function' && obj && typeof obj[val] === 'function') {
|
|
Object.assign(res, obj[val]);
|
|
}
|
|
return res;
|
|
};
|
|
const cookieParser = require('cookie-parser');
|
|
const path = require('path');
|
|
const axios = require('axios');
|
|
const helmet = require('helmet');
|
|
const rateLimit = require('express-rate-limit');
|
|
|
|
const app = express();
|
|
const port = process.env.PORT || 3000;
|
|
|
|
app.disable('x-powered-by');
|
|
app.set('trust proxy', 1);
|
|
|
|
// Blindaje HTTP con Helmet (compatible con despliegues directos por IP y proxies HTTPS)
|
|
app.use(helmet({
|
|
contentSecurityPolicy: false,
|
|
crossOriginEmbedderPolicy: false,
|
|
crossOriginOpenerPolicy: false,
|
|
originAgentCluster: false
|
|
}));
|
|
|
|
// Rate Limiting para protección contra ataques de fuerza bruta y abuso
|
|
const authLimiter = rateLimit({
|
|
windowMs: 15 * 60 * 1000,
|
|
max: 60,
|
|
message: 'Demasiados intentos de autenticación. Por favor intente nuevamente en 15 minutos.',
|
|
standardHeaders: true,
|
|
legacyHeaders: false
|
|
});
|
|
const generalLimiter = rateLimit({
|
|
windowMs: 60 * 1000,
|
|
max: 180,
|
|
standardHeaders: true,
|
|
legacyHeaders: false
|
|
});
|
|
app.post('/auth/login', authLimiter);
|
|
app.post('/auth/moodle', authLimiter);
|
|
app.use('/api', generalLimiter);
|
|
|
|
// Configuración de middlewares con soporte para importaciones masivas y payloads extensos
|
|
app.use(express.json({ limit: '50mb' }));
|
|
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
|
|
app.use(cookieParser());
|
|
|
|
// Configuración de archivos estáticos
|
|
app.use(express.static(path.join(__dirname, '../public')));
|
|
app.use('/static', express.static(path.join(__dirname, '../public')));
|
|
|
|
// Configuración de Nunjucks
|
|
const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
|
autoescape: true,
|
|
express: app,
|
|
watch: process.env.NODE_ENV !== 'production'
|
|
});
|
|
|
|
// Versiones institucionales del sistema
|
|
const APP_VERSION = '3.5.5';
|
|
const FRONTEND_VERSION = '3.5.5';
|
|
const BACKEND_VERSION = '3.5.5';
|
|
|
|
env.addGlobal('app_version', APP_VERSION);
|
|
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
|
env.addGlobal('backend_version', BACKEND_VERSION);
|
|
|
|
// Nunjucks custom filters/helpers
|
|
env.addFilter('get', function(obj, key, defaultVal) {
|
|
if (!obj) return defaultVal;
|
|
return obj[key] !== undefined ? obj[key] : defaultVal;
|
|
});
|
|
|
|
env.addFilter('min', function(arr) {
|
|
if (Array.isArray(arr)) return Math.min(...arr);
|
|
return arr;
|
|
});
|
|
|
|
env.addFilter('max', function(arr) {
|
|
if (Array.isArray(arr)) return Math.max(...arr);
|
|
return arr;
|
|
});
|
|
|
|
env.addFilter('round', function(val, precision = 0) {
|
|
if (val === undefined || val === null) return 0;
|
|
const factor = Math.pow(10, precision);
|
|
return Math.round(val * factor) / factor;
|
|
});
|
|
|
|
env.addFilter('format', function(str, ...args) {
|
|
if (!str) return '';
|
|
let i = 0;
|
|
return String(str).replace(/%0?(\d+)?d|%s/g, (match, pad) => {
|
|
let val = args[i++];
|
|
if (pad && typeof val === 'number') {
|
|
return String(val).padStart(parseInt(pad, 10), '0');
|
|
}
|
|
return val !== undefined ? String(val) : match;
|
|
});
|
|
});
|
|
|
|
const formatDateHelper = function(d, fmt) {
|
|
if (!d) return '';
|
|
let str = String(d);
|
|
let datePart = str.includes('T') ? str.split('T')[0] : (str.includes(' ') ? str.split(' ')[0] : str);
|
|
if (datePart.match(/^\d{4}-\d{2}-\d{2}$/)) {
|
|
const [y, m, day] = datePart.split('-');
|
|
const year = parseInt(y, 10);
|
|
const month = parseInt(m, 10);
|
|
const dayNum = parseInt(day, 10);
|
|
const dObj = new Date(year, month - 1, dayNum);
|
|
const daysNames = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
|
|
const monthsNames = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
|
|
const dayName = daysNames[dObj.getDay()] || '';
|
|
const monthName = monthsNames[month - 1] || '';
|
|
const dayPad = String(dayNum).padStart(2, '0');
|
|
const monthPad = String(month).padStart(2, '0');
|
|
|
|
if (fmt === 'long' || fmt === 'human') {
|
|
return `${dayName} ${dayPad}/${monthPad}/${year}`;
|
|
}
|
|
if (fmt === 'full') {
|
|
return `${dayName}, ${dayPad} de ${monthName} de ${year}`;
|
|
}
|
|
return `${dayPad}/${monthPad}/${year}`;
|
|
}
|
|
return datePart;
|
|
};
|
|
|
|
const formatDateTimeHelper = function(d, fmt) {
|
|
if (!d) return '';
|
|
let str = String(d);
|
|
let datePart = formatDateHelper(str);
|
|
let timePart = '';
|
|
if (str.includes('T')) {
|
|
timePart = str.split('T')[1].substring(0, 5) + ' hs';
|
|
} else if (str.includes(' ')) {
|
|
timePart = str.split(' ')[1].substring(0, 5) + ' hs';
|
|
}
|
|
return timePart ? `${datePart} ${timePart}` : datePart;
|
|
};
|
|
|
|
const formatTimeCleanHelper = function(d) {
|
|
if (!d) return '';
|
|
let str = String(d);
|
|
if (str.includes('T')) return str.split('T')[1].substring(0, 5) + ' hs';
|
|
if (str.includes(' ')) return str.split(' ')[1].substring(0, 5) + ' hs';
|
|
if (str.match(/^\d{2}:\d{2}/)) return str.substring(0, 5) + ' hs';
|
|
return str;
|
|
};
|
|
|
|
const formatTimeRangeHelper = function(start, end) {
|
|
if (!start) return '';
|
|
let s = String(start);
|
|
let e = String(end || '');
|
|
let st = s.includes('T') ? s.split('T')[1].substring(0, 5) : (s.includes(' ') ? s.split(' ')[1].substring(0, 5) : s.substring(0, 5));
|
|
let et = e.includes('T') ? e.split('T')[1].substring(0, 5) : (e.includes(' ') ? e.split(' ')[1].substring(0, 5) : e.substring(0, 5));
|
|
return et ? `${st} - ${et} hs` : `${st} hs`;
|
|
};
|
|
|
|
env.addGlobal('format_date', formatDateHelper);
|
|
env.addGlobal('format_datetime', formatDateTimeHelper);
|
|
env.addGlobal('format_time', formatTimeCleanHelper);
|
|
env.addGlobal('format_time_range', formatTimeRangeHelper);
|
|
|
|
env.addFilter('format_date', formatDateHelper);
|
|
env.addFilter('format_datetime', formatDateTimeHelper);
|
|
env.addFilter('format_date_human', function(d) { return formatDateHelper(d, 'human'); });
|
|
env.addFilter('format_time', formatTimeCleanHelper);
|
|
env.addFilter('format_time_range', formatTimeRangeHelper);
|
|
|
|
env.addFilter('tojson', function(val) {
|
|
return JSON.stringify(val !== undefined ? val : null);
|
|
});
|
|
|
|
env.addFilter('sum', function(arr, attribute) {
|
|
if (!Array.isArray(arr)) return 0;
|
|
return arr.reduce((acc, item) => {
|
|
let val = 0;
|
|
if (attribute && typeof item === 'object' && item !== null) {
|
|
val = item[attribute] || 0;
|
|
} else {
|
|
val = Number(item) || 0;
|
|
}
|
|
return acc + Number(val);
|
|
}, 0);
|
|
});
|
|
|
|
const translateHelper = function(s) {
|
|
return s || '';
|
|
};
|
|
|
|
const urlForHelper = function(endpoint, params = {}) {
|
|
if (!endpoint) return '#';
|
|
const parts = endpoint.split('.');
|
|
const blueprint = parts.length > 1 ? parts[0] : '';
|
|
const action = parts.length > 1 ? parts[1] : parts[0];
|
|
let pathStr = `/${blueprint}/${action}`.replace(/^\/\//, '/').replace(/\/$/, '');
|
|
if (params && typeof params === 'object') {
|
|
const q = [];
|
|
for (const [k, v] of Object.entries(params)) {
|
|
if (k === 'id' || k === 'pk') {
|
|
pathStr += `/${v}`;
|
|
} else {
|
|
q.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
|
|
}
|
|
}
|
|
if (q.length > 0) {
|
|
pathStr += (pathStr.includes('?') ? '&' : '?') + q.join('&');
|
|
}
|
|
}
|
|
return pathStr;
|
|
};
|
|
|
|
env.addGlobal('_', translateHelper);
|
|
env.addFilter('_', translateHelper);
|
|
env.addGlobal('url_for', urlForHelper);
|
|
env.addFilter('url_for', urlForHelper);
|
|
|
|
app.set('view engine', 'html');
|
|
|
|
const { buildUserSession } = require('./middlewares/authMiddleware');
|
|
|
|
// Helper para extraer usuario de cookie si existe
|
|
app.use((req, res, next) => {
|
|
const token = req.cookies.auth_token;
|
|
let user = buildUserSession({ role: 'admin', name: 'System', email: 'admin@edu-space.com' });
|
|
user.is_authenticated = Boolean(token);
|
|
|
|
if (token) {
|
|
try {
|
|
const decoded = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString('utf8'));
|
|
user = buildUserSession(decoded);
|
|
} catch (e) {}
|
|
}
|
|
let isImpersonating = false;
|
|
let impersonatedUser = null;
|
|
if (user.is_admin() && req.cookies.impersonate_user_id) {
|
|
isImpersonating = true;
|
|
const targetId = req.cookies.impersonate_user_id;
|
|
try {
|
|
if (req.cookies.impersonate_user_data) {
|
|
impersonatedUser = JSON.parse(req.cookies.impersonate_user_data);
|
|
}
|
|
} catch (e) {}
|
|
if (!impersonatedUser) {
|
|
impersonatedUser = { id: targetId, name: `Usuario #${targetId}`, role: 'usuario' };
|
|
}
|
|
}
|
|
|
|
req.user = user;
|
|
res.locals.user = user;
|
|
res.locals.current_user = user;
|
|
res.locals.role = user.role;
|
|
res.locals.is_impersonating = isImpersonating;
|
|
res.locals.impersonated_user = impersonatedUser;
|
|
res.locals.session = { get: (k, d) => d };
|
|
res.locals.occupancy_metrics = { get: (k, d) => d };
|
|
res.locals.app_version = APP_VERSION;
|
|
res.locals.frontend_version = FRONTEND_VERSION;
|
|
res.locals.backend_version = BACKEND_VERSION;
|
|
next();
|
|
});
|
|
|
|
// Endpoint público de verificación de versiones
|
|
app.get('/version', (req, res) => {
|
|
res.json({
|
|
app: APP_VERSION,
|
|
frontend: FRONTEND_VERSION,
|
|
backend: BACKEND_VERSION,
|
|
status: 'ok'
|
|
});
|
|
});
|
|
|
|
// Rutas Principales
|
|
const indexRoutes = require('./routes/index');
|
|
const authRoutes = require('./routes/auth');
|
|
const dashboardRoutes = require('./routes/dashboard');
|
|
const classroomsRoutes = require('./routes/classrooms');
|
|
const scheduleRoutes = require('./routes/schedule');
|
|
const buildingsRoutes = require('./routes/buildings');
|
|
const adminRoutes = require('./routes/admin');
|
|
const mySubjectsRoutes = require('./routes/my_subjects');
|
|
|
|
// Proxy transparente hacia la API REST de Flask para llamadas AJAX frontend
|
|
app.use('/api/v1', async (req, res) => {
|
|
try {
|
|
const token = req.cookies.auth_token;
|
|
const targetUrl = `${process.env.FLASK_API_URL || 'http://localhost:5000/api/v1'}${req.url}`;
|
|
const headers = { ...req.headers };
|
|
delete headers.host;
|
|
delete headers['content-length'];
|
|
if (token && !headers.authorization) {
|
|
headers.authorization = `Bearer ${token}`;
|
|
}
|
|
const resp = await axios({
|
|
method: req.method,
|
|
url: targetUrl,
|
|
data: req.body,
|
|
params: req.query,
|
|
headers,
|
|
validateStatus: () => true
|
|
});
|
|
return res.status(resp.status).json(resp.data);
|
|
} catch (err) {
|
|
console.error('API v1 proxy error:', err.message);
|
|
return res.status(500).json({ error: 'ProxyError', message: 'Error de comunicación con el backend API: ' + err.message });
|
|
}
|
|
});
|
|
|
|
app.use('/', indexRoutes);
|
|
app.use('/auth', authRoutes);
|
|
app.use('/dashboard', dashboardRoutes);
|
|
app.use('/classrooms', classroomsRoutes);
|
|
app.use('/schedule', scheduleRoutes);
|
|
app.use('/buildings', buildingsRoutes);
|
|
app.use('/admin', adminRoutes);
|
|
app.use('/my_subjects', mySubjectsRoutes);
|
|
app.use('/mis-materias', mySubjectsRoutes);
|
|
|
|
// Redirección de enlaces heredados de Jinja /main/dashboard preservando query params
|
|
app.get(['/main/dashboard', '/main'], (req, res) => {
|
|
const query = req.url.includes('?') ? req.url.substring(req.url.indexOf('?')) : '';
|
|
res.redirect('/dashboard' + query);
|
|
});
|
|
|
|
const { requireAuth } = require('./middlewares/authMiddleware');
|
|
|
|
// Módulo Predictivo y Optimizador
|
|
app.get('/predictive', requireAuth, (req, res) => {
|
|
res.render('predictive/index', {
|
|
title: 'Dashboard Predictivo - Edu-Space Admin',
|
|
user: req.user,
|
|
user_role: (req.user?.role || 'admin').toLowerCase()
|
|
});
|
|
});
|
|
|
|
app.get(['/genetic_optimizer', '/genetic_algorithm_web/genetic_optimizer'], requireAuth, (req, res) => {
|
|
res.render('genetic_optimizer', {
|
|
title: 'Optimizador de Aulas (IA) - Edu-Space Admin',
|
|
user: req.user,
|
|
user_role: (req.user?.role || 'admin').toLowerCase()
|
|
});
|
|
});
|
|
|
|
// Proxy transparente de peticiones /api a Flask
|
|
app.use('/api', async (req, res) => {
|
|
// Si es dashboard-stats mock directo
|
|
if (req.path === '/dashboard-stats') {
|
|
return res.json({
|
|
monthly_data: [
|
|
{ month: 'Ene', reservations: 120 }, { month: 'Feb', reservations: 180 }, { month: 'Mar', reservations: 250 },
|
|
{ month: 'Abr', reservations: 220 }, { month: 'May', reservations: 300 }, { month: 'Jun', reservations: 310 },
|
|
{ month: 'Jul', reservations: 200 }, { month: 'Ago', reservations: 350 }, { month: 'Sep', reservations: 420 },
|
|
{ month: 'Oct', reservations: 480 }, { month: 'Nov', reservations: 520 }, { month: 'Dic', reservations: 210 }
|
|
]
|
|
});
|
|
}
|
|
|
|
try {
|
|
const token = req.cookies.auth_token;
|
|
const headers = { ...req.headers };
|
|
delete headers.host;
|
|
delete headers.connection;
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
if (req.cookies.impersonate_user_id) {
|
|
headers['X-Impersonate-User'] = req.cookies.impersonate_user_id;
|
|
}
|
|
const flaskUrl = `http://127.0.0.1:5000/api${req.url}`;
|
|
const response = await axios({
|
|
method: req.method,
|
|
url: flaskUrl,
|
|
data: req.body,
|
|
headers,
|
|
validateStatus: () => true
|
|
});
|
|
res.status(response.status).json(response.data);
|
|
} catch (e) {
|
|
res.status(500).json({ error: e.message });
|
|
}
|
|
});
|
|
|
|
// Wildcard route to catch unmigrated menu links and attempt to render the Nunjucks templates
|
|
app.get('/:blueprint/:route', (req, res) => {
|
|
const { blueprint, route } = req.params;
|
|
|
|
// Redirects for specific known route names
|
|
if (blueprint === 'main' && route === 'dashboard') {
|
|
return res.redirect('/dashboard');
|
|
}
|
|
if (blueprint === 'classrooms' && (route === 'list_classrooms' || route === 'list')) {
|
|
return res.redirect('/classrooms/list_classrooms');
|
|
}
|
|
if (blueprint === 'classrooms' && (route === 'add_classroom' || route === 'add')) {
|
|
return res.redirect('/classrooms/add_classroom');
|
|
}
|
|
if (blueprint === 'buildings' && (route === 'list_buildings' || route === 'list')) {
|
|
return res.redirect('/buildings/list_buildings');
|
|
}
|
|
if (blueprint === 'buildings' && (route === 'add_building' || route === 'add')) {
|
|
return res.redirect('/buildings/add_building');
|
|
}
|
|
if (blueprint === 'schedule' && (route === 'calendar_view' || route === 'calendar')) {
|
|
return res.redirect('/schedule/calendar_view');
|
|
}
|
|
if (blueprint === 'schedule' && (route === 'add_reservation' || route === 'add')) {
|
|
return res.redirect('/schedule/add_reservation');
|
|
}
|
|
if (blueprint === 'schedule' && (route === 'today_schedule' || route === 'today')) {
|
|
const query = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
|
|
return res.redirect('/schedule/today' + query);
|
|
}
|
|
if (blueprint === 'schedule' && (route === 'list_reservations' || route === 'list')) {
|
|
return res.redirect('/schedule/list_reservations');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'google_sheets_import' || route === 'import')) {
|
|
return res.redirect('/admin/google_sheets_import');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'occupancy_metrics' || route === 'occupancy-metrics')) {
|
|
return res.redirect('/admin/occupancy_metrics');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'users_list' || route === 'user_list' || route === 'users')) {
|
|
return res.redirect('/admin/users_list');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'user_add' || route === 'user_new')) {
|
|
return res.redirect('/admin/user_add');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'user_edit' || route === 'user_edit/:id')) {
|
|
const id = req.query.id || '';
|
|
return res.redirect(id ? `/admin/user_edit/${id}` : '/admin/user_edit');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'roles_list' || route === 'role_list' || route === 'roles')) {
|
|
return res.redirect('/admin/roles_list');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'role_add' || route === 'role_new')) {
|
|
return res.redirect('/admin/role_add');
|
|
}
|
|
if (blueprint === 'admin' && (route === 'role_edit' || route === 'role_edit/:id')) {
|
|
const id = req.query.id || '';
|
|
return res.redirect(id ? `/admin/role_edit/${id}` : '/admin/role_edit');
|
|
}
|
|
if (blueprint === 'classrooms' && (route === 'view_classroom' || route === 'view')) {
|
|
return res.redirect('/classrooms/view_classroom');
|
|
}
|
|
if (blueprint === 'classrooms' && (route === 'edit_classroom' || route === 'edit')) {
|
|
const id = req.query.id || req.query.classroom_id || '';
|
|
return res.redirect(`/classrooms/edit/${id}`);
|
|
}
|
|
if (blueprint === 'admin' && route.includes('careers')) {
|
|
return res.redirect('/admin/careers_list');
|
|
}
|
|
if (blueprint === 'admin' && route.includes('subjects')) {
|
|
return res.redirect('/admin/subjects_list');
|
|
}
|
|
if (blueprint === 'admin' && route.includes('commissions')) {
|
|
return res.redirect('/admin/commissions_list');
|
|
}
|
|
if (blueprint === 'admin' && (route.includes('academic_term') || route.includes('academic_terms'))) {
|
|
return res.redirect('/admin/academic_terms_list');
|
|
}
|
|
if (blueprint === 'admin' && (route.includes('milestone_type') || route.includes('milestone_types'))) {
|
|
return res.redirect('/admin/milestone_types_list');
|
|
}
|
|
if (blueprint === 'admin' && route.includes('audit')) {
|
|
return res.redirect('/admin/audit_logs');
|
|
}
|
|
if (blueprint === 'genetic_algorithm_web' && route === 'genetic_optimizer') {
|
|
return res.redirect('/genetic_optimizer');
|
|
}
|
|
|
|
let templateName = `${blueprint}/${route}`;
|
|
if (route.endsWith('_list') || route.endsWith('_view')) {
|
|
templateName = `${blueprint}/list`;
|
|
if (blueprint === 'admin' && route.includes('users')) templateName = 'admin/users/list';
|
|
if (blueprint === 'admin' && route.includes('roles')) templateName = 'admin/roles/list';
|
|
if (blueprint === 'admin' && route.includes('academic_terms')) templateName = 'admin/academic_terms/list';
|
|
if (blueprint === 'admin' && route.includes('subjects')) templateName = 'admin/subjects/list';
|
|
if (blueprint === 'admin' && route.includes('careers')) templateName = 'admin/careers/list';
|
|
if (blueprint === 'admin' && route.includes('commissions')) templateName = 'admin/commissions/list';
|
|
if (blueprint === 'admin' && route.includes('milestone_types')) templateName = 'admin/milestone_types/list';
|
|
}
|
|
|
|
const mockContext = {
|
|
title: 'Vista de Administración',
|
|
role: 'admin',
|
|
session: { get: (k, d) => d },
|
|
occupancy_metrics: { get: (id, d) => d },
|
|
users: [],
|
|
roles: [],
|
|
careers: [],
|
|
subjects: [],
|
|
commissions: [],
|
|
academic_terms: [],
|
|
terms: [],
|
|
items: [],
|
|
audit_logs: []
|
|
};
|
|
|
|
res.render(templateName, mockContext, function(err, html) {
|
|
if (err) {
|
|
console.log(`Fallback for ${blueprint}/${route}, tried to render ${templateName}. Error:`, err.message);
|
|
res.send(`
|
|
<!DOCTYPE html><html><head><title>Vista en Migración</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<style>body { background: #121212; color: #fff; font-family: sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }</style>
|
|
</head><body><div class="text-center">
|
|
<h1 class="display-4 text-primary mb-3"><i class="bi bi-tools"></i> En Construcción</h1>
|
|
<p class="lead">La funcionalidad <strong>${blueprint}.${route}</strong> está siendo acoplada al nuevo BFF Node.js.</p>
|
|
<p class="text-muted">La migración de ORM Python a JSON REST está en curso para este módulo.</p>
|
|
<a href="/dashboard" class="btn btn-outline-light mt-4">Volver al Panel</a>
|
|
</div></body></html>
|
|
`);
|
|
} else {
|
|
res.send(html);
|
|
}
|
|
});
|
|
});
|
|
|
|
// Middleware 404 para cualquier ruta no encontrada (evita pantallas en blanco y errores Cannot POST/GET)
|
|
app.use((req, res) => {
|
|
res.status(404).send(`
|
|
<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Página No Encontrada — Edu-Space</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
|
<style>
|
|
body { background: #0f172a; color: #f8fafc; font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; margin: 0; }
|
|
.card-error { background: #1e293b; border: 1px solid #334155; border-radius: 16px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5); }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container text-center p-4" style="max-width: 520px;">
|
|
<div class="card card-error p-4 p-md-5">
|
|
<div class="mb-3 text-warning">
|
|
<i class="bi bi-compass fs-1"></i>
|
|
</div>
|
|
<h1 class="h3 fw-bold mb-2">Página o Acción No Encontrada</h1>
|
|
<p class="text-secondary small mb-4">
|
|
La ruta solicitada <code class="text-light">${req.originalUrl}</code> no existe o no admite el método HTTP ejecutado.
|
|
</p>
|
|
<div class="d-flex justify-content-center gap-2">
|
|
<a href="/dashboard" class="btn btn-primary px-4 fw-semibold">
|
|
<i class="bi bi-house-door me-1"></i>Volver al Panel
|
|
</a>
|
|
<button onclick="window.history.back()" class="btn btn-outline-light px-4">
|
|
Volver Atrás
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`);
|
|
});
|
|
|
|
// Middleware Global de Error 500 & Diagnóstico Institucional
|
|
app.use(async (err, req, res, next) => {
|
|
const incidentId = 'INC-' + new Date().toISOString().slice(0, 10).replace(/-/g, '') + '-' + Math.random().toString(36).substring(2, 7).toUpperCase();
|
|
const timestampStr = new Date().toLocaleString('es-AR', { timeZone: 'America/Argentina/Buenos_Aires' });
|
|
const userEmail = req.user?.email || (req.cookies?.refresh_token ? 'Usuario con sesión activa' : 'No autenticado');
|
|
const reqPath = `${req.method} ${req.originalUrl || req.url}`;
|
|
const clientIp = req.headers['x-forwarded-for'] || req.ip || req.socket?.remoteAddress || '-';
|
|
|
|
console.error(`[BFF Error ${incidentId}] en ${reqPath}:`, err);
|
|
|
|
// Clasificación y mensaje amigable
|
|
let statusCode = err.status || err.statusCode || 500;
|
|
let errorTitle = 'Eventualidad en la Aplicación';
|
|
let errorSummary = 'Ocurrió un error inesperado al procesar la operación solicitada.';
|
|
let errorResolution = 'Por favor intente nuevamente o comuníquese con Soporte / Bedelía indicando el código de incidente.';
|
|
|
|
if (err.type === 'entity.too.large' || statusCode === 413) {
|
|
statusCode = 413;
|
|
errorTitle = 'Tamaño de Datos Excedido (Payload Too Large)';
|
|
const lengthKb = err.length ? (err.length / 1024).toFixed(1) + ' KB' : 'desconocido';
|
|
const limitKb = err.limit ? (err.limit / 1024).toFixed(1) + ' KB' : 'desconocido';
|
|
errorSummary = `El volumen de datos enviado (${lengthKb}) superó la capacidad de recepción configurada (${limitKb}).`;
|
|
errorResolution = 'Si está importando planillas masivas de Google Sheets, aplique filtros por día o carrera, o solicite a Soporte que amplíe el límite de transferencia.';
|
|
} else if (err.code === 'ECONNREFUSED' || err.code === 'ETIMEDOUT') {
|
|
statusCode = 503;
|
|
errorTitle = 'Fallo de Comunicación con Backend Core';
|
|
errorSummary = 'No fue posible conectarse con la API central de Edu-Space en el puerto 5000.';
|
|
errorResolution = 'El servicio backend podría estar reiniciándose o en mantenimiento. Aguarde unos segundos y vuelva a intentar.';
|
|
} else if (err.response && err.response.data) {
|
|
errorTitle = `Respuesta del Servidor Central (${err.response.status})`;
|
|
errorSummary = err.response.data.message || err.response.data.error || err.message;
|
|
errorResolution = 'Revise los parámetros ingresados o consulte el registro de auditoría si posee permisos de administrador.';
|
|
} else if (err.message) {
|
|
errorSummary = err.message;
|
|
}
|
|
|
|
// Registro asíncrono no bloqueante en AuditLog del backend
|
|
try {
|
|
const backendBase = process.env.BACKEND_URL || 'http://localhost:5000/api/v1';
|
|
axios.post(`${backendBase}/admin/log-error`, {
|
|
incident_id: incidentId,
|
|
error_title: errorTitle,
|
|
error_message: err.message || errorSummary,
|
|
status_code: statusCode,
|
|
path: reqPath,
|
|
user_email: userEmail,
|
|
ip_address: clientIp,
|
|
stack: err.stack ? err.stack.slice(0, 1000) : null
|
|
}, { timeout: 3000 }).catch(() => {});
|
|
} catch (_) {}
|
|
|
|
// Si la petición espera JSON, responder en JSON estructurado
|
|
if (req.xhr || (req.headers.accept && req.headers.accept.includes('application/json'))) {
|
|
return res.status(statusCode).json({
|
|
status: 'error',
|
|
incident_id: incidentId,
|
|
title: errorTitle,
|
|
message: errorSummary,
|
|
resolution: errorResolution,
|
|
path: reqPath,
|
|
timestamp: timestampStr
|
|
});
|
|
}
|
|
|
|
// Renderizar pantalla institucional de diagnóstico
|
|
res.status(statusCode).send(`
|
|
<!DOCTYPE html>
|
|
<html lang="es">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Error del Sistema — Edu-Space UniCABA</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
|
<style>
|
|
:root { --bs-body-bg: #0f172a; --bs-body-color: #f8fafc; }
|
|
body { background: #0f172a; color: #f8fafc; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 1.5rem; }
|
|
.card-diagnostic { background: #1e293b; border: 1px solid #334155; border-radius: 16px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.7); max-width: 760px; width: 100%; }
|
|
.code-box { background: #0b1120; border: 1px solid #334155; color: #38bdf8; border-radius: 8px; font-family: monospace; font-size: 0.85rem; }
|
|
.incident-badge { background: #3b82f6; color: white; letter-spacing: 0.05em; font-family: monospace; }
|
|
.accordion-button { background: #1e293b; color: #94a3b8; }
|
|
.accordion-button:not(.collapsed) { background: #0f172a; color: #f8fafc; }
|
|
.accordion-item { border-color: #334155; background: transparent; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="card card-diagnostic p-4 p-md-5">
|
|
<!-- Header con branding institucional -->
|
|
<div class="d-flex align-items-center justify-content-between border-bottom border-secondary pb-3 mb-4 flex-wrap gap-2">
|
|
<div class="d-flex align-items-center gap-2">
|
|
<span class="fs-4 fw-bold text-primary">Edu-Space</span>
|
|
<span class="badge bg-secondary-subtle text-secondary border border-secondary font-monospace">UniCABA</span>
|
|
</div>
|
|
<div>
|
|
<span class="badge incident-badge px-3 py-2 rounded-pill fs-6" id="badgeIncidentId">
|
|
<i class="bi bi-ticket-perforated me-1"></i>${incidentId}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Título y síntesis del incidente -->
|
|
<div class="text-center mb-4">
|
|
<div class="mb-3">
|
|
<span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-danger-subtle text-danger p-3" style="width: 64px; height: 64px;">
|
|
<i class="bi bi-exclamation-triangle-fill fs-2"></i>
|
|
</span>
|
|
</div>
|
|
<div class="d-flex align-items-center justify-content-center gap-2 mb-2">
|
|
<span class="badge bg-danger">HTTP ${statusCode}</span>
|
|
<h1 class="h4 fw-bold mb-0 text-white">${errorTitle}</h1>
|
|
</div>
|
|
<p class="text-light fs-6 mb-2 text-start bg-dark p-3 rounded border border-secondary-subtle">
|
|
<i class="bi bi-info-circle text-info me-2"></i>${errorSummary}
|
|
</p>
|
|
<p class="text-secondary small mb-0 text-start">
|
|
<strong>Acción recomendada:</strong> ${errorResolution}
|
|
</p>
|
|
</div>
|
|
|
|
<!-- Sección colapsable de Diagnóstico Técnico -->
|
|
<div class="accordion mb-4" id="diagnosticAccordion">
|
|
<div class="accordion-item rounded overflow-hidden">
|
|
<h2 class="accordion-header" id="headingOne">
|
|
<button class="accordion-button collapsed py-2 small fw-semibold" type="button" data-bs-toggle="collapse" data-bs-target="#collapseDiag" aria-expanded="false" aria-controls="collapseDiag">
|
|
<i class="bi bi-cpu me-2"></i>Detalles Técnicos y Diagnóstico del Servidor
|
|
</button>
|
|
</h2>
|
|
<div id="collapseDiag" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#diagnosticAccordion">
|
|
<div class="accordion-body p-3 bg-dark">
|
|
<div class="row g-2 small mb-3">
|
|
<div class="col-sm-6">
|
|
<span class="text-secondary">Ruta / Solicitud:</span>
|
|
<div class="font-monospace text-light">${reqPath}</div>
|
|
</div>
|
|
<div class="col-sm-6">
|
|
<span class="text-secondary">Fecha y Hora:</span>
|
|
<div class="font-monospace text-light">${timestampStr}</div>
|
|
</div>
|
|
<div class="col-sm-6">
|
|
<span class="text-secondary">Usuario Actuante:</span>
|
|
<div class="font-monospace text-light">${userEmail}</div>
|
|
</div>
|
|
<div class="col-sm-6">
|
|
<span class="text-secondary">Dirección IP:</span>
|
|
<div class="font-monospace text-light">${clientIp}</div>
|
|
</div>
|
|
</div>
|
|
<label class="text-secondary small fw-bold mb-1">Traza de Error (Stack Trace):</label>
|
|
<pre class="code-box p-3 mb-0" style="max-height: 180px; overflow-y: auto;">${(err.stack || err.message || 'Sin traza disponible').replace(/</g, '<').replace(/>/g, '>')}</pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Acciones Rápidas y Copia de Reporte -->
|
|
<div class="d-flex flex-wrap gap-2 justify-content-between align-items-center pt-2 border-top border-secondary">
|
|
<div class="d-flex gap-2 flex-wrap">
|
|
<button type="button" class="btn btn-outline-info btn-sm fw-semibold" onclick="copyDiagnosticReport()">
|
|
<i class="bi bi-clipboard-check me-1"></i>Copiar Reporte para Soporte
|
|
</button>
|
|
<a href="/admin/audit_logs" class="btn btn-outline-secondary btn-sm">
|
|
<i class="bi bi-shield-check me-1"></i>Ver Auditoría
|
|
</a>
|
|
</div>
|
|
<div class="d-flex gap-2">
|
|
<button type="button" class="btn btn-secondary btn-sm" onclick="history.back()">
|
|
<i class="bi bi-arrow-left me-1"></i>Atrás
|
|
</button>
|
|
<button type="button" class="btn btn-outline-light btn-sm" onclick="location.reload()">
|
|
<i class="bi bi-arrow-clockwise me-1"></i>Reintentar
|
|
</button>
|
|
<a href="/dashboard" class="btn btn-primary btn-sm fw-semibold">
|
|
<i class="bi bi-house-door me-1"></i>Panel Principal
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
|
<script>
|
|
function copyDiagnosticReport() {
|
|
const report = [
|
|
'=== REPORTE DE INCIDENTE EDU-SPACE (UniCABA) ===',
|
|
'Código: ' + '${incidentId}',
|
|
'Fecha/Hora: ' + '${timestampStr}',
|
|
'Estado HTTP: ' + '${statusCode}',
|
|
'Título: ' + '${errorTitle}',
|
|
'Resumen: ' + '${errorSummary.replace(/'/g, "\\'")}',
|
|
'Ruta Solicitada: ' + '${reqPath}',
|
|
'Usuario: ' + '${userEmail}',
|
|
'IP Cliente: ' + '${clientIp}',
|
|
'Error Stack:',
|
|
'${(err.stack || err.message || '').replace(/'/g, "\\'").replace(/\n/g, '\\n')}',
|
|
'=================================================='
|
|
].join('\\n');
|
|
|
|
navigator.clipboard.writeText(report).then(() => {
|
|
alert('Reporte copiado al portapapeles. Puede pegarlo y enviarlo al equipo de Soporte IT o Bedelía.');
|
|
}).catch(() => {
|
|
const ta = document.createElement('textarea');
|
|
ta.value = report;
|
|
document.body.appendChild(ta);
|
|
ta.select();
|
|
document.execCommand('copy');
|
|
document.body.removeChild(ta);
|
|
alert('Reporte copiado al portapapeles.');
|
|
});
|
|
}
|
|
</script>
|
|
</body>
|
|
</html>
|
|
`);
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`BFF Frontend corriendo en http://localhost:${port}`);
|
|
});
|
|
|