BlueGit

timfa filemanager

Files

filemanager / server / routes / admin.js

admin.js

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