'use strict'; const express = require('express'); const bcrypt = require('bcrypt'); const path = require('path'); const router = express.Router(); const { getDb } = require('../db'); const { requireAuth, requireAdmin } = require('../auth'); const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); const BCRYPT_ROUNDS = 12; // All admin routes require authentication + admin privilege router.use(requireAuth, requireAdmin); // --------------------------------------------------------------------------- // GET /api/admin/users // Returns all users. // --------------------------------------------------------------------------- router.get('/users', (req, res) => { const db = getDb(); const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all(); res.json({ users: users.map(u => ({ id: u.id, username: u.username, isAdmin: u.is_admin === 1, permissions: JSON.parse(u.permissions || '{}'), })), }); }); // --------------------------------------------------------------------------- // POST /api/admin/users // Body: { username, password, isAdmin, permissions } // Creates a new user. // --------------------------------------------------------------------------- router.post('/users', (req, res) => { const { username, password, isAdmin, permissions } = req.body; if (!username || !password || password.length < 8) { return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); } const db = getDb(); const exists = db.prepare('SELECT id FROM users WHERE username = ?').get([username]); if (exists) return res.status(409).json({ error: 'Username already exists.' }); const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run( [username, hash, isAdmin ? 1 : 0, JSON.stringify(permissions || {})] ); res.status(201).json({ ok: true }); }); // --------------------------------------------------------------------------- // PATCH /api/admin/users/:id // Body: { password?, isAdmin?, permissions? } // Updates an existing user. At least one field must be present. // --------------------------------------------------------------------------- router.patch('/users/:id', (req, res) => { const db = getDb(); const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); if (!user) return res.status(404).json({ error: 'User not found.' }); const { password, isAdmin, permissions } = req.body; // Prevent removing the last admin if (isAdmin === false || isAdmin === 0) { const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; if (adminCount <= 1 && user.is_admin === 1) { return res.status(400).json({ error: 'Cannot remove the last admin account.' }); } } if (password !== undefined) { if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' }); const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]); } if (isAdmin !== undefined) { db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]); } if (permissions !== undefined) { db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(permissions), user.id]); } res.json({ ok: true }); }); // --------------------------------------------------------------------------- // DELETE /api/admin/users/:id // Deletes a user. Cannot delete yourself or the last admin. // --------------------------------------------------------------------------- router.delete('/users/:id', (req, res) => { const db = getDb(); const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); if (!user) return res.status(404).json({ error: 'User not found.' }); if (String(user.id) === String(req.user.id)) { return res.status(400).json({ error: 'Cannot delete your own account.' }); } if (user.is_admin === 1) { const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; if (adminCount <= 1) { return res.status(400).json({ error: 'Cannot delete the last admin account.' }); } } db.prepare('DELETE FROM users WHERE id = ?').run([user.id]); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // GET /api/admin/config // Returns the current server config (paths, port). // --------------------------------------------------------------------------- router.get('/config', (req, res) => { const config = loadConfig(); const effective = getEffectivePaths(config.paths || []); res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective }); }); // --------------------------------------------------------------------------- // PUT /api/admin/config // Body: { paths: [...], port: number } // Saves the config. // --------------------------------------------------------------------------- router.put('/config', (req, res) => { const { paths, port } = req.body; if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' }); const config = loadConfig(); config.paths = paths.map(p => p.trim()).filter(Boolean); if (port !== undefined) { const p = parseInt(port, 10); if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' }); config.port = p; } try { saveConfig(config); } catch (err) { return res.status(500).json({ error: `Failed to save config: ${err.message}` }); } res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) }); }); // --------------------------------------------------------------------------- // POST /api/admin/shutdown // Responds immediately then gracefully closes the server and DB. // --------------------------------------------------------------------------- router.post('/shutdown', (req, res) => { res.json({ ok: true }); // Defer so the response is flushed before we start closing. setImmediate(() => { const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown'); if (typeof fn === 'function') fn(); }); }); module.exports = router;