62 lines
2.6 KiB
JavaScript
62 lines
2.6 KiB
JavaScript
(function () {
|
|
'use strict';
|
|
const status = document.getElementById('loginStatusText');
|
|
|
|
const form = document.querySelector('.centerLoginPanel');
|
|
const button = form.querySelector('button');
|
|
const buttonLabel = button.querySelector('span');
|
|
const message = document.getElementById('loginMsg');
|
|
const username = document.getElementById('username');
|
|
const password = document.getElementById('password');
|
|
let needsSetup = false;
|
|
button.disabled = true;
|
|
|
|
async function prepare() {
|
|
const response = await fetch('/api/auth/status', { cache: 'no-store' });
|
|
if (!response.ok) throw new Error('无法读取本地服务状态');
|
|
const account = await response.json();
|
|
if (account.authenticated) return location.replace('/workbench/platform.html');
|
|
needsSetup = !account.configured;
|
|
buttonLabel.textContent = needsSetup ? '创建管理员' : '登录';
|
|
password.autocomplete = needsSetup ? 'new-password' : 'current-password';
|
|
password.minLength = needsSetup ? 10 : 0;
|
|
status.textContent = needsSetup ? '首次运行,请设置管理员账号和至少 10 字符的密码' : '本地账号验证';
|
|
button.disabled = false;
|
|
}
|
|
|
|
form.addEventListener('submit', async event => {
|
|
event.preventDefault();
|
|
button.disabled = true;
|
|
message.textContent = '';
|
|
status.textContent = needsSetup ? '正在创建管理员' : '正在验证本地账号';
|
|
try {
|
|
const response = await fetch(`/api/auth/${needsSetup ? 'setup' : 'login'}`, {
|
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: username.value.trim(), password: password.value })
|
|
});
|
|
password.value = '';
|
|
const data = await response.json().catch(() => ({}));
|
|
if (!response.ok) {
|
|
if (response.status === 409) await prepare();
|
|
throw new Error(data.error || '本地账号验证失败');
|
|
}
|
|
status.textContent = '认证通过,正在进入平台';
|
|
location.replace('/workbench/platform.html');
|
|
} catch (error) {
|
|
message.textContent = error.message;
|
|
status.textContent = '请检查后重试';
|
|
button.disabled = false;
|
|
}
|
|
});
|
|
prepare().catch(error => { message.textContent = error.message; });
|
|
fetch('/api/workbench/branding', { cache: 'no-store' })
|
|
.then(response => response.ok ? response.json() : null)
|
|
.then(branding => {
|
|
if (!branding?.name) return;
|
|
document.getElementById('loginPlatformName').textContent = branding.name;
|
|
document.getElementById('loginFooterName').textContent = branding.name;
|
|
document.title = `登录 - ${branding.name}`;
|
|
})
|
|
.catch(() => {});
|
|
})();
|