| |
|
|
| import { AUTH_TOKEN_STORAGE_KEY } from './constants.js'; |
|
|
| |
| |
| |
| |
| |
| |
| export function setupLoginForm(loginForm, authTokenInput, errorMessage) { |
| if (loginForm) { |
| loginForm.addEventListener('submit', async (e) => { |
| e.preventDefault(); |
| const authToken = authTokenInput.value.trim(); |
|
|
| if (!authToken) { |
| errorMessage.textContent = '认证令牌不能为空。'; |
| return; |
| } |
|
|
| localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, authToken); |
|
|
| try { |
| const response = await fetch('/v1/health', { |
| headers: { |
| 'X-Auth-Token': authToken |
| } |
| }); |
|
|
| if (response.ok) { |
| |
| window.location.href = '/static/index.html'; |
| } else { |
| const errorData = await response.json(); |
| errorMessage.textContent = `登录失败: ${errorData.detail || response.statusText}`; |
| localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY); |
| } |
| } catch (error) { |
| errorMessage.textContent = `登录请求出错: ${error.message}`; |
| localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY); |
| } |
| }); |
| } |
| } |
|
|
| |
| |
| |
| |
| export function setupLogoutButton(logoutButton) { |
| if (logoutButton) { |
| logoutButton.addEventListener('click', () => { |
| localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY); |
| window.location.href = '/static/login.html'; |
| }); |
| } |
| } |
|
|
| |
| |
| |
| export function checkAuthAndRedirect() { |
| const storedAuthToken = localStorage.getItem(AUTH_TOKEN_STORAGE_KEY); |
|
|
| if (storedAuthToken) { |
| if (window.location.pathname === '/static/login.html') { |
| window.location.href = '/static/index.html'; |
| } |
| } else { |
| if (window.location.pathname !== '/static/login.html') { |
| window.location.href = '/static/login.html'; |
| } |
| } |
| } |
|
|