Actualizar server.js
This commit is contained in:
208
server.js
208
server.js
@@ -3,20 +3,15 @@ import cors from "cors";
|
|||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import pg from "pg";
|
import pg from "pg";
|
||||||
// import fetch from "node-fetch"; // YA NO ES NECESARIO EN NODE 20
|
|
||||||
|
|
||||||
const { Pool } = pg;
|
const { Pool } = pg;
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
// =========================
|
// --- MIDDLEWARES ---
|
||||||
// MIDDLEWARES (IMPORTANTE EL ORDEN)
|
app.use(cors());
|
||||||
// =========================
|
|
||||||
app.use(cors()); // <--- AÑADIDO: Habilita CORS para que tu web pueda conectarse
|
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
// =========================
|
// --- ENV ---
|
||||||
// ENV
|
|
||||||
// =========================
|
|
||||||
const {
|
const {
|
||||||
DATABASE_URL,
|
DATABASE_URL,
|
||||||
JWT_SECRET,
|
JWT_SECRET,
|
||||||
@@ -26,33 +21,25 @@ const {
|
|||||||
} = process.env;
|
} = process.env;
|
||||||
|
|
||||||
if (!DATABASE_URL || !JWT_SECRET) {
|
if (!DATABASE_URL || !JWT_SECRET) {
|
||||||
console.error("❌ Faltan variables de entorno críticas (DATABASE_URL o JWT_SECRET)");
|
console.error("ERROR FATAL: Faltan DATABASE_URL o JWT_SECRET");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
// --- DB ---
|
||||||
// DB CONNECTION
|
|
||||||
// =========================
|
|
||||||
const pool = new Pool({
|
const pool = new Pool({
|
||||||
connectionString: DATABASE_URL,
|
connectionString: DATABASE_URL,
|
||||||
ssl: DATABASE_URL.includes("localhost") ? false : { rejectUnauthorized: false }
|
ssl: DATABASE_URL.includes("localhost") ? false : { rejectUnauthorized: false }
|
||||||
});
|
});
|
||||||
|
|
||||||
// =========================
|
// --- RUTA HEALTH CHECK (Para evitar el 404/502) ---
|
||||||
// RUTA DE SALUD (Health Check)
|
|
||||||
// =========================
|
|
||||||
// Esta ruta arregla el mensaje "Cannot GET /" y te confirma que la API vive.
|
|
||||||
app.get("/", (req, res) => {
|
app.get("/", (req, res) => {
|
||||||
res.send("🚀 IntegraRepara API v1.0 - Funcionando correctamente");
|
res.status(200).send("IntegraRepara API Online");
|
||||||
});
|
});
|
||||||
|
|
||||||
// =========================
|
// --- HELPERS ---
|
||||||
// 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,182 +58,139 @@ function signToken(user) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Middleware de autenticación
|
// --- WHATSAPP ---
|
||||||
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;
|
|
||||||
next();
|
|
||||||
} catch {
|
|
||||||
return res.status(401).json({ ok: false, error: "Token inválido o expirado" });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// =========================
|
|
||||||
// EVOLUTION API (WHATSAPP)
|
|
||||||
// =========================
|
|
||||||
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.warn("⚠️ Evolution API no configurada. Código (Log):", code);
|
console.log("Simulando envío WhatsApp (Faltan claves):", code);
|
||||||
return { ok: true, skipped: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`;
|
// Detectamos si la URL base termina en / o no
|
||||||
|
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
||||||
|
const url = `${baseUrl}/message/sendText/${EVOLUTION_INSTANCE}`;
|
||||||
|
|
||||||
const body = {
|
const body = {
|
||||||
number: phone.replace("+", ""),
|
number: phone.replace("+", ""),
|
||||||
text: `🔐 Tu código de verificación IntegraRepara es: *${code}*\n\nNo lo compartas con nadie.`
|
text: `Tu código es: ${code}`
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch nativo de Node (sin librería extra)
|
|
||||||
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)
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
console.error("❌ Error Evolution:", data);
|
const txt = await res.text();
|
||||||
|
console.error("Error Evolution:", txt);
|
||||||
return { ok: false };
|
return { ok: false };
|
||||||
}
|
}
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch (error) {
|
} catch (e) {
|
||||||
console.error("❌ Error enviando WhatsApp:", error);
|
console.error("Error envío:", e);
|
||||||
return { ok: false };
|
return { ok: false };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
// --- RUTAS ---
|
||||||
// RUTAS DE AUTENTICACIÓN
|
|
||||||
// =========================
|
|
||||||
|
|
||||||
// 1. REGISTRO
|
// 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 {
|
||||||
const { fullName, phone, address, dni, email, password } = req.body;
|
const { fullName, phone, address, dni, email, password } = req.body;
|
||||||
const p = normalizePhone(phone);
|
const p = normalizePhone(phone);
|
||||||
if (!fullName || !p || !email || !password) {
|
if (!fullName || !p || !email || !password) return res.status(400).json({error: "Faltan datos"});
|
||||||
return res.status(400).json({ ok: false, error: "Faltan datos" });
|
|
||||||
}
|
|
||||||
const passwordHash = await bcrypt.hash(password, 10);
|
const passwordHash = await bcrypt.hash(password, 10);
|
||||||
|
|
||||||
await client.query('BEGIN');
|
await client.query('BEGIN');
|
||||||
// Verificamos si existe
|
|
||||||
const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]);
|
// Check usuario
|
||||||
|
const check = await client.query("SELECT * FROM users WHERE email=$1 OR phone=$2", [email, p]);
|
||||||
let userId;
|
let userId;
|
||||||
|
|
||||||
if (checkUser.rowCount > 0) {
|
if (check.rowCount > 0) {
|
||||||
const existing = checkUser.rows[0];
|
const u = check.rows[0];
|
||||||
if (existing.is_verified) {
|
if (u.is_verified) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
return res.status(409).json({ ok: false, error: "El usuario ya existe y está verificado. Por favor inicia sesión." });
|
return res.status(409).json({error: "Usuario ya existe"});
|
||||||
} else {
|
|
||||||
// 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]
|
|
||||||
);
|
|
||||||
userId = existing.id;
|
|
||||||
}
|
}
|
||||||
|
// Actualizar existente no verificado
|
||||||
|
await client.query("UPDATE users SET full_name=$1, password_hash=$2 WHERE id=$3", [fullName, passwordHash, u.id]);
|
||||||
|
userId = u.id;
|
||||||
} else {
|
} else {
|
||||||
// Nuevo usuario
|
// Nuevo
|
||||||
const insert = await client.query(
|
const ins = await client.query("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]);
|
||||||
`INSERT INTO users (full_name, phone, address, dni, email, password_hash)
|
userId = ins.rows[0].id;
|
||||||
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`,
|
|
||||||
[fullName, p, address, dni, email, passwordHash]
|
|
||||||
);
|
|
||||||
userId = insert.rows[0].id;
|
|
||||||
}
|
}
|
||||||
// Generar código
|
|
||||||
|
// Código
|
||||||
const code = genCode6();
|
const code = genCode6();
|
||||||
const codeHash = await bcrypt.hash(code, 10);
|
const hash = await bcrypt.hash(code, 10);
|
||||||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 min
|
const exp = new Date(Date.now() + 600000);
|
||||||
|
|
||||||
// Invalidar códigos anteriores e insertar nuevo
|
|
||||||
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("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1,$2,$3,$4)", [userId, p, hash, exp]);
|
||||||
`INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)`,
|
|
||||||
[userId, p, codeHash, expiresAt]
|
|
||||||
);
|
|
||||||
|
|
||||||
// Enviar WhatsApp
|
|
||||||
await sendWhatsAppCode(p, code);
|
await sendWhatsAppCode(p, code);
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
res.json({ ok: true, phone: p, msg: "Código enviado" });
|
|
||||||
|
res.json({ok: true, phone: p});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
console.error(e);
|
console.error(e);
|
||||||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
res.status(500).json({error: "Error servidor"});
|
||||||
} finally {
|
} finally {
|
||||||
client.release();
|
client.release();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 2. VERIFICACIÓN
|
// Verificación
|
||||||
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;
|
||||||
const p = normalizePhone(phone);
|
const p = normalizePhone(phone);
|
||||||
// Buscar código válido
|
|
||||||
const codeQuery = await pool.query(
|
const q = await pool.query(`
|
||||||
`SELECT lc.*, u.id as user_id, u.email, u.full_name, u.phone
|
SELECT lc.*, u.id as uid, u.email, u.phone
|
||||||
FROM login_codes lc
|
FROM login_codes lc JOIN users u ON lc.user_id = u.id
|
||||||
JOIN users u ON lc.user_id = u.id
|
|
||||||
WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW()
|
WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW()
|
||||||
ORDER BY lc.created_at DESC LIMIT 1`,
|
ORDER BY lc.created_at DESC LIMIT 1`, [p]);
|
||||||
[p]
|
|
||||||
);
|
if (q.rowCount === 0) return res.status(400).json({error: "Código inválido"});
|
||||||
if (codeQuery.rowCount === 0) {
|
|
||||||
return res.status(400).json({ ok: false, error: "Código inválido o expirado" });
|
const valid = await bcrypt.compare(String(code), q.rows[0].code_hash);
|
||||||
}
|
if (!valid) return res.status(400).json({error: "Código incorrecto"});
|
||||||
const row = codeQuery.rows[0];
|
|
||||||
const valid = await bcrypt.compare(String(code), row.code_hash);
|
await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [q.rows[0].id]);
|
||||||
if (!valid) {
|
await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [q.rows[0].uid]);
|
||||||
return res.status(400).json({ ok: false, error: "Código incorrecto" });
|
|
||||||
}
|
const token = signToken({id: q.rows[0].uid, email: q.rows[0].email, phone: p});
|
||||||
// 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});
|
res.json({ok: true, token});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
res.status(500).json({ ok: false, error: "Error verificando código" });
|
res.status(500).json({error: "Error verify"});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. LOGIN
|
// Login
|
||||||
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;
|
||||||
const u = await pool.query("SELECT * FROM users WHERE email = $1", [email]);
|
const q = 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" });
|
if (q.rowCount === 0) return res.status(401).json({error: "Credenciales"});
|
||||||
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." });
|
|
||||||
}
|
|
||||||
const token = signToken(user);
|
|
||||||
res.json({ ok: true, token });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(500).json({ ok: false, error: "Error en login" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 4. DATOS PROTEGIDOS
|
const u = q.rows[0];
|
||||||
app.get("/services", authMiddleware, async (req, res) => {
|
const match = await bcrypt.compare(password, u.password_hash);
|
||||||
const q = await pool.query("SELECT * FROM services WHERE user_id = $1 ORDER BY created_at DESC", [req.user.sub]);
|
if (!match) return res.status(401).json({error: "Credenciales"});
|
||||||
res.json({ ok: true, services: q.rows });
|
if (!u.is_verified) return res.status(403).json({error: "No verificado"});
|
||||||
|
|
||||||
|
res.json({ok: true, token: signToken(u)});
|
||||||
|
} catch(e) {
|
||||||
|
res.status(500).json({error: "Error login"});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const port = process.env.PORT || 3000;
|
const port = process.env.PORT || 3000;
|
||||||
app.listen(port, () => console.log(`🚀 Server en puerto ${port}`));
|
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`));
|
||||||
Reference in New Issue
Block a user