Actualizar server.js

This commit is contained in:
2026-02-07 22:24:04 +00:00
parent 968bb4412f
commit da89d7bf85

109
server.js
View File

@@ -4,20 +4,12 @@ import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import pg from "pg"; import pg from "pg";
// Nota: En Node.js v18/v20 'fetch' ya es nativo, no hace falta importarlo.
const { Pool } = pg; const { Pool } = pg;
const app = express(); const app = express();
// ========================= app.use(cors());
// MIDDLEWARES
// =========================
app.use(cors()); // Importante para que la web no de error de bloqueo
app.use(express.json()); app.use(express.json());
// =========================
// VARIABLES DE ENTORNO
// =========================
const { const {
DATABASE_URL, DATABASE_URL,
JWT_SECRET, JWT_SECRET,
@@ -31,28 +23,76 @@ if (!DATABASE_URL || !JWT_SECRET) {
process.exit(1); process.exit(1);
} }
// ========================= // --- CONEXIÓN DB ---
// CONEXIÓN BASE DE DATOS
// =========================
const pool = new Pool({ const pool = new Pool({
connectionString: DATABASE_URL, connectionString: DATABASE_URL,
ssl: false // <--- IMPORTANTE: 'false' para que funcione en Coolify interno ssl: false // Correcto para Coolify interno
}); });
// ========================= // ==========================================
// RUTA DE "ESTOY VIVO" (Health Check) // 🛠️ INICIALIZACIÓN DE LA BASE DE DATOS
// ========================= // ==========================================
async function initDB() {
const client = await pool.connect();
try {
console.log("🛠️ Comprobando tablas de base de datos...");
await client.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
full_name TEXT NOT NULL,
phone TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
dni TEXT,
address TEXT,
password_hash TEXT NOT NULL,
is_verified BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS login_codes (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id) ON DELETE CASCADE,
phone TEXT NOT NULL,
code_hash TEXT NOT NULL,
purpose TEXT DEFAULT 'register_verify',
consumed_at TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS services (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id) ON DELETE CASCADE,
title TEXT NOT NULL,
client_name TEXT,
phone TEXT,
address TEXT,
notes TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
`);
console.log("✅ Tablas verificadas/creadas correctamente.");
} catch (e) {
console.error("❌ Error creando tablas:", e);
} finally {
client.release();
}
}
// Ejecutamos la creación de tablas al arrancar
initDB();
// ==========================================
// RESTO DEL SERVIDOR
// ==========================================
app.get("/", (req, res) => { app.get("/", (req, res) => {
res.status(200).send("🚀 IntegraRepara API v1.0 - Online"); res.status(200).send("🚀 IntegraRepara API v1.0 - Online");
}); });
// =========================
// FUNCIONES DE AYUDA (Helpers)
// =========================
function normalizePhone(phone) { function normalizePhone(phone) {
let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, "");
if (!p) return ""; if (!p) return "";
// Lógica simple para España
if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) { if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) {
return "+34" + p; return "+34" + p;
} }
@@ -71,7 +111,6 @@ function signToken(user) {
); );
} }
// Middleware de seguridad para rutas protegidas
function authMiddleware(req, res, next) { function authMiddleware(req, res, next) {
const h = req.headers.authorization || ""; const h = req.headers.authorization || "";
const token = h.startsWith("Bearer ") ? h.slice(7) : ""; const token = h.startsWith("Bearer ") ? h.slice(7) : "";
@@ -85,9 +124,6 @@ function authMiddleware(req, res, next) {
} }
} }
// =========================
// WHATSAPP (EVOLUTION API)
// =========================
async function sendWhatsAppCode(phone, code) { async function sendWhatsAppCode(phone, code) {
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
console.log("⚠️ Evolution no configurado. Código simulado:", code); console.log("⚠️ Evolution no configurado. Código simulado:", code);
@@ -104,10 +140,7 @@ async function sendWhatsAppCode(phone, code) {
const res = await fetch(url, { const res = await fetch(url, {
method: "POST", method: "POST",
headers: { headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
"Content-Type": "application/json",
"apikey": EVOLUTION_API_KEY
},
body: JSON.stringify(body) body: JSON.stringify(body)
}); });
@@ -123,11 +156,8 @@ async function sendWhatsAppCode(phone, code) {
} }
} }
// ========================= // --- RUTAS ---
// RUTAS DE LA API
// =========================
// 1. REGISTRO
app.post("/auth/register", async (req, res) => { app.post("/auth/register", async (req, res) => {
const client = await pool.connect(); const client = await pool.connect();
try { try {
@@ -142,7 +172,6 @@ app.post("/auth/register", async (req, res) => {
await client.query('BEGIN'); await client.query('BEGIN');
// Comprobar si existe
const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]); const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]);
let userId; let userId;
@@ -152,14 +181,12 @@ app.post("/auth/register", async (req, res) => {
await client.query('ROLLBACK'); await client.query('ROLLBACK');
return res.status(409).json({ ok: false, error: "Usuario ya registrado y verificado." }); return res.status(409).json({ ok: false, error: "Usuario ya registrado y verificado." });
} }
// Actualizar usuario existente no verificado
await client.query( await client.query(
"UPDATE users SET full_name=$1, address=$2, dni=$3, password_hash=$4 WHERE id=$5", "UPDATE users SET full_name=$1, address=$2, dni=$3, password_hash=$4 WHERE id=$5",
[fullName, address, dni, passwordHash, existing.id] [fullName, address, dni, passwordHash, existing.id]
); );
userId = existing.id; userId = existing.id;
} else { } else {
// Crear nuevo
const insert = await client.query( const insert = await client.query(
"INSERT INTO users (full_name, phone, address, dni, email, password_hash) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id", "INSERT INTO users (full_name, phone, address, dni, email, password_hash) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id",
[fullName, p, address, dni, email, passwordHash] [fullName, p, address, dni, email, passwordHash]
@@ -167,10 +194,9 @@ app.post("/auth/register", async (req, res) => {
userId = insert.rows[0].id; userId = insert.rows[0].id;
} }
// Código de verificación
const code = genCode6(); const code = genCode6();
const codeHash = await bcrypt.hash(code, 10); const codeHash = await bcrypt.hash(code, 10);
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 min const expiresAt = new Date(Date.now() + 10 * 60 * 1000);
await client.query("DELETE FROM login_codes WHERE user_id = $1", [userId]); await client.query("DELETE FROM login_codes WHERE user_id = $1", [userId]);
await client.query( await client.query(
@@ -178,7 +204,6 @@ app.post("/auth/register", async (req, res) => {
[userId, p, codeHash, expiresAt] [userId, p, codeHash, expiresAt]
); );
// Enviar WhatsApp (sin esperar bloqueante para no fallar la DB si tarda)
await sendWhatsAppCode(p, code); await sendWhatsAppCode(p, code);
await client.query('COMMIT'); await client.query('COMMIT');
@@ -193,7 +218,6 @@ app.post("/auth/register", async (req, res) => {
} }
}); });
// 2. VERIFICAR CÓDIGO (Aquí estaba tu error de sintaxis, ya está corregido)
app.post("/auth/verify", async (req, res) => { app.post("/auth/verify", async (req, res) => {
try { try {
const { phone, code } = req.body; const { phone, code } = req.body;
@@ -210,15 +234,13 @@ app.post("/auth/verify", async (req, res) => {
if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o expirado" }); if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o expirado" });
const row = q.rows[0]; // Definimos 'row' aquí para usarlo abajo const row = q.rows[0];
const valid = await bcrypt.compare(String(code), row.code_hash); const valid = await bcrypt.compare(String(code), row.code_hash);
if (!valid) return res.status(400).json({ ok: false, error: "Código incorrecto" }); if (!valid) return res.status(400).json({ ok: false, error: "Código incorrecto" });
// --- CORRECCIÓN DE SINTAXIS AQUI ---
await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]); 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.uid]); await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [row.uid]);
// -----------------------------------
const token = signToken({ id: row.uid, email: row.email, phone: p }); const token = signToken({ id: row.uid, email: row.email, phone: p });
res.json({ ok: true, token }); res.json({ ok: true, token });
@@ -229,7 +251,6 @@ app.post("/auth/verify", async (req, res) => {
} }
}); });
// 3. LOGIN (Email + Pass)
app.post("/auth/login", async (req, res) => { app.post("/auth/login", async (req, res) => {
try { try {
const { email, password } = req.body; const { email, password } = req.body;
@@ -250,7 +271,6 @@ app.post("/auth/login", async (req, res) => {
} }
}); });
// 4. SERVICIOS (Protegido)
app.get("/services", authMiddleware, async (req, res) => { app.get("/services", authMiddleware, async (req, res) => {
try { try {
const q = await pool.query("SELECT * FROM services WHERE user_id=$1 ORDER BY created_at DESC", [req.user.sub]); const q = await pool.query("SELECT * FROM services WHERE user_id=$1 ORDER BY created_at DESC", [req.user.sub]);
@@ -260,6 +280,5 @@ app.get("/services", authMiddleware, async (req, res) => {
} }
}); });
// ARRANCAR SERVIDOR
const port = process.env.PORT || 3000; const port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`));