Actualizar server.js
This commit is contained in:
204
server.js
204
server.js
@@ -80,7 +80,7 @@ async function autoUpdateDB() {
|
|||||||
);
|
);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
// Parches de columnas
|
// Parches
|
||||||
await client.query(`
|
await client.query(`
|
||||||
DO $$ BEGIN
|
DO $$ BEGIN
|
||||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='role') THEN
|
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='role') THEN
|
||||||
@@ -99,18 +99,11 @@ async function autoUpdateDB() {
|
|||||||
`);
|
`);
|
||||||
|
|
||||||
try { await client.query(`ALTER TABLE guilds DROP CONSTRAINT IF EXISTS guilds_name_key`); } catch (e) {}
|
try { await client.query(`ALTER TABLE guilds DROP CONSTRAINT IF EXISTS guilds_name_key`); } catch (e) {}
|
||||||
|
|
||||||
console.log("✅ DB Sincronizada.");
|
console.log("✅ DB Sincronizada.");
|
||||||
} catch (e) {
|
} catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); }
|
||||||
console.error("❌ Error DB:", e);
|
|
||||||
} finally {
|
|
||||||
client.release();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
|
||||||
// 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 "";
|
||||||
@@ -123,8 +116,7 @@ function signToken(user) {
|
|||||||
const accountId = user.owner_id || user.id;
|
const accountId = user.owner_id || user.id;
|
||||||
return jwt.sign(
|
return jwt.sign(
|
||||||
{ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId: accountId },
|
{ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId: accountId },
|
||||||
JWT_SECRET,
|
JWT_SECRET, { expiresIn: "30d" }
|
||||||
{ expiresIn: "30d" }
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,8 +128,21 @@ function authMiddleware(req, res, next) {
|
|||||||
catch { return res.status(401).json({ ok: false, error: "Token inválido" }); }
|
catch { return res.status(401).json({ ok: false, error: "Token inválido" }); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function sendWhatsAppCode(phone, code) {
|
||||||
|
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
||||||
|
console.log("⚠️ Evolution no configurado. Código:", code);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`;
|
||||||
|
await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
||||||
|
body: JSON.stringify({ number: phone.replace("+", ""), text: `🔐 Código IntegraRepara: *${code}*` })
|
||||||
|
}).catch(console.error);
|
||||||
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// RUTAS
|
// RUTAS DE AUTENTICACIÓN
|
||||||
// =========================
|
// =========================
|
||||||
|
|
||||||
// REGISTRO
|
// REGISTRO
|
||||||
@@ -176,20 +181,14 @@ app.post("/auth/register", async (req, res) => {
|
|||||||
|
|
||||||
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("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]);
|
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);
|
||||||
if (EVOLUTION_BASE_URL && EVOLUTION_API_KEY) {
|
|
||||||
const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`;
|
|
||||||
await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, body: JSON.stringify({ number: p.replace("+", ""), text: `🔐 Código: *${code}*` }) }).catch(console.error);
|
|
||||||
}
|
|
||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
res.json({ ok: true, phone: p });
|
res.json({ ok: true, phone: p });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
res.status(500).json({ ok: false, error: "Error server" });
|
res.status(500).json({ ok: false, error: "Error server" });
|
||||||
} finally {
|
} finally { client.release(); }
|
||||||
client.release();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// VERIFICACIÓN & LOGIN
|
// VERIFICACIÓN & LOGIN
|
||||||
@@ -218,7 +217,86 @@ app.post("/auth/login", async (req, res) => {
|
|||||||
} catch(e) { res.status(500).json({ ok: false, error: "Error login" }); }
|
} catch(e) { res.status(500).json({ ok: false, error: "Error login" }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
// SERVICES
|
// 🆕 NUEVO: RECUPERAR CONTRASEÑA 🆕
|
||||||
|
|
||||||
|
// Paso 1: Solicitar código con DNI y Teléfono
|
||||||
|
app.post("/auth/forgot-password", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { dni, phone } = req.body;
|
||||||
|
const p = normalizePhone(phone);
|
||||||
|
|
||||||
|
// Buscamos usuario por DNI y Teléfono
|
||||||
|
const userQuery = await pool.query("SELECT id FROM users WHERE dni = $1 AND phone = $2", [dni, p]);
|
||||||
|
|
||||||
|
if (userQuery.rowCount === 0) {
|
||||||
|
return res.status(404).json({ ok: false, error: "No coinciden los datos." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = userQuery.rows[0].id;
|
||||||
|
const code = genCode6();
|
||||||
|
const codeHash = await bcrypt.hash(code, 10);
|
||||||
|
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 min
|
||||||
|
|
||||||
|
// Guardamos con propósito 'password_reset'
|
||||||
|
await pool.query("INSERT INTO login_codes (user_id, phone, code_hash, purpose, expires_at) VALUES ($1, $2, $3, 'password_reset', $4)",
|
||||||
|
[userId, p, codeHash, expiresAt]);
|
||||||
|
|
||||||
|
await sendWhatsAppCode(p, code);
|
||||||
|
res.json({ ok: true, msg: "Código enviado" });
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
res.status(500).json({ ok: false, error: "Error interno" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Paso 2: Resetear contraseña
|
||||||
|
app.post("/auth/reset-password", async (req, res) => {
|
||||||
|
const client = await pool.connect();
|
||||||
|
try {
|
||||||
|
const { phone, code, newPassword } = req.body;
|
||||||
|
const p = normalizePhone(phone);
|
||||||
|
|
||||||
|
// Buscar código válido para reset
|
||||||
|
const codeQuery = await client.query(`
|
||||||
|
SELECT lc.*, u.id as uid
|
||||||
|
FROM login_codes lc
|
||||||
|
JOIN users u ON lc.user_id = u.id
|
||||||
|
WHERE lc.phone=$1
|
||||||
|
AND lc.purpose='password_reset'
|
||||||
|
AND lc.consumed_at IS NULL
|
||||||
|
AND lc.expires_at > NOW()
|
||||||
|
ORDER BY lc.created_at DESC LIMIT 1
|
||||||
|
`, [p]);
|
||||||
|
|
||||||
|
if (codeQuery.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o expirado" });
|
||||||
|
|
||||||
|
const row = codeQuery.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" });
|
||||||
|
|
||||||
|
// Cambiar contraseña
|
||||||
|
const newHash = await bcrypt.hash(newPassword, 10);
|
||||||
|
|
||||||
|
await client.query('BEGIN');
|
||||||
|
await client.query("UPDATE users SET password_hash=$1 WHERE id=$2", [newHash, row.uid]);
|
||||||
|
await client.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]);
|
||||||
|
await client.query('COMMIT');
|
||||||
|
|
||||||
|
res.json({ ok: true, msg: "Contraseña actualizada" });
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
console.error(e);
|
||||||
|
res.status(500).json({ ok: false, error: "Error al cambiar contraseña" });
|
||||||
|
} finally { client.release(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// =========================
|
||||||
|
// RUTAS PROTEGIDAS
|
||||||
|
// =========================
|
||||||
|
|
||||||
app.get("/services", authMiddleware, async (req, res) => {
|
app.get("/services", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const q = await pool.query("SELECT * FROM services WHERE owner_id=$1 ORDER BY created_at DESC", [req.user.accountId]);
|
const q = await pool.query("SELECT * FROM services WHERE owner_id=$1 ORDER BY created_at DESC", [req.user.accountId]);
|
||||||
@@ -226,7 +304,6 @@ app.get("/services", authMiddleware, async (req, res) => {
|
|||||||
} catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); }
|
} catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
// GREMIOS
|
|
||||||
app.get("/guilds", authMiddleware, async (req, res) => {
|
app.get("/guilds", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]);
|
const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]);
|
||||||
@@ -250,125 +327,76 @@ app.delete("/guilds/:id", authMiddleware, async (req, res) => {
|
|||||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
// =========================
|
// ADMIN USERS
|
||||||
// GESTIÓN DE USUARIOS (CRUD COMPLETO)
|
|
||||||
// =========================
|
|
||||||
|
|
||||||
// 1. LISTAR USUARIOS (GET)
|
|
||||||
app.get("/admin/users", authMiddleware, async (req, res) => {
|
app.get("/admin/users", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
// Obtenemos usuarios y sus gremios en una sola consulta
|
|
||||||
const q = await pool.query(`
|
const q = await pool.query(`
|
||||||
SELECT u.id, u.full_name, u.email, u.phone, u.role,
|
SELECT u.id, u.full_name, u.email, u.phone, u.role, COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds
|
||||||
COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds
|
FROM users u LEFT JOIN user_guilds ug ON u.id = ug.user_id LEFT JOIN guilds g ON ug.guild_id = g.id
|
||||||
FROM users u
|
WHERE u.owner_id = $1 GROUP BY u.id ORDER BY u.id DESC
|
||||||
LEFT JOIN user_guilds ug ON u.id = ug.user_id
|
|
||||||
LEFT JOIN guilds g ON ug.guild_id = g.id
|
|
||||||
WHERE u.owner_id = $1
|
|
||||||
GROUP BY u.id
|
|
||||||
ORDER BY u.id DESC
|
|
||||||
`, [req.user.accountId]);
|
`, [req.user.accountId]);
|
||||||
|
|
||||||
res.json({ ok: true, users: q.rows });
|
res.json({ ok: true, users: q.rows });
|
||||||
} catch (e) {
|
} catch (e) { res.status(500).json({ ok: false, error: "Error listar users" }); }
|
||||||
console.error(e);
|
|
||||||
res.status(500).json({ ok: false, error: "Error al listar usuarios" });
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 2. CREAR USUARIO (POST) - AHORA CON TELÉFONO REAL
|
|
||||||
app.post("/admin/users", authMiddleware, async (req, res) => {
|
app.post("/admin/users", authMiddleware, async (req, res) => {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
const { fullName, email, password, role, guilds, phone } = req.body;
|
const { fullName, email, password, role, guilds, phone } = req.body;
|
||||||
|
if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||||||
if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false, error: "Faltan datos (nombre, email, pass, teléfono)" });
|
|
||||||
|
|
||||||
const p = normalizePhone(phone);
|
const p = normalizePhone(phone);
|
||||||
const passwordHash = await bcrypt.hash(password, 10);
|
const passwordHash = await bcrypt.hash(password, 10);
|
||||||
|
|
||||||
await client.query('BEGIN');
|
await client.query('BEGIN');
|
||||||
|
|
||||||
const insert = await client.query(
|
const insert = await client.query(
|
||||||
`INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id)
|
`INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id) VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id`,
|
||||||
VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id`,
|
|
||||||
[fullName, email, passwordHash, role || 'operario', p, req.user.accountId]
|
[fullName, email, passwordHash, role || 'operario', p, req.user.accountId]
|
||||||
);
|
);
|
||||||
const userId = insert.rows[0].id;
|
const userId = insert.rows[0].id;
|
||||||
|
|
||||||
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]);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
res.json({ ok: true, msg: "Usuario creado" });
|
res.json({ ok: true, msg: "Usuario creado" });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await client.query('ROLLBACK');
|
await client.query('ROLLBACK');
|
||||||
if (e.code === '23505') {
|
if (e.code === '23505') {
|
||||||
if (e.constraint && e.constraint.includes('email')) return res.status(400).json({ ok: false, error: "❌ El email ya existe." });
|
if (e.constraint && e.constraint.includes('email')) return res.status(400).json({ ok: false, error: "❌ Email existe." });
|
||||||
if (e.constraint && e.constraint.includes('phone')) return res.status(400).json({ ok: false, error: "❌ El teléfono ya existe." });
|
if (e.constraint && e.constraint.includes('phone')) return res.status(400).json({ ok: false, error: "❌ Teléfono existe." });
|
||||||
}
|
}
|
||||||
console.error(e);
|
|
||||||
res.status(500).json({ ok: false, error: "Error creando usuario" });
|
res.status(500).json({ ok: false, error: "Error creando usuario" });
|
||||||
} finally {
|
} finally { client.release(); }
|
||||||
client.release();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. EDITAR USUARIO (PUT)
|
|
||||||
app.put("/admin/users/:id", authMiddleware, async (req, res) => {
|
app.put("/admin/users/:id", authMiddleware, async (req, res) => {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
const userId = req.params.id;
|
const userId = req.params.id;
|
||||||
const { fullName, email, phone, role, guilds, password } = req.body;
|
const { fullName, email, phone, role, guilds, password } = req.body;
|
||||||
const p = normalizePhone(phone);
|
const p = normalizePhone(phone);
|
||||||
|
|
||||||
await client.query('BEGIN');
|
await client.query('BEGIN');
|
||||||
|
|
||||||
// Verificar que el usuario pertenece a mi empresa
|
|
||||||
const check = await client.query("SELECT id FROM users WHERE id=$1 AND owner_id=$2", [userId, req.user.accountId]);
|
const check = await client.query("SELECT id FROM users WHERE id=$1 AND owner_id=$2", [userId, req.user.accountId]);
|
||||||
if(check.rowCount === 0) throw new Error("Usuario no encontrado o no tienes permiso");
|
if(check.rowCount === 0) throw new Error("No encontrado");
|
||||||
|
|
||||||
// Actualizar datos básicos
|
|
||||||
if(password) {
|
if(password) {
|
||||||
const hash = await bcrypt.hash(password, 10);
|
const hash = await bcrypt.hash(password, 10);
|
||||||
await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5 WHERE id=$6", [fullName, email, p, role, hash, userId]);
|
await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5 WHERE id=$6", [fullName, email, p, role, hash, userId]);
|
||||||
} else {
|
} else {
|
||||||
await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, userId]);
|
await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, userId]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualizar Gremios (Borrar y Crear)
|
|
||||||
if (guilds && Array.isArray(guilds)) {
|
if (guilds && Array.isArray(guilds)) {
|
||||||
await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]);
|
await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]);
|
||||||
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]);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
res.json({ ok: true, msg: "Usuario actualizado" });
|
res.json({ ok: true, msg: "Actualizado" });
|
||||||
|
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false, error: "Error updating" }); } finally { client.release(); }
|
||||||
} catch (e) {
|
|
||||||
await client.query('ROLLBACK');
|
|
||||||
console.error(e);
|
|
||||||
res.status(500).json({ ok: false, error: "Error actualizando (Revisa email/teléfono duplicados)" });
|
|
||||||
} finally {
|
|
||||||
client.release();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 4. BORRAR USUARIO (DELETE)
|
|
||||||
app.delete("/admin/users/:id", authMiddleware, async (req, res) => {
|
app.delete("/admin/users/:id", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const result = await pool.query("DELETE FROM users WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]);
|
const result = await pool.query("DELETE FROM users WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]);
|
||||||
if (result.rowCount === 0) return res.status(404).json({ ok: false, error: "Usuario no encontrado" });
|
if (result.rowCount === 0) return res.status(404).json({ ok: false, error: "No encontrado" });
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
} catch (e) {
|
} catch (e) { res.status(500).json({ ok: false, error: "Error deleting" }); }
|
||||||
console.error(e);
|
|
||||||
res.status(500).json({ ok: false, error: "Error borrando usuario" });
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const port = process.env.PORT || 3000;
|
const port = process.env.PORT || 3000;
|
||||||
|
|||||||
Reference in New Issue
Block a user