| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const bcrypt = require('bcrypt'); |
| 5 | const path = require('path'); |
| 6 | const router = express.Router(); |
| 7 | |
| 8 | const { getDb } = require('../db'); |
| 9 | const { requireAuth, requireAdmin } = require('../auth'); |
| 10 | const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); |
| 11 | |
| 12 | const BCRYPT_ROUNDS = 12; |
| 13 | |
| 14 | function normalizePermissions (permissions) |
| 15 | { |
| 16 | if (!permissions || typeof permissions !== 'object') return {}; |
| 17 | |
| 18 | const normalized = {}; |
| 19 | for (const [key, value] of Object.entries(permissions)) |
| 20 | { |
| 21 | if (!value || typeof value !== 'object') continue; |
| 22 | const write = !!value.write; |
| 23 | const read = !!value.read || write; |
| 24 | if (!read && !write) continue; |
| 25 | normalized[key] = { read, write }; |
| 26 | } |
| 27 | |
| 28 | return normalized; |
| 29 | } |
| 30 | |
| 31 | // All admin routes require authentication + admin privilege |
| 32 | router.use(requireAuth, requireAdmin); |
| 33 | |
| 34 | // --------------------------------------------------------------------------- |
| 35 | // GET /api/admin/users |
| 36 | // Returns all users. |
| 37 | // --------------------------------------------------------------------------- |
| 38 | router.get('/users', (req, res) => |
| 39 | { |
| 40 | const db = getDb(); |
| 41 | const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all(); |
| 42 | res.json({ |
| 43 | users: users.map(u => ({ |
| 44 | id: u.id, |
| 45 | username: u.username, |
| 46 | isAdmin: u.is_admin === 1, |
| 47 | permissions: JSON.parse(u.permissions || '{}'), |
| 48 | })), |
| 49 | }); |
| 50 | }); |
| 51 | |
| 52 | // --------------------------------------------------------------------------- |
| 53 | // POST /api/admin/users |
| 54 | // Body: { username, password, isAdmin, permissions } |
| 55 | // Creates a new user. |
| 56 | // --------------------------------------------------------------------------- |
| 57 | router.post('/users', (req, res) => |
| 58 | { |
| 59 | const { username, password, isAdmin, permissions } = req.body; |
| 60 | |
| 61 | if (!username || !password || password.length < 8) |
| 62 | { |
| 63 | return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); |
| 64 | } |
| 65 | |
| 66 | const db = getDb(); |
| 67 | const exists = db.prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE').get([username]); |
| 68 | if (exists) return res.status(409).json({ error: 'Username already exists.' }); |
| 69 | |
| 70 | const normalizedPermissions = normalizePermissions(permissions); |
| 71 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 72 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run( |
| 73 | [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)] |
| 74 | ); |
| 75 | |
| 76 | res.status(201).json({ ok: true }); |
| 77 | }); |
| 78 | |
| 79 | // --------------------------------------------------------------------------- |
| 80 | // PATCH /api/admin/users/:id |
| 81 | // Body: { password?, isAdmin?, permissions? } |
| 82 | // Updates an existing user. At least one field must be present. |
| 83 | // --------------------------------------------------------------------------- |
| 84 | router.patch('/users/:id', (req, res) => |
| 85 | { |
| 86 | const db = getDb(); |
| 87 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 88 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 89 | |
| 90 | const { password, isAdmin, permissions } = req.body; |
| 91 | |
| 92 | // Prevent removing the last admin |
| 93 | if (isAdmin === false || isAdmin === 0) |
| 94 | { |
| 95 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 96 | if (adminCount <= 1 && user.is_admin === 1) |
| 97 | { |
| 98 | return res.status(400).json({ error: 'Cannot remove the last admin account.' }); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | if (password !== undefined) |
| 103 | { |
| 104 | if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' }); |
| 105 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 106 | db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]); |
| 107 | } |
| 108 | |
| 109 | if (isAdmin !== undefined) |
| 110 | { |
| 111 | db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]); |
| 112 | } |
| 113 | |
| 114 | if (permissions !== undefined) |
| 115 | { |
| 116 | const normalizedPermissions = normalizePermissions(permissions); |
| 117 | db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]); |
| 118 | } |
| 119 | |
| 120 | res.json({ ok: true }); |
| 121 | }); |
| 122 | |
| 123 | // --------------------------------------------------------------------------- |
| 124 | // DELETE /api/admin/users/:id |
| 125 | // Deletes a user. Cannot delete yourself or the last admin. |
| 126 | // --------------------------------------------------------------------------- |
| 127 | router.delete('/users/:id', (req, res) => |
| 128 | { |
| 129 | const db = getDb(); |
| 130 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 131 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 132 | |
| 133 | if (String(user.id) === String(req.user.id)) |
| 134 | { |
| 135 | return res.status(400).json({ error: 'Cannot delete your own account.' }); |
| 136 | } |
| 137 | |
| 138 | if (user.is_admin === 1) |
| 139 | { |
| 140 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 141 | if (adminCount <= 1) |
| 142 | { |
| 143 | return res.status(400).json({ error: 'Cannot delete the last admin account.' }); |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | db.prepare('DELETE FROM users WHERE id = ?').run([user.id]); |
| 148 | res.json({ ok: true }); |
| 149 | }); |
| 150 | |
| 151 | // --------------------------------------------------------------------------- |
| 152 | // GET /api/admin/config |
| 153 | // Returns the current server config (paths, port). |
| 154 | // --------------------------------------------------------------------------- |
| 155 | router.get('/config', (req, res) => |
| 156 | { |
| 157 | const config = loadConfig(); |
| 158 | const effective = getEffectivePaths(config.paths || []); |
| 159 | res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective }); |
| 160 | }); |
| 161 | |
| 162 | // --------------------------------------------------------------------------- |
| 163 | // PUT /api/admin/config |
| 164 | // Body: { paths: [...], port: number } |
| 165 | // Saves the config. |
| 166 | // --------------------------------------------------------------------------- |
| 167 | router.put('/config', (req, res) => |
| 168 | { |
| 169 | const { paths, port } = req.body; |
| 170 | if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' }); |
| 171 | |
| 172 | const config = loadConfig(); |
| 173 | config.paths = paths.map(p => p.trim()).filter(Boolean); |
| 174 | if (port !== undefined) |
| 175 | { |
| 176 | const p = parseInt(port, 10); |
| 177 | if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' }); |
| 178 | config.port = p; |
| 179 | } |
| 180 | |
| 181 | try |
| 182 | { |
| 183 | saveConfig(config); |
| 184 | } catch (err) |
| 185 | { |
| 186 | return res.status(500).json({ error: `Failed to save config: ${err.message}` }); |
| 187 | } |
| 188 | res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) }); |
| 189 | }); |
| 190 | |
| 191 | // --------------------------------------------------------------------------- |
| 192 | // POST /api/admin/shutdown |
| 193 | // Responds immediately then gracefully closes the server and DB. |
| 194 | // --------------------------------------------------------------------------- |
| 195 | router.post('/shutdown', (req, res) => |
| 196 | { |
| 197 | res.json({ ok: true }); |
| 198 | // Defer so the response is flushed before we start closing. |
| 199 | setImmediate(() => |
| 200 | { |
| 201 | const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown'); |
| 202 | if (typeof fn === 'function') fn(); |
| 203 | }); |
| 204 | }); |
| 205 | |
| 206 | module.exports = router; |