Files
ai-xiaocai/server/public/js/auth.js

44 lines
1.4 KiB
JavaScript

// 认证与初始化
async function init() {
const token = Store.getToken();
if (token) {
try {
const res = await fetch('/api/user', { headers: { 'Authorization': 'Bearer ' + token } });
if (res.ok) {
document.getElementById('login-page').classList.add('hidden');
document.getElementById('main-page').classList.remove('hidden');
initWebSocket();
loadRooms();
updateSummaryPreview();
initSwipeGestures();
return;
}
} catch(e) {}
Store.clearAuth();
}
document.getElementById('login-page').classList.remove('hidden');
document.getElementById('main-page').classList.add('hidden');
}
async function login() {
const u = document.getElementById('login-user').value;
const p = document.getElementById('login-pass').value;
const res = await fetch('/api/login', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: u, password: p })
});
if (res.ok) {
const data = await res.json();
Store.saveAuth(data);
document.getElementById('login-page').classList.add('hidden');
document.getElementById('main-page').classList.remove('hidden');
initWebSocket();
loadRooms();
updateSummaryPreview();
initSwipeGestures();
} else {
const err = await res.json();
document.getElementById('login-error').textContent = err.error || '\u767b\u5f55\u5931\u8d25';
}
}