Add user management UI and stable UUIDs for users

Backend
- New routes/users.js (admin-only via requireAdmin) with list, create,
  update (incl. password reset) and delete endpoints.
- All user-facing API responses identify users by uuid, not the
  numeric primary key — usernames can now be renamed without breaking
  external references.
- Protection rules: cannot delete or demote the last admin; cannot
  delete or demote your own account.

Schema / data
- users table gained a uuid TEXT column (unique). Existing rows are
  backfilled with crypto.randomUUID() on startup. Setup endpoint and
  the create-user CLI both generate a UUID for new users.

Frontend
- New "Benutzer" tab in nav-tabs, marked admin-only and shown only
  after /api/auth/me reports isAdmin.
- Modal with create / edit forms (password optional on edit = leave
  unchanged). XSS-safe rendering of the user list using the existing
  escapeHtml helper and data-* attributes for action buttons.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
kerimatilganandClaude Opus 4.7 committed 2026-05-15 16:03:04 +02:00
1 parent b43ff3c5ca
commit e308c1a7b7
7 files changed
+333 -7

No files matched your search

+120
View File
@@ -48,6 +48,10 @@ document.addEventListener('DOMContentLoaded', async function() {
function renderUserBadge() {
if (!currentUser) return;
// Show admin-only navigation elements (e.g. the Benutzer tab) once we know the role.
document.querySelectorAll('.admin-only').forEach(el => {
el.style.display = currentUser.isAdmin ? '' : 'none';
});
let badge = document.getElementById('userBadge');
if (!badge) {
badge = document.createElement('div');
@@ -141,6 +145,8 @@ function showTab(tabName) {
if (!document.getElementById('anbieterList') || !document.getElementById('anbieterList').innerHTML.trim()) {
loadAdminData();
}
} else if (tabName === 'users') {
loadUsers();
}
}
@@ -3751,3 +3757,117 @@ document.addEventListener('DOMContentLoaded', function() {
});
}
});
// ============================================================================
// Benutzer-Verwaltung (admin only). Backend: /api/users/*
// ============================================================================
async function loadUsers() {
const tbody = document.getElementById('usersTableBody');
if (!tbody) return;
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#666;">Lade...</td></tr>';
try {
const users = await apiRequest('/api/users');
tbody.innerHTML = '';
if (!users.length) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#666;">Keine Benutzer</td></tr>';
return;
}
users.forEach(u => {
const tr = document.createElement('tr');
const isSelf = currentUser && currentUser.username === u.username;
tr.innerHTML = `
<td>${escapeHtml(u.username)}${isSelf ? ' <small style="color:#3498db;">(Sie)</small>' : ''}</td>
<td>${escapeHtml(u.displayName || '')}</td>
<td>${u.isAdmin ? '<span style="color:#27ae60;">✓</span>' : ''}</td>
<td>${escapeHtml(u.createdAt || '')}</td>
<td>
<button data-user-action="edit" data-uuid="${escapeHtml(u.uuid)}" class="btn-success" style="margin-right:5px;">Bearbeiten</button>
<button data-user-action="delete" data-uuid="${escapeHtml(u.uuid)}" data-username="${escapeHtml(u.username)}" class="btn-danger" ${isSelf ? 'disabled title="Eigener Account kann nicht gelöscht werden"' : ''}>Löschen</button>
</td>
`;
tr.querySelectorAll('button[data-user-action]').forEach(btn => {
btn.addEventListener('click', () => {
const action = btn.dataset.userAction;
const uuid = btn.dataset.uuid;
if (action === 'edit') openUserModal(u);
else if (action === 'delete') deleteUser(uuid, btn.dataset.username);
});
});
tbody.appendChild(tr);
});
} catch (err) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#c0392b;">Fehler beim Laden</td></tr>';
}
}
function openUserModal(user) {
const isEdit = !!user;
document.getElementById('userModalTitle').textContent = isEdit ? 'Benutzer bearbeiten' : 'Neuer Benutzer';
document.getElementById('userModalUuid').value = isEdit ? user.uuid : '';
document.getElementById('userModalUsername').value = isEdit ? user.username : '';
document.getElementById('userModalDisplay').value = isEdit ? (user.displayName || '') : '';
document.getElementById('userModalPassword').value = '';
document.getElementById('userModalIsAdmin').checked = isEdit ? !!user.isAdmin : false;
document.getElementById('userModalPasswordHint').style.display = isEdit ? 'none' : '';
document.getElementById('userModalPasswordEditHint').style.display = isEdit ? '' : 'none';
document.getElementById('userModal').style.display = 'block';
}
function closeUserModal() {
document.getElementById('userModal').style.display = 'none';
}
async function saveUserFromModal() {
const uuid = document.getElementById('userModalUuid').value;
const username = document.getElementById('userModalUsername').value.trim();
const displayName = document.getElementById('userModalDisplay').value.trim();
const password = document.getElementById('userModalPassword').value;
const isAdmin = document.getElementById('userModalIsAdmin').checked;
if (!username) {
showMessage('Username ist erforderlich', 'error');
return;
}
try {
if (uuid) {
// Update existing user
const body = { username, displayName, isAdmin };
if (password) body.newPassword = password;
await apiRequest(`/api/users/${encodeURIComponent(uuid)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
showMessage(`Benutzer "${username}" aktualisiert`);
} else {
// Create new user
if (!password || password.length < 8) {
showMessage('Passwort muss mindestens 8 Zeichen lang sein', 'error');
return;
}
await apiRequest('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, displayName, isAdmin }),
});
showMessage(`Benutzer "${username}" angelegt`);
}
closeUserModal();
loadUsers();
} catch (err) {
// apiRequest already shows the error message
}
}
async function deleteUser(uuid, username) {
if (!confirm(`Benutzer "${username}" wirklich löschen?`)) return;
try {
await apiRequest(`/api/users/${encodeURIComponent(uuid)}`, { method: 'DELETE' });
showMessage(`Benutzer "${username}" gelöscht`);
loadUsers();
} catch (err) {
// apiRequest already shows the error message
}
}