BlueGit

timfa filemanager

Files

filemanager / server / routes / admin.js

admin.js

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