const API_URL = 'https://fb.srv.medeba-media.de/api'; function getRedirectTarget() { try { const params = new URLSearchParams(window.location.search); const redirect = params.get('redirect'); if (redirect) { return decodeURIComponent(redirect); } } catch (error) { console.warn('Konnte Redirect-Parameter nicht lesen:', error); } return 'index.html'; } function updateStatus(message, isError = false) { const statusEl = document.getElementById('status'); if (!statusEl) { return; } statusEl.textContent = message || ''; statusEl.style.color = isError ? '#b91c1c' : '#15803d'; } async function checkExistingSession() { try { const response = await fetch(`${API_URL}/session`, { credentials: 'include' }); if (response.ok) { const data = await response.json(); if (data && data.authenticated) { window.location.href = getRedirectTarget(); return true; } } } catch (error) { console.warn('Konnte Session nicht prüfen:', error); } return false; } async function handleLogin(event) { event.preventDefault(); const usernameInput = document.getElementById('username'); const passwordInput = document.getElementById('password'); const username = usernameInput ? usernameInput.value.trim() : ''; const password = passwordInput ? passwordInput.value : ''; if (!username || !password) { updateStatus('Bitte Benutzername und Passwort eingeben.', true); return; } updateStatus('Anmeldung läuft…', false); try { const response = await fetch(`${API_URL}/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ username, password }) }); if (!response.ok) { const payload = await response.json().catch(() => ({})); const message = payload && payload.error ? payload.error : 'Anmeldung fehlgeschlagen'; updateStatus(message, true); return; } updateStatus('Erfolgreich angemeldet. Weiterleitung…', false); window.location.href = getRedirectTarget(); } catch (error) { console.error('Login fehlgeschlagen:', error); updateStatus('Netzwerkfehler – bitte erneut versuchen.', true); } } document.addEventListener('DOMContentLoaded', async () => { const alreadyLoggedIn = await checkExistingSession(); if (alreadyLoggedIn) { return; } const form = document.getElementById('loginForm'); if (form) { form.addEventListener('submit', handleLogin); } });