async function loadUsers() {
const res = await apiFetch('/api/users');
if (!res) return;
const users = await res.json();
const tb = document.getElementById('usersTableBody');
if (!users.length) {
tb.innerHTML = `
| No users found. |
`;
return;
}
tb.innerHTML = users.map(u => {
// esc() HTML-encodes JSON so " inside onclick="..." doesn't break the attribute
const nameJson = esc(JSON.stringify(u.name));
return `
| ${esc(u.name)} |
${u.uid} |
${u.smb ? 'Active' : 'No'}
|
|
`;
}).join('');
}
async function createUser() {
const name = document.getElementById('newUsername').value.trim();
const password = document.getElementById('newPassword').value;
if (!name || !password) return showToast('Username and password are required.', 'danger');
const res = await apiFetch('/api/users', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name, password}),
});
if (!res) return;
const data = await res.json();
if (!res.ok) return showToast('Error: ' + (data.error || res.status), 'danger');
showToast(`User "${name}" created.`);
document.getElementById('newUsername').value = '';
document.getElementById('newPassword').value = '';
loadUsers();
}
function confirmDeleteUser(name) {
document.getElementById('deleteModalMsg').textContent =
`Are you sure you want to delete user "${name}"? This removes both the system account and SMB access.`;
const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
const btn = document.getElementById('deleteModalConfirm');
const handler = async () => {
btn.removeEventListener('click', handler);
modal.hide();
const res = await apiFetch(`/api/users/${encodeURIComponent(name)}`, { method: 'DELETE' });
if (!res) return;
const data = await res.json();
if (!res.ok) return showToast('Error: ' + (data.error || res.status), 'danger');
showToast(`User "${name}" deleted.`);
loadUsers();
};
btn.addEventListener('click', handler);
modal.show();
}
function openPwModal(name) {
document.getElementById('pwUsername').value = name;
document.getElementById('pwNew').value = '';
document.getElementById('pwConfirm').value = '';
new bootstrap.Modal(document.getElementById('pwModal')).show();
}
async function submitPassword() {
const name = document.getElementById('pwUsername').value;
const pw = document.getElementById('pwNew').value;
const pwConfirm = document.getElementById('pwConfirm').value;
if (pw.length < 8) return showToast('Password must be at least 8 characters.', 'danger');
if (pw !== pwConfirm) return showToast('Passwords do not match.', 'danger');
const res = await apiFetch(`/api/users/${encodeURIComponent(name)}/password`, {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({password: pw}),
});
if (!res) return;
const data = await res.json();
bootstrap.Modal.getInstance(document.getElementById('pwModal')).hide();
if (!res.ok) return showToast('Error: ' + (data.error || res.status), 'danger');
showToast(`Password updated for "${name}".`);
}