Actualizar server.js

This commit is contained in:
2026-02-07 23:55:21 +00:00
parent 23dcaa8b76
commit 45160f685f

View File

@@ -34,16 +34,19 @@ if (!DATABASE_URL || !JWT_SECRET) {
// ========================= // =========================
const pool = new Pool({ const pool = new Pool({
connectionString: DATABASE_URL, connectionString: DATABASE_URL,
ssl: false // Correcto para Coolify interno ssl: false
}); });
// ========================================== // ==========================================
// 🛠️ RUTA DE INSTALACIÓN (ACTUALIZADA) // 🧠 CEREBRO DE AUTO-ACTUALIZACIÓN (NUEVO)
// ========================================== // ==========================================
app.get("/setup-db", async (req, res) => { // Esta función se ejecuta sola al arrancar y repara la DB
async function autoUpdateDB() {
const client = await pool.connect(); const client = await pool.connect();
try { try {
// 1. TABLAS ORIGINALES console.log("🔄 Verificando salud de la base de datos...");
// 1. Crear tablas base si no existen
await client.query(` await client.query(`
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
@@ -56,6 +59,7 @@ app.get("/setup-db", async (req, res) => {
is_verified BOOLEAN DEFAULT FALSE, is_verified BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW() created_at TIMESTAMP DEFAULT NOW()
); );
CREATE TABLE IF NOT EXISTS login_codes ( CREATE TABLE IF NOT EXISTS login_codes (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id) ON DELETE CASCADE, user_id INT REFERENCES users(id) ON DELETE CASCADE,
@@ -66,6 +70,7 @@ app.get("/setup-db", async (req, res) => {
expires_at TIMESTAMP NOT NULL, expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT NOW() created_at TIMESTAMP DEFAULT NOW()
); );
CREATE TABLE IF NOT EXISTS services ( CREATE TABLE IF NOT EXISTS services (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id) ON DELETE CASCADE, user_id INT REFERENCES users(id) ON DELETE CASCADE,
@@ -76,10 +81,7 @@ app.get("/setup-db", async (req, res) => {
notes TEXT, notes TEXT,
created_at TIMESTAMP DEFAULT NOW() created_at TIMESTAMP DEFAULT NOW()
); );
`);
// 2. NUEVAS TABLAS (Gremios y Roles)
await client.query(`
CREATE TABLE IF NOT EXISTS guilds ( CREATE TABLE IF NOT EXISTS guilds (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL, name TEXT UNIQUE NOT NULL,
@@ -93,28 +95,25 @@ app.get("/setup-db", async (req, res) => {
); );
`); `);
// 3. ACTUALIZAR USUARIOS (Añadir columna role si no existe) // 2. PARCHE INTELIGENTE: Añadir columna 'role' si falta
try { // Este bloque es la CLAVE: comprueba si existe 'role', si no, la crea.
await client.query(`ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'operario'`); await client.query(`
} catch (e) { DO $$
// Ignoramos error si la columna ya existe BEGIN
} IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='role') THEN
ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'operario';
RAISE NOTICE '✅ Columna ROLE añadida automáticamente';
END IF;
END $$;
`);
res.send("✅ ¡Base de datos actualizada! Tablas y Roles listos."); console.log("✅ Base de datos Sincronizada y Lista.");
} catch (e) { } catch (e) {
console.error(e); console.error("❌ Error en auto-actualización:", e);
res.status(500).send("❌ Error configurando DB: " + e.message);
} finally { } finally {
client.release(); client.release();
} }
}); }
// =========================
// RUTA DE "ESTOY VIVO"
// =========================
app.get("/", (req, res) => {
res.status(200).send("🚀 IntegraRepara API v1.0 - Online");
});
// ========================= // =========================
// HELPERS // HELPERS
@@ -133,7 +132,6 @@ function genCode6() {
} }
function signToken(user) { function signToken(user) {
// AÑADIDO: Incluimos el 'role' en el token
return jwt.sign( return jwt.sign(
{ sub: user.id, phone: user.phone, email: user.email, role: user.role || 'operario' }, { sub: user.id, phone: user.phone, email: user.email, role: user.role || 'operario' },
JWT_SECRET, JWT_SECRET,
@@ -190,7 +188,7 @@ async function sendWhatsAppCode(phone, code) {
} }
// ========================= // =========================
// RUTAS ORIGINALES // RUTAS
// ========================= // =========================
// 1. REGISTRO // 1. REGISTRO
@@ -277,7 +275,6 @@ app.post("/auth/verify", async (req, res) => {
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]);
// Incluimos role en el token
const token = signToken({ id: row.uid, email: row.email, phone: p, role: row.role }); const token = signToken({ id: row.uid, email: row.email, phone: p, role: row.role });
res.json({ ok: true, token }); res.json({ ok: true, token });
} catch (e) { } catch (e) {
@@ -317,10 +314,6 @@ app.get("/services", authMiddleware, async (req, res) => {
} }
}); });
// =========================
// NUEVAS RUTAS: CONFIGURACIÓN
// =========================
// 5. GESTIÓN DE GREMIOS // 5. GESTIÓN DE GREMIOS
app.get("/guilds", authMiddleware, async (req, res) => { app.get("/guilds", authMiddleware, async (req, res) => {
try { try {
@@ -351,18 +344,13 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
try { try {
const { fullName, email, password, role, guilds } = req.body; const { fullName, email, password, role, guilds } = req.body;
// Validación if (!email || !password || !fullName) return res.status(400).json({ ok: false, error: "Faltan datos" });
if (!email || !password || !fullName) {
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios" });
}
const passwordHash = await bcrypt.hash(password, 10); 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()}`; const dummyPhone = `manual_${Date.now()}`;
await client.query('BEGIN'); await client.query('BEGIN');
// Insertar usuario
const insert = await client.query( const insert = await client.query(
`INSERT INTO users (full_name, email, password_hash, role, phone, is_verified) `INSERT INTO users (full_name, email, password_hash, role, phone, is_verified)
VALUES ($1, $2, $3, $4, $5, TRUE) RETURNING id`, VALUES ($1, $2, $3, $4, $5, TRUE) RETURNING id`,
@@ -370,7 +358,6 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
); );
const userId = insert.rows[0].id; const userId = insert.rows[0].id;
// Asignar Gremios
if (guilds && Array.isArray(guilds)) { if (guilds && Array.isArray(guilds)) {
for (const guildId of 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("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, guildId]);
@@ -378,17 +365,24 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
} }
await client.query('COMMIT'); await client.query('COMMIT');
res.json({ ok: true, msg: "Usuario creado correctamente" }); res.json({ ok: true, msg: "Usuario creado" });
} 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 creando usuario (Email duplicado?)" }); res.status(500).json({ ok: false, error: "Error creando usuario" });
} finally { } finally {
client.release(); client.release();
} }
}); });
// ARRANCAR // =========================
// ARRANCAR SERVIDOR Y AUTO-UPDATE
// =========================
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}`));
// Primero ejecutamos la actualización, y SOLO CUANDO TERMINE, arrancamos el server
autoUpdateDB().then(() => {
app.listen(port, "0.0.0.0", () => {
console.log(`🚀 Server OK en puerto ${port} (DB Sincronizada)`);
});
});