import { BASE_URL, getLoggedUser } from '../index.js' // // Page Element // const elErrorString = document.querySelector('#error-string') const elLoginUsernameInput = document.querySelector('#input-login-username') const elLoginPasswordInput = document.querySelector('#input-login-password') const elLoginButton = document.querySelector('#button-login') // // Display error message // let errorTimeoutHandle = null function displayErrorString(e) { if (errorTimeoutHandle) clearTimeout(errorTimeoutHandle) elErrorString.classList.toggle('hidden', false) elErrorString.innerText = e.toString() errorTimeoutHandle = setTimeout(() => { elErrorString.classList.toggle('hidden', true) elErrorString.innerText = '' }, 5 * 1000) } // // Handle Login Button // async function login() { try { const response = await fetch(`${BASE_URL}/api/login`, { method: 'POST', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', }, body: JSON.stringify({ username: elLoginUsernameInput.value, password: elLoginPasswordInput.value, }), }) if (!response.ok) { displayErrorString(await response.text()) return } location.href = `${BASE_URL}/` } catch (e) { displayErrorString(e) } } // // Main // async function main() { const user = await getLoggedUser() console.log(user) if (user) { location.href = `${BASE_URL}/` } elLoginButton.addEventListener('click', () => login()) elLoginPasswordInput.addEventListener('keydown', e => { if (e.key === 'Enter') login() }) elLoginUsernameInput.focus() } main()