| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const bcrypt = require('bcrypt'); |
| 5 | const fs = require('fs'); |
| 6 | const path = require('path'); |
| 7 | const { execFile } = require('child_process'); |
| 8 | const { promisify } = require('util'); |
| 9 | const router = express.Router(); |
| 10 | |
| 11 | const execFileAsync = promisify(execFile); |
| 12 | const PROJECT_ROOT = path.resolve(__dirname, '../../'); |
| 13 | |
| 14 | /** |
| 15 | * Ensures that a personal subfolder exists for each registered user under userPath. |
| 16 | * Non-fatal: logs errors but does not throw. |
| 17 | */ |
| 18 | function ensureUserFolders (userPath) |
| 19 | { |
| 20 | if (!userPath) return; |
| 21 | try |
| 22 | { |
| 23 | fs.mkdirSync(userPath, { recursive: true }); |
| 24 | } catch (err) |
| 25 | { |
| 26 | console.error('Failed to create user folder root:', err.message); |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | const db = require('../db').getDb(); |
| 31 | const users = db.prepare('SELECT username FROM users').all(); |
| 32 | for (const { username } of users) |
| 33 | { |
| 34 | const folder = path.join(userPath, username); |
| 35 | try |
| 36 | { |
| 37 | fs.mkdirSync(folder, { recursive: true }); |
| 38 | } catch (err) |
| 39 | { |
| 40 | console.error(`Failed to create user folder for ${username}:`, err.message); |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | const { getDb } = require('../db'); |
| 46 | const { requireAuth, requireAdmin } = require('../auth'); |
| 47 | const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); |
| 48 | |
| 49 | const BCRYPT_ROUNDS = 12; |
| 50 | |
| 51 | function normalizePermissions (permissions) |
| 52 | { |
| 53 | if (!permissions || typeof permissions !== 'object') return {}; |
| 54 | |
| 55 | const normalized = {}; |
| 56 | for (const [key, value] of Object.entries(permissions)) |
| 57 | { |
| 58 | if (!value || typeof value !== 'object') continue; |
| 59 | const write = !!value.write; |
| 60 | const read = !!value.read || write; |
| 61 | if (!read && !write) continue; |
| 62 | normalized[key] = { read, write }; |
| 63 | } |
| 64 | |
| 65 | return normalized; |
| 66 | } |
| 67 | |
| 68 | // All admin routes require authentication + admin privilege |
| 69 | router.use(requireAuth, requireAdmin); |
| 70 | |
| 71 | // --------------------------------------------------------------------------- |
| 72 | // GET /api/admin/users |
| 73 | // Returns all users. |
| 74 | // --------------------------------------------------------------------------- |
| 75 | router.get('/users', (req, res) => |
| 76 | { |
| 77 | const db = getDb(); |
| 78 | const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all(); |
| 79 | res.json({ |
| 80 | users: users.map(u => ({ |
| 81 | id: u.id, |
| 82 | username: u.username, |
| 83 | isAdmin: u.is_admin === 1, |
| 84 | permissions: JSON.parse(u.permissions || '{}'), |
| 85 | })), |
| 86 | }); |
| 87 | }); |
| 88 | |
| 89 | // --------------------------------------------------------------------------- |
| 90 | // POST /api/admin/users |
| 91 | // Body: { username, password, isAdmin, permissions } |
| 92 | // Creates a new user. |
| 93 | // --------------------------------------------------------------------------- |
| 94 | router.post('/users', (req, res) => |
| 95 | { |
| 96 | const { username, password, isAdmin, permissions } = req.body; |
| 97 | |
| 98 | if (!username || !password || password.length < 8) |
| 99 | { |
| 100 | return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); |
| 101 | } |
| 102 | |
| 103 | const db = getDb(); |
| 104 | const exists = db.prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE').get([username]); |
| 105 | if (exists) return res.status(409).json({ error: 'Username already exists.' }); |
| 106 | |
| 107 | const normalizedPermissions = normalizePermissions(permissions); |
| 108 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 109 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run( |
| 110 | [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)] |
| 111 | ); |
| 112 | |
| 113 | // Create personal folder for the new user if a userPath is configured. |
| 114 | const config = loadConfig(); |
| 115 | if (config.userPath) |
| 116 | { |
| 117 | const folder = path.join(config.userPath, username); |
| 118 | try { fs.mkdirSync(folder, { recursive: true }); } catch { /* non-fatal */ } |
| 119 | } |
| 120 | |
| 121 | res.status(201).json({ ok: true }); |
| 122 | }); |
| 123 | |
| 124 | // --------------------------------------------------------------------------- |
| 125 | // PATCH /api/admin/users/:id |
| 126 | // Body: { password?, isAdmin?, permissions? } |
| 127 | // Updates an existing user. At least one field must be present. |
| 128 | // --------------------------------------------------------------------------- |
| 129 | router.patch('/users/:id', (req, res) => |
| 130 | { |
| 131 | const db = getDb(); |
| 132 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 133 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 134 | |
| 135 | const { password, isAdmin, permissions } = req.body; |
| 136 | |
| 137 | // Admins may not remove admin privileges from their own account. |
| 138 | if ((isAdmin === false || isAdmin === 0) && String(user.id) === String(req.user.id)) |
| 139 | { |
| 140 | return res.status(400).json({ error: 'Cannot remove your own admin privileges.' }); |
| 141 | } |
| 142 | |
| 143 | // Prevent removing the last admin |
| 144 | if (isAdmin === false || isAdmin === 0) |
| 145 | { |
| 146 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 147 | if (adminCount <= 1 && user.is_admin === 1) |
| 148 | { |
| 149 | return res.status(400).json({ error: 'Cannot remove the last admin account.' }); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | if (password !== undefined) |
| 154 | { |
| 155 | if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' }); |
| 156 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 157 | db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]); |
| 158 | } |
| 159 | |
| 160 | if (isAdmin !== undefined) |
| 161 | { |
| 162 | db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]); |
| 163 | } |
| 164 | |
| 165 | if (permissions !== undefined) |
| 166 | { |
| 167 | const normalizedPermissions = normalizePermissions(permissions); |
| 168 | db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]); |
| 169 | } |
| 170 | |
| 171 | res.json({ ok: true }); |
| 172 | }); |
| 173 | |
| 174 | // --------------------------------------------------------------------------- |
| 175 | // DELETE /api/admin/users/:id |
| 176 | // Deletes a user. Cannot delete yourself or the last admin. |
| 177 | // --------------------------------------------------------------------------- |
| 178 | router.delete('/users/:id', (req, res) => |
| 179 | { |
| 180 | const db = getDb(); |
| 181 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 182 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 183 | |
| 184 | if (String(user.id) === String(req.user.id)) |
| 185 | { |
| 186 | return res.status(400).json({ error: 'Cannot delete your own account.' }); |
| 187 | } |
| 188 | |
| 189 | if (user.is_admin === 1) |
| 190 | { |
| 191 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 192 | if (adminCount <= 1) |
| 193 | { |
| 194 | return res.status(400).json({ error: 'Cannot delete the last admin account.' }); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | db.prepare('DELETE FROM users WHERE id = ?').run([user.id]); |
| 199 | res.json({ ok: true }); |
| 200 | }); |
| 201 | |
| 202 | // --------------------------------------------------------------------------- |
| 203 | // GET /api/admin/config |
| 204 | // Returns the current server config (paths, port, userPath, userFolderSizeLimit). |
| 205 | // --------------------------------------------------------------------------- |
| 206 | router.get('/config', (req, res) => |
| 207 | { |
| 208 | const config = loadConfig(); |
| 209 | const effective = getEffectivePaths(config.paths || []); |
| 210 | res.json({ |
| 211 | port: config.port || 3000, |
| 212 | paths: config.paths || [], |
| 213 | effectivePaths: effective, |
| 214 | userPath: config.userPath || null, |
| 215 | userFolderSizeLimit: config.userFolderSizeLimit || null, |
| 216 | }); |
| 217 | }); |
| 218 | |
| 219 | // --------------------------------------------------------------------------- |
| 220 | // PUT /api/admin/config |
| 221 | // Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null } |
| 222 | // Saves the config. |
| 223 | // --------------------------------------------------------------------------- |
| 224 | router.put('/config', (req, res) => |
| 225 | { |
| 226 | const { paths, port, userPath, userFolderSizeLimit } = req.body; |
| 227 | if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' }); |
| 228 | |
| 229 | const config = loadConfig(); |
| 230 | config.paths = paths.map(p => p.trim()).filter(Boolean); |
| 231 | |
| 232 | if (port !== undefined) |
| 233 | { |
| 234 | const p = parseInt(port, 10); |
| 235 | if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' }); |
| 236 | config.port = p; |
| 237 | } |
| 238 | |
| 239 | // userPath — a single directory for per-user storage. |
| 240 | // Only update when explicitly provided so path-only saves do not clear it. |
| 241 | if (userPath !== undefined) |
| 242 | { |
| 243 | const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : ''; |
| 244 | config.userPath = cleanUserPath || null; |
| 245 | } |
| 246 | |
| 247 | // userFolderSizeLimit — stored as bytes (number) or null = unlimited. |
| 248 | // Only update when explicitly provided. |
| 249 | if (userFolderSizeLimit !== undefined) |
| 250 | { |
| 251 | if (userFolderSizeLimit === null) |
| 252 | { |
| 253 | config.userFolderSizeLimit = null; |
| 254 | } else |
| 255 | { |
| 256 | const lim = Number(userFolderSizeLimit); |
| 257 | config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null; |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | try |
| 262 | { |
| 263 | saveConfig(config); |
| 264 | } catch (err) |
| 265 | { |
| 266 | return res.status(500).json({ error: `Failed to save config: ${err.message}` }); |
| 267 | } |
| 268 | |
| 269 | // Ensure personal subfolders exist for all current users. |
| 270 | if (config.userPath) ensureUserFolders(config.userPath); |
| 271 | |
| 272 | res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) }); |
| 273 | }); |
| 274 | |
| 275 | // --------------------------------------------------------------------------- |
| 276 | // GET /api/admin/update-status |
| 277 | // Returns whether the process is running under systemd and whether the git |
| 278 | // remote is ahead of the local checkout. |
| 279 | // --------------------------------------------------------------------------- |
| 280 | router.get('/update-status', async (req, res) => |
| 281 | { |
| 282 | const underSystemd = !!process.env.INVOCATION_ID; |
| 283 | if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] }); |
| 284 | |
| 285 | let commitsAhead = []; |
| 286 | try |
| 287 | { |
| 288 | await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT }); |
| 289 | const { stdout } = await execFileAsync( |
| 290 | 'git', ['log', 'HEAD..origin/HEAD', '--oneline', '--no-decorate'], |
| 291 | { cwd: PROJECT_ROOT }, |
| 292 | ); |
| 293 | commitsAhead = stdout.trim().split('\n').filter(Boolean); |
| 294 | } |
| 295 | catch |
| 296 | { |
| 297 | // git may not be available or repo may not have a remote — return empty list. |
| 298 | } |
| 299 | |
| 300 | res.json({ underSystemd: true, commitsAhead }); |
| 301 | }); |
| 302 | |
| 303 | // --------------------------------------------------------------------------- |
| 304 | // POST /api/admin/shutdown |
| 305 | // Responds immediately then gracefully closes the server and DB. |
| 306 | // --------------------------------------------------------------------------- |
| 307 | router.post('/shutdown', (req, res) => |
| 308 | { |
| 309 | res.json({ ok: true }); |
| 310 | // Defer so the response is flushed before we start closing. |
| 311 | setImmediate(() => |
| 312 | { |
| 313 | const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown'); |
| 314 | if (typeof fn === 'function') fn(); |
| 315 | }); |
| 316 | }); |
| 317 | |
| 318 | module.exports = router; |