From cc815213d4daf06f417ab3ea7bef3583c1e5fdf5 Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 8 Feb 2026 11:15:02 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 204 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 116 insertions(+), 88 deletions(-) diff --git a/server.js b/server.js index aeec1e6..da5095c 100644 --- a/server.js +++ b/server.js @@ -80,7 +80,7 @@ async function autoUpdateDB() { ); `); - // Parches de columnas + // Parches await client.query(` DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='role') THEN @@ -99,18 +99,11 @@ async function autoUpdateDB() { `); try { await client.query(`ALTER TABLE guilds DROP CONSTRAINT IF EXISTS guilds_name_key`); } catch (e) {} - console.log("✅ DB Sincronizada."); - } catch (e) { - console.error("❌ Error DB:", e); - } finally { - client.release(); - } + } catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); } } -// ========================= // HELPERS -// ========================= function normalizePhone(phone) { let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); if (!p) return ""; @@ -123,8 +116,7 @@ function signToken(user) { const accountId = user.owner_id || user.id; return jwt.sign( { sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId: accountId }, - JWT_SECRET, - { expiresIn: "30d" } + JWT_SECRET, { expiresIn: "30d" } ); } @@ -136,8 +128,21 @@ function authMiddleware(req, res, next) { catch { return res.status(401).json({ ok: false, error: "Token inválido" }); } } +async function sendWhatsAppCode(phone, code) { + if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) { + console.log("⚠️ Evolution no configurado. Código:", code); + return; + } + const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`; + await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, + body: JSON.stringify({ number: phone.replace("+", ""), text: `🔐 Código IntegraRepara: *${code}*` }) + }).catch(console.error); +} + // ========================= -// RUTAS +// RUTAS DE AUTENTICACIÓN // ========================= // REGISTRO @@ -176,20 +181,14 @@ app.post("/auth/register", async (req, res) => { await client.query("DELETE FROM login_codes WHERE user_id = $1", [userId]); await client.query("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]); - - if (EVOLUTION_BASE_URL && EVOLUTION_API_KEY) { - const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`; - await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, body: JSON.stringify({ number: p.replace("+", ""), text: `🔐 Código: *${code}*` }) }).catch(console.error); - } + await sendWhatsAppCode(p, code); await client.query('COMMIT'); res.json({ ok: true, phone: p }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false, error: "Error server" }); - } finally { - client.release(); - } + } finally { client.release(); } }); // VERIFICACIÓN & LOGIN @@ -218,7 +217,86 @@ app.post("/auth/login", async (req, res) => { } catch(e) { res.status(500).json({ ok: false, error: "Error login" }); } }); -// SERVICES +// 🆕 NUEVO: RECUPERAR CONTRASEÑA 🆕 + +// Paso 1: Solicitar código con DNI y Teléfono +app.post("/auth/forgot-password", async (req, res) => { + try { + const { dni, phone } = req.body; + const p = normalizePhone(phone); + + // Buscamos usuario por DNI y Teléfono + const userQuery = await pool.query("SELECT id FROM users WHERE dni = $1 AND phone = $2", [dni, p]); + + if (userQuery.rowCount === 0) { + return res.status(404).json({ ok: false, error: "No coinciden los datos." }); + } + + const userId = userQuery.rows[0].id; + const code = genCode6(); + const codeHash = await bcrypt.hash(code, 10); + const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 min + + // Guardamos con propósito 'password_reset' + await pool.query("INSERT INTO login_codes (user_id, phone, code_hash, purpose, expires_at) VALUES ($1, $2, $3, 'password_reset', $4)", + [userId, p, codeHash, expiresAt]); + + await sendWhatsAppCode(p, code); + res.json({ ok: true, msg: "Código enviado" }); + + } catch (e) { + console.error(e); + res.status(500).json({ ok: false, error: "Error interno" }); + } +}); + +// Paso 2: Resetear contraseña +app.post("/auth/reset-password", async (req, res) => { + const client = await pool.connect(); + try { + const { phone, code, newPassword } = req.body; + const p = normalizePhone(phone); + + // Buscar código válido para reset + const codeQuery = await client.query(` + SELECT lc.*, u.id as uid + FROM login_codes lc + JOIN users u ON lc.user_id = u.id + WHERE lc.phone=$1 + AND lc.purpose='password_reset' + AND lc.consumed_at IS NULL + AND lc.expires_at > NOW() + ORDER BY lc.created_at DESC LIMIT 1 + `, [p]); + + if (codeQuery.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o expirado" }); + + const row = codeQuery.rows[0]; + const valid = await bcrypt.compare(String(code), row.code_hash); + if (!valid) return res.status(400).json({ ok: false, error: "Código incorrecto" }); + + // Cambiar contraseña + const newHash = await bcrypt.hash(newPassword, 10); + + await client.query('BEGIN'); + await client.query("UPDATE users SET password_hash=$1 WHERE id=$2", [newHash, row.uid]); + await client.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]); + await client.query('COMMIT'); + + res.json({ ok: true, msg: "Contraseña actualizada" }); + + } catch (e) { + await client.query('ROLLBACK'); + console.error(e); + res.status(500).json({ ok: false, error: "Error al cambiar contraseña" }); + } finally { client.release(); } +}); + + +// ========================= +// RUTAS PROTEGIDAS +// ========================= + app.get("/services", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM services WHERE owner_id=$1 ORDER BY created_at DESC", [req.user.accountId]); @@ -226,7 +304,6 @@ app.get("/services", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); } }); -// GREMIOS app.get("/guilds", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); @@ -250,125 +327,76 @@ app.delete("/guilds/:id", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); -// ========================= -// GESTIÓN DE USUARIOS (CRUD COMPLETO) -// ========================= - -// 1. LISTAR USUARIOS (GET) +// ADMIN USERS app.get("/admin/users", authMiddleware, async (req, res) => { try { - // Obtenemos usuarios y sus gremios en una sola consulta const q = await pool.query(` - SELECT u.id, u.full_name, u.email, u.phone, u.role, - COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds - FROM users u - LEFT JOIN user_guilds ug ON u.id = ug.user_id - LEFT JOIN guilds g ON ug.guild_id = g.id - WHERE u.owner_id = $1 - GROUP BY u.id - ORDER BY u.id DESC + SELECT u.id, u.full_name, u.email, u.phone, u.role, COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds + FROM users u LEFT JOIN user_guilds ug ON u.id = ug.user_id LEFT JOIN guilds g ON ug.guild_id = g.id + WHERE u.owner_id = $1 GROUP BY u.id ORDER BY u.id DESC `, [req.user.accountId]); - res.json({ ok: true, users: q.rows }); - } catch (e) { - console.error(e); - res.status(500).json({ ok: false, error: "Error al listar usuarios" }); - } + } catch (e) { res.status(500).json({ ok: false, error: "Error listar users" }); } }); -// 2. CREAR USUARIO (POST) - AHORA CON TELÉFONO REAL app.post("/admin/users", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { fullName, email, password, role, guilds, phone } = req.body; - - if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false, error: "Faltan datos (nombre, email, pass, teléfono)" }); - + if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false, error: "Faltan datos" }); const p = normalizePhone(phone); const passwordHash = await bcrypt.hash(password, 10); - await client.query('BEGIN'); - const insert = await client.query( - `INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id) - VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id`, + `INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id) VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id`, [fullName, email, passwordHash, role || 'operario', p, req.user.accountId] ); const userId = insert.rows[0].id; - if (guilds && Array.isArray(guilds)) { - for (const guildId of guilds) { - await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, guildId]); - } + for (const guildId of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, guildId]); } - await client.query('COMMIT'); res.json({ ok: true, msg: "Usuario creado" }); } catch (e) { await client.query('ROLLBACK'); if (e.code === '23505') { - if (e.constraint && e.constraint.includes('email')) return res.status(400).json({ ok: false, error: "❌ El email ya existe." }); - if (e.constraint && e.constraint.includes('phone')) return res.status(400).json({ ok: false, error: "❌ El teléfono ya existe." }); + if (e.constraint && e.constraint.includes('email')) return res.status(400).json({ ok: false, error: "❌ Email existe." }); + if (e.constraint && e.constraint.includes('phone')) return res.status(400).json({ ok: false, error: "❌ Teléfono existe." }); } - console.error(e); res.status(500).json({ ok: false, error: "Error creando usuario" }); - } finally { - client.release(); - } + } finally { client.release(); } }); -// 3. EDITAR USUARIO (PUT) app.put("/admin/users/:id", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const userId = req.params.id; const { fullName, email, phone, role, guilds, password } = req.body; const p = normalizePhone(phone); - await client.query('BEGIN'); - - // Verificar que el usuario pertenece a mi empresa const check = await client.query("SELECT id FROM users WHERE id=$1 AND owner_id=$2", [userId, req.user.accountId]); - if(check.rowCount === 0) throw new Error("Usuario no encontrado o no tienes permiso"); - - // Actualizar datos básicos + if(check.rowCount === 0) throw new Error("No encontrado"); if(password) { const hash = await bcrypt.hash(password, 10); await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5 WHERE id=$6", [fullName, email, p, role, hash, userId]); } else { await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, userId]); } - - // Actualizar Gremios (Borrar y Crear) if (guilds && Array.isArray(guilds)) { await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]); - for (const guildId of guilds) { - await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, guildId]); - } + for (const guildId of guilds) await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, guildId]); } - await client.query('COMMIT'); - res.json({ ok: true, msg: "Usuario actualizado" }); - - } catch (e) { - await client.query('ROLLBACK'); - console.error(e); - res.status(500).json({ ok: false, error: "Error actualizando (Revisa email/teléfono duplicados)" }); - } finally { - client.release(); - } + res.json({ ok: true, msg: "Actualizado" }); + } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false, error: "Error updating" }); } finally { client.release(); } }); -// 4. BORRAR USUARIO (DELETE) app.delete("/admin/users/:id", authMiddleware, async (req, res) => { try { const result = await pool.query("DELETE FROM users WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); - if (result.rowCount === 0) return res.status(404).json({ ok: false, error: "Usuario no encontrado" }); + if (result.rowCount === 0) return res.status(404).json({ ok: false, error: "No encontrado" }); res.json({ ok: true }); - } catch (e) { - console.error(e); - res.status(500).json({ ok: false, error: "Error borrando usuario" }); - } + } catch (e) { res.status(500).json({ ok: false, error: "Error deleting" }); } }); const port = process.env.PORT || 3000;