// Login page logic. Detects whether initial setup is required and adjusts the form. (async function init() { const errorBox = document.getElementById('errorBox'); const setupNote = document.getElementById('setupNote'); const title = document.getElementById('title'); const submitBtn = document.getElementById('submitBtn'); const form = document.getElementById('loginForm'); const passwordInput = document.getElementById('password'); let setupMode = false; function showError(msg) { errorBox.textContent = msg; errorBox.classList.add('visible'); } function clearError() { errorBox.textContent = ''; errorBox.classList.remove('visible'); } try { const r = await fetch('/api/auth/setup-required'); if (r.ok) { const data = await r.json(); setupMode = !!data.setupRequired; } } catch (e) { // Fall through: stay in login mode } if (setupMode) { title.textContent = 'Ersteinrichtung'; setupNote.style.display = 'block'; submitBtn.textContent = 'Administrator anlegen'; passwordInput.setAttribute('autocomplete', 'new-password'); passwordInput.setAttribute('minlength', '8'); } form.addEventListener('submit', async (e) => { e.preventDefault(); clearError(); submitBtn.disabled = true; const username = document.getElementById('username').value.trim(); const password = passwordInput.value; try { const url = setupMode ? '/api/auth/setup' : '/api/auth/login'; const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ username, password }), }); const data = await r.json().catch(() => ({})); if (!r.ok) { showError(data.error || 'Anmeldung fehlgeschlagen'); submitBtn.disabled = false; return; } window.location.href = '/'; } catch (err) { showError('Netzwerkfehler: ' + err.message); submitBtn.disabled = false; } }); })();