BlueGit

timfa filemanager

Files

filemanager / server / routes / admin.js

admin.js

Add scheduled restart backend
timfa Tim Falken · pushed by timfa · 5 months ago
9e526bef History
admin.js 15.1 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const bcrypt = require('bcrypt');
5const fs = require('fs');
6const path = require('path');
7const { execFile } = require('child_process');
8const { promisify } = require('util');
9const router = express.Router();
10
11const execFileAsync = promisify(execFile);
12const 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 */
18function 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
45const { getDb } = require('../db');
46const { requireAuth, requireAdmin } = require('../auth');
47const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
48const debugRouter = require('./debug');
49
50const BCRYPT_ROUNDS = 12;
51const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
52const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
53
54function normaliseScheduledRestartConfig (value, fallback = null)
55{
56 const defaults = fallback && typeof fallback === 'object'
57 ? fallback
58 : { enabled: false, cadence: 'daily', time: '04:00' };
59 const raw = value && typeof value === 'object' ? value : {};
60
61 const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase();
62 const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence;
63
64 const timeRaw = String(raw.time || defaults.time || '').trim();
65 const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time;
66
67 return {
68 enabled: !!raw.enabled,
69 cadence,
70 time,
71 };
72}
73
74function normalizePermissions (permissions)
75{
76 if (!permissions || typeof permissions !== 'object') return {};
77
78 const normalized = {};
79 for (const [key, value] of Object.entries(permissions))
80 {
81 if (!value || typeof value !== 'object') continue;
82 const write = !!value.write;
83 const read = !!value.read || write;
84 if (!read && !write) continue;
85 normalized[key] = { read, write };
86 }
87
88 return normalized;
89}
90
91function userFolderRootFromConfig (config)
92{
93 const raw = config && typeof config.userPath === 'string' ? config.userPath.trim() : '';
94 return raw ? path.resolve(raw) : null;
95}
96
97function removeIfEmptyDir (dirPath)
98{
99 try
100 {
101 const entries = fs.readdirSync(dirPath);
102 if (entries.length !== 0) return false;
103 fs.rmdirSync(dirPath);
104 return true;
105 } catch
106 {
107 return false;
108 }
109}
110
111function listOrphanUserFolders (userFolderRoot, options = {})
112{
113 const deleteEmpty = !!options.deleteEmpty;
114 if (!userFolderRoot) return [];
115
116 let entries = [];
117 try
118 {
119 entries = fs.readdirSync(userFolderRoot, { withFileTypes: true });
120 } catch
121 {
122 return [];
123 }
124
125 const db = getDb();
126 const users = db.prepare('SELECT username FROM users').all();
127 const usernames = new Set(users.map((u) => String(u.username || '').toLowerCase()));
128
129 const out = [];
130 for (const entry of entries)
131 {
132 if (!entry.isDirectory()) continue;
133
134 const folderName = String(entry.name || '');
135 if (!folderName) continue;
136 if (usernames.has(folderName.toLowerCase())) continue;
137
138 const folderPath = path.join(userFolderRoot, folderName);
139 let itemCount = 0;
140 try
141 {
142 itemCount = fs.readdirSync(folderPath).length;
143 } catch
144 {
145 continue;
146 }
147
148 if (itemCount === 0 && deleteEmpty)
149 {
150 const removed = removeIfEmptyDir(folderPath);
151 if (removed) continue;
152 }
153
154 out.push({
155 folderName,
156 path: folderPath,
157 itemCount,
158 });
159 }
160
161 out.sort((a, b) => a.folderName.localeCompare(b.folderName));
162 return out;
163}
164
165// All admin routes require authentication + admin privilege
166router.use(requireAuth, requireAdmin);
167router.use(debugRouter);
168
169// ---------------------------------------------------------------------------
170// GET /api/admin/users
171// Returns all users.
172// ---------------------------------------------------------------------------
173router.get('/users', (req, res) =>
174{
175 const db = getDb();
176 const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all();
177 res.json({
178 users: users.map(u => ({
179 id: u.id,
180 username: u.username,
181 isAdmin: u.is_admin === 1,
182 permissions: JSON.parse(u.permissions || '{}'),
183 })),
184 });
185});
186
187// ---------------------------------------------------------------------------
188// GET /api/admin/orphan-userfolders
189// Returns non-empty user folders that are not linked to an existing user.
190// Empty orphan folders are auto-deleted.
191// ---------------------------------------------------------------------------
192router.get('/orphan-userfolders', (req, res) =>
193{
194 const config = loadConfig();
195 const userFolderRoot = userFolderRootFromConfig(config);
196 const folders = listOrphanUserFolders(userFolderRoot, { deleteEmpty: true });
197 res.json({ folders });
198});
199
200// ---------------------------------------------------------------------------
201// POST /api/admin/users
202// Body: { username, password, isAdmin, permissions }
203// Creates a new user.
204// ---------------------------------------------------------------------------
205router.post('/users', (req, res) =>
206{
207 const { username, password, isAdmin, permissions } = req.body;
208
209 if (!username || !password || password.length < 8)
210 {
211 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
212 }
213
214 const db = getDb();
215 const exists = db.prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE').get([username]);
216 if (exists) return res.status(409).json({ error: 'Username already exists.' });
217
218 const normalizedPermissions = normalizePermissions(permissions);
219 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
220 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run(
221 [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)]
222 );
223
224 // Create personal folder for the new user if a userPath is configured.
225 const config = loadConfig();
226 if (config.userPath)
227 {
228 const folder = path.join(config.userPath, username);
229 try { fs.mkdirSync(folder, { recursive: true }); } catch { /* non-fatal */ }
230 }
231
232 res.status(201).json({ ok: true });
233});
234
235// ---------------------------------------------------------------------------
236// PATCH /api/admin/users/:id
237// Body: { password?, isAdmin?, permissions? }
238// Updates an existing user. At least one field must be present.
239// ---------------------------------------------------------------------------
240router.patch('/users/:id', (req, res) =>
241{
242 const db = getDb();
243 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
244 if (!user) return res.status(404).json({ error: 'User not found.' });
245
246 const { password, isAdmin, permissions } = req.body;
247
248 // Admins may not remove admin privileges from their own account.
249 if ((isAdmin === false || isAdmin === 0) && String(user.id) === String(req.user.id))
250 {
251 return res.status(400).json({ error: 'Cannot remove your own admin privileges.' });
252 }
253
254 // Prevent removing the last admin
255 if (isAdmin === false || isAdmin === 0)
256 {
257 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
258 if (adminCount <= 1 && user.is_admin === 1)
259 {
260 return res.status(400).json({ error: 'Cannot remove the last admin account.' });
261 }
262 }
263
264 if (password !== undefined)
265 {
266 if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' });
267 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
268 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
269 }
270
271 if (isAdmin !== undefined)
272 {
273 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
274 }
275
276 if (permissions !== undefined)
277 {
278 const normalizedPermissions = normalizePermissions(permissions);
279 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]);
280 }
281
282 res.json({ ok: true });
283});
284
285// ---------------------------------------------------------------------------
286// DELETE /api/admin/users/:id
287// Deletes a user. Cannot delete yourself or the last admin.
288// ---------------------------------------------------------------------------
289router.delete('/users/:id', (req, res) =>
290{
291 const db = getDb();
292 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
293 if (!user) return res.status(404).json({ error: 'User not found.' });
294
295 if (String(user.id) === String(req.user.id))
296 {
297 return res.status(400).json({ error: 'Cannot delete your own account.' });
298 }
299
300 if (user.is_admin === 1)
301 {
302 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
303 if (adminCount <= 1)
304 {
305 return res.status(400).json({ error: 'Cannot delete the last admin account.' });
306 }
307 }
308
309 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
310
311 // If the deleted user's personal folder is now empty, remove it automatically.
312 const config = loadConfig();
313 const userFolderRoot = userFolderRootFromConfig(config);
314 if (userFolderRoot)
315 {
316 const folderPath = path.join(userFolderRoot, String(user.username || ''));
317 removeIfEmptyDir(folderPath);
318 }
319
320 res.json({ ok: true });
321});
322
323// ---------------------------------------------------------------------------
324// GET /api/admin/config
325// Returns the current server config (paths, port, userPath, userFolderSizeLimit).
326// ---------------------------------------------------------------------------
327router.get('/config', (req, res) =>
328{
329 const config = loadConfig();
330 const effective = getEffectivePaths(config.paths || []);
331 const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart);
332 res.json({
333 port: config.port || 3000,
334 paths: config.paths || [],
335 effectivePaths: effective,
336 userPath: config.userPath || null,
337 userFolderSizeLimit: config.userFolderSizeLimit || null,
338 scheduledRestart,
339 });
340});
341
342// ---------------------------------------------------------------------------
343// PUT /api/admin/config
344// Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null }
345// Saves the config.
346// ---------------------------------------------------------------------------
347router.put('/config', (req, res) =>
348{
349 const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body;
350 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
351
352 const config = loadConfig();
353 config.paths = paths.map(p => p.trim()).filter(Boolean);
354
355 if (port !== undefined)
356 {
357 const p = parseInt(port, 10);
358 if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' });
359 config.port = p;
360 }
361
362 // userPath — a single directory for per-user storage.
363 // Only update when explicitly provided so path-only saves do not clear it.
364 if (userPath !== undefined)
365 {
366 const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : '';
367 config.userPath = cleanUserPath || null;
368 }
369
370 // userFolderSizeLimit — stored as bytes (number) or null = unlimited.
371 // Only update when explicitly provided.
372 if (userFolderSizeLimit !== undefined)
373 {
374 if (userFolderSizeLimit === null)
375 {
376 config.userFolderSizeLimit = null;
377 } else
378 {
379 const lim = Number(userFolderSizeLimit);
380 config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null;
381 }
382 }
383
384 if (scheduledRestart !== undefined)
385 {
386 if (!process.env.INVOCATION_ID)
387 {
388 return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' });
389 }
390
391 if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart))
392 {
393 return res.status(400).json({ error: 'scheduledRestart must be an object.' });
394 }
395
396 const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase();
397 if (!SCHEDULED_RESTART_CADENCES.has(cadence))
398 {
399 return res.status(400).json({ error: 'Invalid scheduled restart cadence.' });
400 }
401
402 const time = String(scheduledRestart.time || '').trim();
403 if (!SCHEDULED_RESTART_TIME_RE.test(time))
404 {
405 return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' });
406 }
407
408 config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart);
409 }
410
411 try
412 {
413 saveConfig(config);
414 } catch (err)
415 {
416 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
417 }
418
419 // Ensure personal subfolders exist for all current users.
420 if (config.userPath) ensureUserFolders(config.userPath);
421
422 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
423});
424
425// ---------------------------------------------------------------------------
426// GET /api/admin/update-status
427// Returns whether the process is running under systemd and whether the git
428// remote is ahead of the local checkout.
429// ---------------------------------------------------------------------------
430router.get('/update-status', async (req, res) =>
431{
432 const underSystemd = !!process.env.INVOCATION_ID;
433 if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] });
434
435 let commitsAhead = [];
436 try
437 {
438 await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT });
439 const { stdout } = await execFileAsync(
440 'git', ['log', 'HEAD..origin/HEAD', '--no-decorate', '--no-merges', '--pretty=format:%H%x1f%s%x1f%b%x1e'],
441 { cwd: PROJECT_ROOT },
442 );
443 const records = String(stdout || '').split('\x1e').map(line => line.trim()).filter(Boolean);
444 commitsAhead = records.map((record) =>
445 {
446 const parts = record.split('\x1f');
447 const hash = String(parts[0] || '').trim();
448 const subject = String(parts[1] || '').trim();
449 const body = String(parts.slice(2).join('\x1f') || '').trim();
450 if (!subject) return null;
451 return { hash, subject, body };
452 }).filter(Boolean);
453 }
454 catch
455 {
456 // git may not be available or repo may not have a remote — return empty list.
457 }
458
459 res.json({ underSystemd: true, commitsAhead });
460});
461
462// ---------------------------------------------------------------------------
463// POST /api/admin/shutdown
464// Responds immediately then gracefully closes the server and DB.
465// ---------------------------------------------------------------------------
466router.post('/shutdown', (req, res) =>
467{
468 res.json({ ok: true });
469 // Defer so the response is flushed before we start closing.
470 setImmediate(() =>
471 {
472 const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown');
473 if (typeof fn === 'function') fn();
474 });
475});
476
477module.exports = router;