Actualizar server.js
This commit is contained in:
80
server.js
80
server.js
@@ -34,16 +34,19 @@ if (!DATABASE_URL || !JWT_SECRET) {
|
||||
// =========================
|
||||
const pool = new Pool({
|
||||
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();
|
||||
try {
|
||||
// 1. TABLAS ORIGINALES
|
||||
console.log("🔄 Verificando salud de la base de datos...");
|
||||
|
||||
// 1. Crear tablas base si no existen
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -56,6 +59,7 @@ app.get("/setup-db", async (req, res) => {
|
||||
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,
|
||||
@@ -66,6 +70,7 @@ app.get("/setup-db", async (req, res) => {
|
||||
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,
|
||||
@@ -76,10 +81,7 @@ app.get("/setup-db", async (req, res) => {
|
||||
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,
|
||||
@@ -93,28 +95,25 @@ app.get("/setup-db", async (req, res) => {
|
||||
);
|
||||
`);
|
||||
|
||||
// 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
|
||||
}
|
||||
// 2. PARCHE INTELIGENTE: Añadir columna 'role' si falta
|
||||
// Este bloque es la CLAVE: comprueba si existe 'role', si no, la crea.
|
||||
await client.query(`
|
||||
DO $$
|
||||
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) {
|
||||
console.error(e);
|
||||
res.status(500).send("❌ Error configurando DB: " + e.message);
|
||||
console.error("❌ Error en auto-actualización:", e);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
// =========================
|
||||
// RUTA DE "ESTOY VIVO"
|
||||
// =========================
|
||||
app.get("/", (req, res) => {
|
||||
res.status(200).send("🚀 IntegraRepara API v1.0 - Online");
|
||||
});
|
||||
}
|
||||
|
||||
// =========================
|
||||
// HELPERS
|
||||
@@ -133,7 +132,6 @@ function genCode6() {
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -190,7 +188,7 @@ async function sendWhatsAppCode(phone, code) {
|
||||
}
|
||||
|
||||
// =========================
|
||||
// RUTAS ORIGINALES
|
||||
// RUTAS
|
||||
// =========================
|
||||
|
||||
// 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 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) {
|
||||
@@ -317,10 +314,6 @@ app.get("/services", authMiddleware, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// =========================
|
||||
// NUEVAS RUTAS: CONFIGURACIÓN
|
||||
// =========================
|
||||
|
||||
// 5. GESTIÓN DE GREMIOS
|
||||
app.get("/guilds", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
@@ -351,18 +344,13 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
|
||||
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" });
|
||||
}
|
||||
if (!email || !password || !fullName) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||||
|
||||
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`,
|
||||
@@ -370,7 +358,6 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
|
||||
);
|
||||
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]);
|
||||
@@ -378,17 +365,24 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
res.json({ ok: true, msg: "Usuario creado correctamente" });
|
||||
|
||||
res.json({ ok: true, msg: "Usuario creado" });
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
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 {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
// ARRANCAR
|
||||
// =========================
|
||||
// ARRANCAR SERVIDOR Y AUTO-UPDATE
|
||||
// =========================
|
||||
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)`);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user