BlueGit

timfa filemanager

Files

filemanager / server / routes / admin.js

admin.js

fixes and updates
timfa Tim Falken · pushed by timfa · 6 months ago
0ae63c84 History
admin.js 6.2 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const bcrypt = require('bcrypt');
5const path = require('path');
6const router = express.Router();
7
8const { getDb } = require('../db');
9const { requireAuth, requireAdmin } = require('../auth');
10const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
11
12const BCRYPT_ROUNDS = 12;
13
14// All admin routes require authentication + admin privilege
15router.use(requireAuth, requireAdmin);
16
17// ---------------------------------------------------------------------------
18// GET /api/admin/users
19// Returns all users.
20// ---------------------------------------------------------------------------
21router.get('/users', (req, res) =>
22{
23 const db = getDb();
24 const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all();
25 res.json({
26 users: users.map(u => ({
27 id: u.id,
28 username: u.username,
29 isAdmin: u.is_admin === 1,
30 permissions: JSON.parse(u.permissions || '{}'),
31 })),
32 });
33});
34
35// ---------------------------------------------------------------------------
36// POST /api/admin/users
37// Body: { username, password, isAdmin, permissions }
38// Creates a new user.
39// ---------------------------------------------------------------------------
40router.post('/users', (req, res) =>
41{
42 const { username, password, isAdmin, permissions } = req.body;
43
44 if (!username || !password || password.length < 8)
45 {
46 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
47 }
48
49 const db = getDb();
50 const exists = db.prepare('SELECT id FROM users WHERE username = ?').get([username]);
51 if (exists) return res.status(409).json({ error: 'Username already exists.' });
52
53 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
54 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run(
55 [username, hash, isAdmin ? 1 : 0, JSON.stringify(permissions || {})]
56 );
57
58 res.status(201).json({ ok: true });
59});
60
61// ---------------------------------------------------------------------------
62// PATCH /api/admin/users/:id
63// Body: { password?, isAdmin?, permissions? }
64// Updates an existing user. At least one field must be present.
65// ---------------------------------------------------------------------------
66router.patch('/users/:id', (req, res) =>
67{
68 const db = getDb();
69 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
70 if (!user) return res.status(404).json({ error: 'User not found.' });
71
72 const { password, isAdmin, permissions } = req.body;
73
74 // Prevent removing the last admin
75 if (isAdmin === false || isAdmin === 0)
76 {
77 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
78 if (adminCount <= 1 && user.is_admin === 1)
79 {
80 return res.status(400).json({ error: 'Cannot remove the last admin account.' });
81 }
82 }
83
84 if (password !== undefined)
85 {
86 if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' });
87 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
88 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
89 }
90
91 if (isAdmin !== undefined)
92 {
93 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
94 }
95
96 if (permissions !== undefined)
97 {
98 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(permissions), user.id]);
99 }
100
101 res.json({ ok: true });
102});
103
104// ---------------------------------------------------------------------------
105// DELETE /api/admin/users/:id
106// Deletes a user. Cannot delete yourself or the last admin.
107// ---------------------------------------------------------------------------
108router.delete('/users/:id', (req, res) =>
109{
110 const db = getDb();
111 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
112 if (!user) return res.status(404).json({ error: 'User not found.' });
113
114 if (String(user.id) === String(req.user.id))
115 {
116 return res.status(400).json({ error: 'Cannot delete your own account.' });
117 }
118
119 if (user.is_admin === 1)
120 {
121 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
122 if (adminCount <= 1)
123 {
124 return res.status(400).json({ error: 'Cannot delete the last admin account.' });
125 }
126 }
127
128 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
129 res.json({ ok: true });
130});
131
132// ---------------------------------------------------------------------------
133// GET /api/admin/config
134// Returns the current server config (paths, port).
135// ---------------------------------------------------------------------------
136router.get('/config', (req, res) =>
137{
138 const config = loadConfig();
139 const effective = getEffectivePaths(config.paths || []);
140 res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective });
141});
142
143// ---------------------------------------------------------------------------
144// PUT /api/admin/config
145// Body: { paths: [...], port: number }
146// Saves the config.
147// ---------------------------------------------------------------------------
148router.put('/config', (req, res) =>
149{
150 const { paths, port } = req.body;
151 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
152
153 const config = loadConfig();
154 config.paths = paths.map(p => p.trim()).filter(Boolean);
155 if (port !== undefined)
156 {
157 const p = parseInt(port, 10);
158 if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' });
159 config.port = p;
160 }
161
162 try
163 {
164 saveConfig(config);
165 } catch (err)
166 {
167 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
168 }
169 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
170});
171
172// ---------------------------------------------------------------------------
173// POST /api/admin/shutdown
174// Responds immediately then gracefully closes the server and DB.
175// ---------------------------------------------------------------------------
176router.post('/shutdown', (req, res) =>
177{
178 res.json({ ok: true });
179 // Defer so the response is flushed before we start closing.
180 setImmediate(() =>
181 {
182 const fn = req.app.get('shutdown');
183 if (typeof fn === 'function') fn();
184 });
185});
186
187module.exports = router;