feat(auth): admin role management with logbook entries

This commit is contained in:
Brückner
2026-06-10 16:05:08 +02:00
parent 08a4df5503
commit 84bad8c0e6
4 changed files with 81 additions and 5 deletions

View File

@ -405,6 +405,29 @@ async function startServer() {
db.prepare('UPDATE users SET name = COALESCE(?, name), email = COALESCE(?, email) WHERE id = ?')
.run(name ?? null, email ?? null, id);
const updated = db.prepare('SELECT id, name, role, email FROM users WHERE id = ?').get(id) as User;
const changes: string[] = [];
if (name && name !== existing.name) changes.push(`name "${existing.name}" → "${name}"`);
if (email && email !== existing.email) changes.push(`email "${existing.email}" → "${email}"`);
if (changes.length > 0) {
addLog('system', `User ${updated.email} updated: ${changes.join(', ')}.`, { userId: req.user!.userId });
}
res.json(updated);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.patch('/api/users/:id/role', requireAuth, requireAdmin, (req, res) => {
try {
const id = req.params.id;
const { role } = req.body as { role: string };
const safeRole = role?.toLowerCase() === 'admin' ? 'admin' : 'User';
const existing = db.prepare('SELECT id, name, email, role FROM users WHERE id = ?').get(id) as User | undefined;
if (!existing) return res.status(404).json({ error: 'User not found.' });
if (existing.role === safeRole) return res.json(existing);
db.prepare('UPDATE users SET role = ? WHERE id = ?').run(safeRole, id);
const updated = db.prepare('SELECT id, name, role, email FROM users WHERE id = ?').get(id) as User;
addLog('system', `User ${updated.email} role changed to ${safeRole}.`, { userId: req.user!.userId });
res.json(updated);
} catch (err: any) {
res.status(500).json({ error: err.message });