import { createFeedbackController, escapeHtml } from './modules/common.js'; import { buildLoginUrl, loadAuthState, redirectToNextPath } from './modules/auth-client.js'; const feedback = createFeedbackController(document.querySelector('#feedback')); const authSummaryElement = document.querySelector('#authSummary'); const setupForm = document.querySelector('#setupForm'); const setupButton = document.querySelector('#setupButton'); function setSummaryRows(rows) { authSummaryElement.innerHTML = `
${rows .map( (row) => `
${escapeHtml(row.label)} ${escapeHtml(row.value)}
` ) .join('')}
`; } async function postJson(url, payload) { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const body = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(`${body.error?.code ?? 'REQUEST_FAILED'}: ${body.error?.message ?? 'Request failed.'}`); } return body; } async function refreshAuthState() { const auth = await loadAuthState(); if (auth.authenticated) { setSummaryRows([ { label: '状态', value: `已登录:${auth.username}` }, { label: '会话有效期', value: auth.expiresAt ?? '未知' } ]); redirectToNextPath('/'); return; } if (!auth.setupRequired) { window.location.assign(buildLoginUrl()); return; } setSummaryRows([ { label: '系统状态', value: '尚未配置管理员账号' }, { label: '下一步', value: '创建管理员账号并进入系统' } ]); } async function handleSetup(event) { event.preventDefault(); feedback.clear(); const password = document.querySelector('#setupPassword').value; const passwordConfirm = document.querySelector('#setupPasswordConfirm').value; if (password !== passwordConfirm) { feedback.set('error', '两次输入的密码不一致。'); return; } setupButton.disabled = true; try { await postJson('/api/auth/setup', { username: document.querySelector('#setupUsername').value.trim(), password }); await refreshAuthState(); } catch (error) { feedback.set('error', error.message); } finally { setupButton.disabled = false; } } setupForm.addEventListener('submit', (event) => { void handleSetup(event); }); void refreshAuthState().catch((error) => { feedback.set('error', error.message); setSummaryRows([ { label: '状态', value: '无法读取认证信息' }, { label: '错误', value: error.message } ]); });