const form = document.querySelector('#auth-form'); // Keep login standalone: the server renders the prefix in both HTML documents. const basePath = (document.querySelector('meta[name="ranch-web-base-path"]')?.content || '').replace(/\/+$/, ''); const webPath = path => `${basePath}${path}`; form.setAttribute('action', webPath('/api/auth/login')); const input = document.querySelector('#admin-password'); const button = form.querySelector('button[type="submit"]'); const status = document.querySelector('#auth-status'); const error = document.querySelector('#auth-error'); let busy = false; let leaving = false; function setBusy(value, message = '') { busy = value; input.disabled = value; button.disabled = value; form.setAttribute('aria-busy', String(value)); status.textContent = message; status.hidden = !message; } function showError(message) { error.textContent = message; error.hidden = false; } function openWorkbench() { leaving = true; input.value = ''; setBusy(true, '正在进入工作台…'); location.replace(webPath('/')); } async function authRequest(path, body) { let response; try { response = await fetch(webPath(path), { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: body === undefined ? {Accept: 'application/json'} : {Accept: 'application/json', 'Content-Type': 'application/json'}, body, }); } catch { throw new Error('无法连接 Web 服务,请检查服务是否仍在运行后重试。'); } const data = await response.json().catch(() => null); if (!response.ok) { const message = typeof data?.detail === 'string' ? data.detail : data?.error?.message; throw new Error(message || `请求未完成(HTTP ${response.status}),请重试。`); } if (!data || typeof data.required !== 'boolean' || typeof data.authenticated !== 'boolean') { throw new Error('无法确认登录状态,请重试。'); } return data; } async function checkAuth() { setBusy(true, '正在检查登录状态…'); error.hidden = true; try { const auth = await authRequest('/api/auth/status'); if (!auth.required || auth.authenticated) openWorkbench(); } catch (failure) { showError(failure.message); } finally { if (!leaving) { setBusy(false); input.focus(); } } } form.addEventListener('submit', async event => { event.preventDefault(); if (busy || leaving || !form.reportValidity()) return; const body = JSON.stringify({password: input.value}); input.value = ''; error.hidden = true; setBusy(true, '正在登录…'); try { const auth = await authRequest('/api/auth/login', body); if (!auth.required || auth.authenticated) openWorkbench(); else showError('登录未完成,请重新输入管理密码。'); } catch (failure) { showError(failure.message); } finally { if (!leaving) { setBusy(false); input.focus(); } } }); window.addEventListener('pagehide', () => { input.value = ''; }); window.addEventListener('pageshow', event => { if (event.persisted) { leaving = false; input.value = ''; checkAuth(); } }); checkAuth();