diff --git a/server.js b/server.js index 5982b40..1a7e04b 100644 --- a/server.js +++ b/server.js @@ -3,12 +3,15 @@ import cors from "cors"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import pg from "pg"; -import fetch from "node-fetch"; // Asegúrate de tener node-fetch si usas Node < 18 +// import fetch from "node-fetch"; // YA NO ES NECESARIO EN NODE 20 const { Pool } = pg; const app = express(); -app.use(cors()); +// ========================= +// MIDDLEWARES (IMPORTANTE EL ORDEN) +// ========================= +app.use(cors()); // <--- AÑADIDO: Habilita CORS para que tu web pueda conectarse app.use(express.json()); // ========================= @@ -35,6 +38,14 @@ const pool = new Pool({ ssl: DATABASE_URL.includes("localhost") ? false : { rejectUnauthorized: false } }); +// ========================= +// RUTA DE SALUD (Health Check) +// ========================= +// Esta ruta arregla el mensaje "Cannot GET /" y te confirma que la API vive. +app.get("/", (req, res) => { + res.send("🚀 IntegraRepara API v1.0 - Funcionando correctamente"); +}); + // ========================= // HELPERS // ========================= @@ -65,7 +76,6 @@ function authMiddleware(req, res, next) { const h = req.headers.authorization || ""; const token = h.startsWith("Bearer ") ? h.slice(7) : ""; if (!token) return res.status(401).json({ ok: false, error: "No token" }); - try { const payload = jwt.verify(token, JWT_SECRET); req.user = payload; @@ -81,17 +91,16 @@ function authMiddleware(req, res, next) { async function sendWhatsAppCode(phone, code) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) { console.warn("⚠️ Evolution API no configurada. Código (Log):", code); - return { ok: true, skipped: true }; // Devolvemos true para no romper el flujo en desarrollo + return { ok: true, skipped: true }; } - try { const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`; - const body = { - number: phone.replace("+", ""), // Evolution suele preferir el número sin el + + number: phone.replace("+", ""), text: `🔐 Tu código de verificación IntegraRepara es: *${code}*\n\nNo lo compartas con nadie.` }; - + + // Fetch nativo de Node (sin librería extra) const res = await fetch(url, { method: "POST", headers: { @@ -100,9 +109,8 @@ async function sendWhatsAppCode(phone, code) { }, body: JSON.stringify(body) }); - - const data = await res.json(); + const data = await res.json(); if (!res.ok) { console.error("❌ Error Evolution:", data); return { ok: false }; @@ -124,27 +132,23 @@ app.post("/auth/register", async (req, res) => { try { const { fullName, phone, address, dni, email, password } = req.body; const p = normalizePhone(phone); - if (!fullName || !p || !email || !password) { return res.status(400).json({ ok: false, error: "Faltan datos" }); } - const passwordHash = await bcrypt.hash(password, 10); await client.query('BEGIN'); - // Verificamos si existe const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]); - let userId; - + if (checkUser.rowCount > 0) { const existing = checkUser.rows[0]; if (existing.is_verified) { await client.query('ROLLBACK'); return res.status(409).json({ ok: false, error: "El usuario ya existe y está verificado. Por favor inicia sesión." }); } else { - // Existe pero NO verificado: Actualizamos datos y reenvíamos código + // Existe pero NO verificado: Actualizamos datos await client.query( `UPDATE users SET full_name=$1, address=$2, dni=$3, password_hash=$4 WHERE id=$5`, [fullName, address, dni, passwordHash, existing.id] @@ -160,28 +164,22 @@ app.post("/auth/register", async (req, res) => { ); userId = insert.rows[0].id; } - // Generar código const code = genCode6(); const codeHash = await bcrypt.hash(code, 10); const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 min - - // Invalidar códigos anteriores - await client.query("DELETE FROM login_codes WHERE user_id = $1", [userId]); - // Insertar nuevo código + // Invalidar códigos anteriores e insertar nuevo + 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] ); - - // Enviar WhatsApp (fuera de la transacción para no bloquear DB si tarda) - const whatsAppStatus = await sendWhatsAppCode(p, code); - + + // Enviar WhatsApp + await sendWhatsAppCode(p, code); await client.query('COMMIT'); - res.json({ ok: true, phone: p, msg: "Código enviado" }); - } catch (e) { await client.query('ROLLBACK'); console.error(e); @@ -196,7 +194,6 @@ app.post("/auth/verify", async (req, res) => { try { const { phone, code } = req.body; const p = normalizePhone(phone); - // Buscar código válido const codeQuery = await pool.query( `SELECT lc.*, u.id as user_id, u.email, u.full_name, u.phone @@ -206,27 +203,20 @@ app.post("/auth/verify", async (req, res) => { 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" }); } - // Consumir código y verificar usuario await pool.query("UPDATE login_codes SET consumed_at = NOW() WHERE id = $1", [row.id]); await pool.query("UPDATE users SET is_verified = TRUE WHERE id = $1", [row.user_id]); - const user = { id: row.user_id, email: row.email, phone: row.phone }; const token = signToken(user); - res.json({ ok: true, token }); - } catch (e) { console.error(e); res.status(500).json({ ok: false, error: "Error verificando código" }); @@ -237,28 +227,22 @@ app.post("/auth/verify", async (req, res) => { app.post("/auth/login", async (req, res) => { try { const { email, password } = req.body; - const u = await pool.query("SELECT * FROM users WHERE email = $1", [email]); if (u.rowCount === 0) return res.status(401).json({ ok: false, error: "Credenciales inválidas" }); - const user = u.rows[0]; const match = await bcrypt.compare(password, user.password_hash); - if (!match) return res.status(401).json({ ok: false, error: "Credenciales inválidas" }); - if (!user.is_verified) { - return res.status(403).json({ ok: false, error: "Cuenta no verificada. Regístrate de nuevo para recibir el código." }); + return res.status(403).json({ ok: false, error: "Cuenta no verificada." }); } - const token = signToken(user); res.json({ ok: true, token }); - } catch (e) { res.status(500).json({ ok: false, error: "Error en login" }); } }); -// 4. DATOS PROTEGIDOS (Dashboard) +// 4. DATOS PROTEGIDOS app.get("/services", authMiddleware, async (req, res) => { const q = await pool.query("SELECT * FROM services WHERE user_id = $1 ORDER BY created_at DESC", [req.user.sub]); res.json({ ok: true, services: q.rows });