61 lines
2.4 KiB
JavaScript
61 lines
2.4 KiB
JavaScript
const $ = (s) => document.querySelector(s);
|
|
|
|
// Decide whether to show the sign-in form or the first-run setup form.
|
|
fetch('/api/me').then((r) => r.json()).then((m) => {
|
|
if (m.authed) { location.href = '/'; return; }
|
|
if (m.needsSetup) {
|
|
$('#loginView').style.display = 'none';
|
|
$('#setupView').style.display = 'block';
|
|
$('#s_username').focus();
|
|
} else {
|
|
$('#username').focus();
|
|
}
|
|
}).catch(() => {});
|
|
|
|
// --- sign in ---------------------------------------------------------------
|
|
async function signIn() {
|
|
const username = $('#username').value.trim();
|
|
const password = $('#password').value;
|
|
$('#err').textContent = '';
|
|
if (!username || !password) { $('#err').textContent = 'Enter your username and password.'; return; }
|
|
$('#signin').disabled = true;
|
|
try {
|
|
const res = await fetch('/api/login', {
|
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password })
|
|
});
|
|
const data = await res.json().catch(() => ({}));
|
|
if (!res.ok) throw new Error(data.error || 'Sign in failed.');
|
|
location.href = '/';
|
|
} catch (e) { $('#err').textContent = e.message; $('#signin').disabled = false; }
|
|
}
|
|
$('#signin').addEventListener('click', signIn);
|
|
|
|
// --- first-run setup -------------------------------------------------------
|
|
async function createAdmin() {
|
|
const username = $('#s_username').value.trim();
|
|
const email = $('#s_email').value.trim();
|
|
const password = $('#s_password').value;
|
|
const password2 = $('#s_password2').value;
|
|
$('#s_err').textContent = '';
|
|
if (!username || !password) { $('#s_err').textContent = 'Choose a username and password.'; return; }
|
|
if (password !== password2) { $('#s_err').textContent = 'The passwords do not match.'; return; }
|
|
$('#createAdmin').disabled = true;
|
|
try {
|
|
const res = await fetch('/api/setup', {
|
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, email, password })
|
|
});
|
|
const data = await res.json().catch(() => ({}));
|
|
if (!res.ok) throw new Error(data.error || 'Could not create the account.');
|
|
location.href = '/';
|
|
} catch (e) { $('#s_err').textContent = e.message; $('#createAdmin').disabled = false; }
|
|
}
|
|
$('#createAdmin').addEventListener('click', createAdmin);
|
|
|
|
document.addEventListener('keydown', (e) => {
|
|
if (e.key !== 'Enter') return;
|
|
if ($('#setupView').style.display !== 'none') createAdmin();
|
|
else signIn();
|
|
});
|