BlueGit

timfa filemanager

Files

filemanager / server / routes / admin.js

admin.js

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