const express = require('express'); const router = express.Router(); const apiClient = require('../services/apiClient'); const isSecureCookie = (req) => { if (process.env.COOKIE_SECURE === 'true') return true; if (process.env.COOKIE_SECURE === 'false') return false; return Boolean(req.secure || req.protocol === 'https' || req.get('x-forwarded-proto') === 'https'); }; router.get('/login', async (req, res) => { let providers = { local: true, google: false, moodle: false }; let google_client_id = ''; let demo_access_enabled = false; try { const resp = await apiClient.get('/auth/providers'); if (resp.data) { if (resp.data.providers) { providers = resp.data.providers; } google_client_id = resp.data.google_client_id || ''; if (resp.data.demo_access_enabled !== undefined) { demo_access_enabled = Boolean(resp.data.demo_access_enabled); } } } catch (e) { console.warn('Providers fetch notice in login:', e.message); } res.render('auth/login', { error: req.query.error || null, providers, google_client_id, demo_access_enabled }); }); router.post('/login', async (req, res) => { try { const username = req.body.username || req.body.email; const password = req.body.password; // Proxy de la solicitud al backend Flask const response = await apiClient.post('/auth/login', { email: username, password }); const token = response.data.access_token; if (token) { res.cookie('auth_token', token, { httpOnly: true, secure: isSecureCookie(req), sameSite: 'lax', maxAge: 24 * 60 * 60 * 1000 // 1 día }); return res.redirect('/dashboard'); } return res.redirect('/auth/login?error=' + encodeURIComponent('Autenticación fallida')); } catch (error) { console.error('Login error:', error.response?.data || error.message); const errorMsg = error.response?.data?.message || 'Credenciales de acceso incorrectas o cuenta inactiva.'; return res.redirect('/auth/login?error=' + encodeURIComponent(errorMsg)); } }); // Proxy para Login Delegado Moodle router.post('/moodle', async (req, res) => { try { const { username, password } = req.body; const response = await apiClient.post('/auth/moodle', { username, password }); const token = response.data.access_token; if (token) { res.cookie('auth_token', token, { httpOnly: true, secure: isSecureCookie(req), sameSite: 'lax', maxAge: 24 * 60 * 60 * 1000 }); return res.redirect('/dashboard'); } res.redirect('/auth/login?error=moodle_auth_failed'); } catch (error) { console.error('Moodle auth error:', error.response?.data || error.message); const errorMsg = encodeURIComponent(error.response?.data?.message || 'Error de autenticación en Moodle.'); res.redirect(`/auth/login?error=${errorMsg}`); } }); // Proxy para Google OAuth router.post('/google', async (req, res) => { try { const response = await apiClient.post('/auth/google', req.body); const token = response.data.access_token; if (token) { res.cookie('auth_token', token, { httpOnly: true, secure: isSecureCookie(req), sameSite: 'lax', maxAge: 24 * 60 * 60 * 1000 }); return res.json({ success: true, redirect: '/dashboard' }); } return res.status(401).json({ success: false, message: 'Fallo al autenticar con Google.' }); } catch (error) { console.error('Google auth error:', error.response?.data || error.message); return res.status(error.response?.status || 500).json({ success: false, message: error.response?.data?.message || 'Error en autenticación Google Workspace.' }); } }); const { requireAuth } = require('../middlewares/authMiddleware'); router.get('/logout', (req, res) => { res.clearCookie('auth_token'); res.clearCookie('impersonate_user_id'); res.clearCookie('impersonate_user_data'); res.redirect('/auth/login'); }); // Iniciar Modo Impersonación (Solo Admin) router.get('/impersonate/:id', requireAuth, async (req, res) => { try { const targetUserId = parseInt(req.params.id, 10); if (!req.user || !req.user.is_admin()) { return res.status(403).send('Solo los administradores pueden activar el modo de impersonación.'); } const response = await req.apiClient.post('/admin/impersonate', { user_id: targetUserId }); const targetUser = response.data && response.data.target_user; if (targetUser) { res.cookie('impersonate_user_id', targetUserId.toString(), { httpOnly: true, secure: isSecureCookie(req), sameSite: 'lax' }); res.cookie('impersonate_user_data', JSON.stringify(targetUser), { httpOnly: true, secure: isSecureCookie(req), sameSite: 'lax' }); } res.redirect('/dashboard'); } catch (error) { console.error('Error initiating impersonation:', error.response?.data || error.message); res.redirect('/admin/users_list?error=impersonate_failed'); } }); // Detener Modo Impersonación router.get('/stop-impersonating', requireAuth, async (req, res) => { try { await req.apiClient.post('/admin/stop-impersonating', {}); } catch (error) { console.error('Error stopping impersonation on backend:', error.response?.data || error.message); } finally { res.clearCookie('impersonate_user_id'); res.clearCookie('impersonate_user_data'); res.redirect('/admin/users_list'); } }); // Cambiar Contraseña Propia (GET) router.get(['/change_password', '/change-password'], requireAuth, (req, res) => { res.render('auth/change_password', { title: 'Cambiar Contraseña — Edu-Space', error: req.query.error || null, success: req.query.success || null }); }); // Cambiar Contraseña Propia (POST) router.post(['/change_password', '/change-password'], requireAuth, async (req, res) => { const { current_password, new_password, confirm_password } = req.body; if (!current_password || !new_password || !confirm_password) { return res.render('auth/change_password', { title: 'Cambiar Contraseña — Edu-Space', error: 'Todos los campos son obligatorios.', success: null }); } if (new_password !== confirm_password) { return res.render('auth/change_password', { title: 'Cambiar Contraseña — Edu-Space', error: 'La nueva contraseña y su confirmación no coinciden.', success: null }); } if (new_password.length < 6) { return res.render('auth/change_password', { title: 'Cambiar Contraseña — Edu-Space', error: 'La nueva contraseña debe tener al menos 6 caracteres.', success: null }); } try { const response = await req.apiClient.post('/auth/change_password', { current_password, new_password, confirm_password }); return res.render('auth/change_password', { title: 'Cambiar Contraseña — Edu-Space', success: response.data?.message || 'Contraseña actualizada correctamente.', error: null }); } catch (error) { console.error('Change password error:', error.response?.data || error.message); const errMsg = error.response?.data?.message || 'Error al actualizar la contraseña. Verifique su clave actual.'; return res.render('auth/change_password', { title: 'Cambiar Contraseña — Edu-Space', error: errMsg, success: null }); } }); module.exports = router;