BlueGit

timfa filemanager

Files

filemanager / server / routes / admin.js

admin.js

userdirs
timfa Tim Falken · pushed by timfa · 6 months ago
f803c52f History
admin.js 10.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');
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
68// All admin routes require authentication + admin privilege
69router.use(requireAuth, requireAdmin);
70
71// ---------------------------------------------------------------------------
72// GET /api/admin/users
73// Returns all users.
74// ---------------------------------------------------------------------------
75router.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// ---------------------------------------------------------------------------
94router.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// ---------------------------------------------------------------------------
129router.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 // Prevent removing the last admin
138 if (isAdmin === false || isAdmin === 0)
139 {
140 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
141 if (adminCount <= 1 && user.is_admin === 1)
142 {
143 return res.status(400).json({ error: 'Cannot remove the last admin account.' });
144 }
145 }
146
147 if (password !== undefined)
148 {
149 if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' });
150 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
151 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
152 }
153
154 if (isAdmin !== undefined)
155 {
156 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
157 }
158
159 if (permissions !== undefined)
160 {
161 const normalizedPermissions = normalizePermissions(permissions);
162 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]);
163 }
164
165 res.json({ ok: true });
166});
167
168// ---------------------------------------------------------------------------
169// DELETE /api/admin/users/:id
170// Deletes a user. Cannot delete yourself or the last admin.
171// ---------------------------------------------------------------------------
172router.delete('/users/:id', (req, res) =>
173{
174 const db = getDb();
175 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
176 if (!user) return res.status(404).json({ error: 'User not found.' });
177
178 if (String(user.id) === String(req.user.id))
179 {
180 return res.status(400).json({ error: 'Cannot delete your own account.' });
181 }
182
183 if (user.is_admin === 1)
184 {
185 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
186 if (adminCount <= 1)
187 {
188 return res.status(400).json({ error: 'Cannot delete the last admin account.' });
189 }
190 }
191
192 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
193 res.json({ ok: true });
194});
195
196// ---------------------------------------------------------------------------
197// GET /api/admin/config
198// Returns the current server config (paths, port, userPath, userFolderSizeLimit).
199// ---------------------------------------------------------------------------
200router.get('/config', (req, res) =>
201{
202 const config = loadConfig();
203 const effective = getEffectivePaths(config.paths || []);
204 res.json({
205 port: config.port || 3000,
206 paths: config.paths || [],
207 effectivePaths: effective,
208 userPath: config.userPath || null,
209 userFolderSizeLimit: config.userFolderSizeLimit || null,
210 });
211});
212
213// ---------------------------------------------------------------------------
214// PUT /api/admin/config
215// Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null }
216// Saves the config.
217// ---------------------------------------------------------------------------
218router.put('/config', (req, res) =>
219{
220 const { paths, port, userPath, userFolderSizeLimit } = req.body;
221 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
222
223 const config = loadConfig();
224 config.paths = paths.map(p => p.trim()).filter(Boolean);
225
226 if (port !== undefined)
227 {
228 const p = parseInt(port, 10);
229 if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' });
230 config.port = p;
231 }
232
233 // userPath — a single directory for per-user storage.
234 // Only update when explicitly provided so path-only saves do not clear it.
235 if (userPath !== undefined)
236 {
237 const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : '';
238 config.userPath = cleanUserPath || null;
239 }
240
241 // userFolderSizeLimit — stored as bytes (number) or null = unlimited.
242 // Only update when explicitly provided.
243 if (userFolderSizeLimit !== undefined)
244 {
245 if (userFolderSizeLimit === null)
246 {
247 config.userFolderSizeLimit = null;
248 } else
249 {
250 const lim = Number(userFolderSizeLimit);
251 config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null;
252 }
253 }
254
255 try
256 {
257 saveConfig(config);
258 } catch (err)
259 {
260 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
261 }
262
263 // Ensure personal subfolders exist for all current users.
264 if (config.userPath) ensureUserFolders(config.userPath);
265
266 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
267});
268
269// ---------------------------------------------------------------------------
270// GET /api/admin/update-status
271// Returns whether the process is running under systemd and whether the git
272// remote is ahead of the local checkout.
273// ---------------------------------------------------------------------------
274router.get('/update-status', async (req, res) =>
275{
276 const underSystemd = !!process.env.INVOCATION_ID;
277 if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] });
278
279 let commitsAhead = [];
280 try
281 {
282 await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT });
283 const { stdout } = await execFileAsync(
284 'git', ['log', 'HEAD..origin/HEAD', '--oneline', '--no-decorate'],
285 { cwd: PROJECT_ROOT },
286 );
287 commitsAhead = stdout.trim().split('\n').filter(Boolean);
288 }
289 catch
290 {
291 // git may not be available or repo may not have a remote — return empty list.
292 }
293
294 res.json({ underSystemd: true, commitsAhead });
295});
296
297// ---------------------------------------------------------------------------
298// POST /api/admin/shutdown
299// Responds immediately then gracefully closes the server and DB.
300// ---------------------------------------------------------------------------
301router.post('/shutdown', (req, res) =>
302{
303 res.json({ ok: true });
304 // Defer so the response is flushed before we start closing.
305 setImmediate(() =>
306 {
307 const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown');
308 if (typeof fn === 'function') fn();
309 });
310});
311
312module.exports = router;