Actualizar server.js
This commit is contained in:
199
server.js
199
server.js
@@ -7,11 +7,15 @@ import pg from "pg";
|
||||
const { Pool } = pg;
|
||||
const app = express();
|
||||
|
||||
// --- MIDDLEWARES ---
|
||||
app.use(cors());
|
||||
// =========================
|
||||
// MIDDLEWARES
|
||||
// =========================
|
||||
app.use(cors()); // Habilita conexiones desde tu web
|
||||
app.use(express.json());
|
||||
|
||||
// --- ENV ---
|
||||
// =========================
|
||||
// VARIABLES DE ENTORNO
|
||||
// =========================
|
||||
const {
|
||||
DATABASE_URL,
|
||||
JWT_SECRET,
|
||||
@@ -21,22 +25,28 @@ const {
|
||||
} = process.env;
|
||||
|
||||
if (!DATABASE_URL || !JWT_SECRET) {
|
||||
console.error("ERROR FATAL: Faltan DATABASE_URL o JWT_SECRET");
|
||||
console.error("❌ ERROR FATAL: Faltan variables DATABASE_URL o JWT_SECRET");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// --- DB ---
|
||||
// =========================
|
||||
// CONEXIÓN BASE DE DATOS (CORREGIDO)
|
||||
// =========================
|
||||
const pool = new Pool({
|
||||
connectionString: DATABASE_URL,
|
||||
ssl: DATABASE_URL.includes("localhost") ? false : { rejectUnauthorized: false }
|
||||
ssl: false // <--- ESTO ARREGLA EL ERROR DE REINICIO
|
||||
});
|
||||
|
||||
// --- RUTA HEALTH CHECK (Para evitar el 404/502) ---
|
||||
// =========================
|
||||
// RUTA DE "ESTOY VIVO"
|
||||
// =========================
|
||||
app.get("/", (req, res) => {
|
||||
res.status(200).send("IntegraRepara API Online");
|
||||
res.status(200).send("🚀 IntegraRepara API v1.0 - Online");
|
||||
});
|
||||
|
||||
// --- HELPERS ---
|
||||
// =========================
|
||||
// FUNCIONES DE AYUDA
|
||||
// =========================
|
||||
function normalizePhone(phone) {
|
||||
let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, "");
|
||||
if (!p) return "";
|
||||
@@ -58,139 +68,146 @@ function signToken(user) {
|
||||
);
|
||||
}
|
||||
|
||||
// --- WHATSAPP ---
|
||||
// Middleware para proteger rutas
|
||||
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" });
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// WHATSAPP (EVOLUTION API)
|
||||
// =========================
|
||||
async function sendWhatsAppCode(phone, code) {
|
||||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
||||
console.log("Simulando envío WhatsApp (Faltan claves):", code);
|
||||
return { ok: true };
|
||||
console.log("⚠️ Evolution no configurado. Código simulado:", code);
|
||||
return { ok: true, skipped: true };
|
||||
}
|
||||
try {
|
||||
// Detectamos si la URL base termina en / o no
|
||||
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
||||
const url = `${baseUrl}/message/sendText/${EVOLUTION_INSTANCE}`;
|
||||
|
||||
const body = {
|
||||
number: phone.replace("+", ""),
|
||||
text: `Tu código es: ${code}`
|
||||
text: `🔐 Tu código IntegraRepara es: *${code}*\n\nNo lo compartas.`
|
||||
};
|
||||
|
||||
// Usamos fetch nativo de Node.js
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"apikey": EVOLUTION_API_KEY
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const txt = await res.text();
|
||||
console.error("Error Evolution:", txt);
|
||||
console.error("❌ Error Evolution:", txt);
|
||||
return { ok: false };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
console.error("Error envío:", e);
|
||||
console.error("❌ Error enviando WhatsApp:", e);
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
|
||||
// --- RUTAS ---
|
||||
// =========================
|
||||
// RUTAS
|
||||
// =========================
|
||||
|
||||
// Registro
|
||||
// 1. REGISTRO
|
||||
app.post("/auth/register", async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { fullName, phone, address, dni, email, password } = req.body;
|
||||
const p = normalizePhone(phone);
|
||||
if (!fullName || !p || !email || !password) return res.status(400).json({error: "Faltan datos"});
|
||||
|
||||
if (!fullName || !p || !email || !password) {
|
||||
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios" });
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Check usuario
|
||||
const check = await client.query("SELECT * FROM users WHERE email=$1 OR phone=$2", [email, p]);
|
||||
// Comprobar si existe
|
||||
const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]);
|
||||
let userId;
|
||||
|
||||
if (check.rowCount > 0) {
|
||||
const u = check.rows[0];
|
||||
if (u.is_verified) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(409).json({error: "Usuario ya existe"});
|
||||
}
|
||||
// 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;
|
||||
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: "Usuario ya registrado y verificado." });
|
||||
}
|
||||
// Actualizar usuario existente no verificado
|
||||
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;
|
||||
} else {
|
||||
// Nuevo
|
||||
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]);
|
||||
userId = ins.rows[0].id;
|
||||
// Crear nuevo
|
||||
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",
|
||||
[fullName, p, address, dni, email, passwordHash]
|
||||
);
|
||||
userId = insert.rows[0].id;
|
||||
}
|
||||
|
||||
// Código
|
||||
// Código de verificación
|
||||
const code = genCode6();
|
||||
const hash = await bcrypt.hash(code, 10);
|
||||
const exp = new Date(Date.now() + 600000);
|
||||
|
||||
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, hash, exp]);
|
||||
|
||||
const codeHash = await bcrypt.hash(code, 10);
|
||||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 min
|
||||
|
||||
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]
|
||||
);
|
||||
|
||||
await sendWhatsAppCode(p, code);
|
||||
await client.query('COMMIT');
|
||||
|
||||
res.json({ok: true, phone: p});
|
||||
await client.query('COMMIT');
|
||||
res.json({ ok: true, phone: p, msg: "Código enviado" });
|
||||
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
console.error(e);
|
||||
res.status(500).json({error: "Error servidor"});
|
||||
console.error("Error en Registro:", e);
|
||||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
// Verificación
|
||||
// 2. VERIFICAR CÓDIGO
|
||||
app.post("/auth/verify", async (req, res) => {
|
||||
try {
|
||||
const { phone, code } = req.body;
|
||||
const p = normalizePhone(phone);
|
||||
|
||||
const q = await pool.query(`
|
||||
SELECT lc.*, u.id as uid, u.email, u.phone
|
||||
FROM login_codes lc JOIN users u ON lc.user_id = u.id
|
||||
WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW()
|
||||
ORDER BY lc.created_at DESC LIMIT 1`, [p]);
|
||||
|
||||
if (q.rowCount === 0) return res.status(400).json({error: "Código inválido"});
|
||||
|
||||
const valid = await bcrypt.compare(String(code), q.rows[0].code_hash);
|
||||
if (!valid) return res.status(400).json({error: "Código incorrecto"});
|
||||
|
||||
await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [q.rows[0].id]);
|
||||
await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [q.rows[0].uid]);
|
||||
|
||||
const token = signToken({id: q.rows[0].uid, email: q.rows[0].email, phone: p});
|
||||
res.json({ok: true, token});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.status(500).json({error: "Error verify"});
|
||||
}
|
||||
});
|
||||
try {
|
||||
const { phone, code } = req.body;
|
||||
const p = normalizePhone(phone);
|
||||
|
||||
const q = await pool.query(`
|
||||
SELECT lc.*, u.id as uid, u.email
|
||||
FROM login_codes lc
|
||||
JOIN users u ON lc.user_id = u.id
|
||||
WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW()
|
||||
ORDER BY lc.created_at DESC LIMIT 1`,
|
||||
[p]
|
||||
);
|
||||
|
||||
// Login
|
||||
app.post("/auth/login", async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
const q = await pool.query("SELECT * FROM users WHERE email=$1", [email]);
|
||||
if (q.rowCount === 0) return res.status(401).json({error: "Credenciales"});
|
||||
|
||||
const u = q.rows[0];
|
||||
const match = await bcrypt.compare(password, u.password_hash);
|
||||
if (!match) return res.status(401).json({error: "Credenciales"});
|
||||
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;
|
||||
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`));
|
||||
if (q.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({ ok: false, error: "Código incorrecto" });
|
||||
|
||||
await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1
|
||||
Reference in New Issue
Block a user