394 lines
12 KiB
JavaScript
394 lines
12 KiB
JavaScript
import express from "express";
|
|
import cors from "cors";
|
|
import bcrypt from "bcryptjs";
|
|
import jwt from "jsonwebtoken";
|
|
import pg from "pg";
|
|
|
|
const { Pool } = pg;
|
|
const app = express();
|
|
|
|
// =========================
|
|
// MIDDLEWARES
|
|
// =========================
|
|
app.use(cors());
|
|
app.use(express.json());
|
|
|
|
// =========================
|
|
// VARIABLES DE ENTORNO
|
|
// =========================
|
|
const {
|
|
DATABASE_URL,
|
|
JWT_SECRET,
|
|
EVOLUTION_BASE_URL,
|
|
EVOLUTION_API_KEY,
|
|
EVOLUTION_INSTANCE,
|
|
} = process.env;
|
|
|
|
if (!DATABASE_URL || !JWT_SECRET) {
|
|
console.error("❌ ERROR FATAL: Faltan variables DATABASE_URL o JWT_SECRET");
|
|
process.exit(1);
|
|
}
|
|
|
|
// =========================
|
|
// CONEXIÓN DB
|
|
// =========================
|
|
const pool = new Pool({
|
|
connectionString: DATABASE_URL,
|
|
ssl: false // Correcto para Coolify interno
|
|
});
|
|
|
|
// ==========================================
|
|
// 🛠️ RUTA DE INSTALACIÓN (ACTUALIZADA)
|
|
// ==========================================
|
|
app.get("/setup-db", async (req, res) => {
|
|
const client = await pool.connect();
|
|
try {
|
|
// 1. TABLAS ORIGINALES
|
|
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()
|
|
);
|
|
`);
|
|
|
|
// 2. NUEVAS TABLAS (Gremios y Roles)
|
|
await client.query(`
|
|
CREATE TABLE IF NOT EXISTS guilds (
|
|
id SERIAL PRIMARY KEY,
|
|
name TEXT UNIQUE NOT NULL,
|
|
created_at TIMESTAMP DEFAULT NOW()
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS user_guilds (
|
|
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
|
guild_id INT REFERENCES guilds(id) ON DELETE CASCADE,
|
|
PRIMARY KEY (user_id, guild_id)
|
|
);
|
|
`);
|
|
|
|
// 3. ACTUALIZAR USUARIOS (Añadir columna role si no existe)
|
|
try {
|
|
await client.query(`ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'operario'`);
|
|
} catch (e) {
|
|
// Ignoramos error si la columna ya existe
|
|
}
|
|
|
|
res.send("✅ ¡Base de datos actualizada! Tablas y Roles listos.");
|
|
} catch (e) {
|
|
console.error(e);
|
|
res.status(500).send("❌ Error configurando DB: " + e.message);
|
|
} finally {
|
|
client.release();
|
|
}
|
|
});
|
|
|
|
// =========================
|
|
// RUTA DE "ESTOY VIVO"
|
|
// =========================
|
|
app.get("/", (req, res) => {
|
|
res.status(200).send("🚀 IntegraRepara API v1.0 - Online");
|
|
});
|
|
|
|
// =========================
|
|
// HELPERS
|
|
// =========================
|
|
function normalizePhone(phone) {
|
|
let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, "");
|
|
if (!p) return "";
|
|
if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) {
|
|
return "+34" + p;
|
|
}
|
|
return p;
|
|
}
|
|
|
|
function genCode6() {
|
|
return String(Math.floor(100000 + Math.random() * 900000));
|
|
}
|
|
|
|
function signToken(user) {
|
|
// AÑADIDO: Incluimos el 'role' en el token
|
|
return jwt.sign(
|
|
{ sub: user.id, phone: user.phone, email: user.email, role: user.role || 'operario' },
|
|
JWT_SECRET,
|
|
{ expiresIn: "30d" }
|
|
);
|
|
}
|
|
|
|
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
|
|
// =========================
|
|
async function sendWhatsAppCode(phone, code) {
|
|
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
|
console.log("⚠️ Evolution no configurado. Código simulado:", code);
|
|
return { ok: true, skipped: true };
|
|
}
|
|
try {
|
|
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
|
const url = `${baseUrl}/message/sendText/${EVOLUTION_INSTANCE}`;
|
|
|
|
const body = {
|
|
number: phone.replace("+", ""),
|
|
text: `🔐 Tu código IntegraRepara es: *${code}*\n\nNo lo compartas.`
|
|
};
|
|
|
|
const res = await fetch(url, {
|
|
method: "POST",
|
|
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);
|
|
return { ok: false };
|
|
}
|
|
return { ok: true };
|
|
} catch (e) {
|
|
console.error("❌ Error enviando WhatsApp:", e);
|
|
return { ok: false };
|
|
}
|
|
}
|
|
|
|
// =========================
|
|
// RUTAS ORIGINALES
|
|
// =========================
|
|
|
|
// 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({ ok: false, error: "Faltan datos obligatorios" });
|
|
}
|
|
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
|
|
|
await client.query('BEGIN');
|
|
|
|
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: "Usuario ya registrado y 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 {
|
|
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;
|
|
}
|
|
|
|
const code = genCode6();
|
|
const codeHash = await bcrypt.hash(code, 10);
|
|
const expiresAt = new Date(Date.now() + 10 * 60 * 1000);
|
|
|
|
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, msg: "Código enviado" });
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
console.error("Error en Registro:", e);
|
|
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
|
} finally {
|
|
client.release();
|
|
}
|
|
});
|
|
|
|
// 2. VERIFICACIÓN
|
|
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.role
|
|
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({ ok: false, error: "Código inválido o expirado" });
|
|
|
|
const row = q.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" });
|
|
|
|
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]);
|
|
|
|
// Incluimos role en el token
|
|
const token = signToken({ id: row.uid, email: row.email, phone: p, role: row.role });
|
|
res.json({ ok: true, token });
|
|
} catch (e) {
|
|
console.error("Error Verify:", e);
|
|
res.status(500).json({ ok: false, error: "Error verificando código" });
|
|
}
|
|
});
|
|
|
|
// 3. 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({ ok: false, error: "Credenciales inválidas" });
|
|
|
|
const u = q.rows[0];
|
|
const match = await bcrypt.compare(password, u.password_hash);
|
|
|
|
if (!match) return res.status(401).json({ ok: false, error: "Credenciales inválidas" });
|
|
if (!u.is_verified) return res.status(403).json({ ok: false, error: "Cuenta no verificada" });
|
|
|
|
res.json({ ok: true, token: signToken(u) });
|
|
} catch(e) {
|
|
console.error("Error Login:", e);
|
|
res.status(500).json({ ok: false, error: "Error en login" });
|
|
}
|
|
});
|
|
|
|
// 4. SERVICIOS (PROTEGIDO)
|
|
app.get("/services", authMiddleware, async (req, res) => {
|
|
try {
|
|
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 });
|
|
} catch (e) {
|
|
res.status(500).json({ ok: false, error: "Error al obtener servicios" });
|
|
}
|
|
});
|
|
|
|
// =========================
|
|
// NUEVAS RUTAS: CONFIGURACIÓN
|
|
// =========================
|
|
|
|
// 5. GESTIÓN DE GREMIOS
|
|
app.get("/guilds", authMiddleware, async (req, res) => {
|
|
try {
|
|
const q = await pool.query("SELECT * FROM guilds ORDER BY name ASC");
|
|
res.json({ ok: true, guilds: q.rows });
|
|
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
|
});
|
|
|
|
app.post("/guilds", authMiddleware, async (req, res) => {
|
|
try {
|
|
const { name } = req.body;
|
|
if (!name) return res.status(400).json({ ok: false, error: "Falta nombre" });
|
|
const q = await pool.query("INSERT INTO guilds (name) VALUES ($1) RETURNING *", [name.toUpperCase()]);
|
|
res.json({ ok: true, guild: q.rows[0] });
|
|
} catch (e) { res.status(500).json({ ok: false, error: "Error o gremio duplicado" }); }
|
|
});
|
|
|
|
app.delete("/guilds/:id", authMiddleware, async (req, res) => {
|
|
try {
|
|
await pool.query("DELETE FROM guilds WHERE id = $1", [req.params.id]);
|
|
res.json({ ok: true });
|
|
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
|
});
|
|
|
|
// 6. CREAR USUARIO (ADMIN)
|
|
app.post("/admin/users", authMiddleware, async (req, res) => {
|
|
const client = await pool.connect();
|
|
try {
|
|
const { fullName, email, password, role, guilds } = req.body;
|
|
|
|
// Validación
|
|
if (!email || !password || !fullName) {
|
|
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios" });
|
|
}
|
|
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
|
// Generamos un teléfono dummy porque la base de datos lo exige (UNIQUE)
|
|
const dummyPhone = `manual_${Date.now()}`;
|
|
|
|
await client.query('BEGIN');
|
|
|
|
// Insertar usuario
|
|
const insert = await client.query(
|
|
`INSERT INTO users (full_name, email, password_hash, role, phone, is_verified)
|
|
VALUES ($1, $2, $3, $4, $5, TRUE) RETURNING id`,
|
|
[fullName, email, passwordHash, role || 'operario', dummyPhone]
|
|
);
|
|
const userId = insert.rows[0].id;
|
|
|
|
// Asignar Gremios
|
|
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]);
|
|
}
|
|
}
|
|
|
|
await client.query('COMMIT');
|
|
res.json({ ok: true, msg: "Usuario creado correctamente" });
|
|
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
console.error(e);
|
|
res.status(500).json({ ok: false, error: "Error creando usuario (Email duplicado?)" });
|
|
} finally {
|
|
client.release();
|
|
}
|
|
});
|
|
|
|
// ARRANCAR
|
|
const port = process.env.PORT || 3000;
|
|
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); |