87 lines
2.6 KiB
JavaScript
87 lines
2.6 KiB
JavaScript
/* Skuld — the login page: sign in, or create the admin on first run. */
|
|
|
|
(function () {
|
|
"use strict";
|
|
|
|
var title = document.querySelector("[data-title]");
|
|
var intro = document.querySelector("[data-intro]");
|
|
var loginForm = document.querySelector('[data-form="login"]');
|
|
var setupForm = document.querySelector('[data-form="setup"]');
|
|
|
|
/* The API names the field "username" or "password"; the two forms need their
|
|
own field keys, so the name is prefixed before the error is shown. */
|
|
function scoped(prefix, error) {
|
|
return {
|
|
status: error && error.status,
|
|
error: (error && error.error) || "Noko gjekk gale. Prøv om att.",
|
|
field: error && error.field ? prefix + "_" + error.field : null
|
|
};
|
|
}
|
|
|
|
function readValue(form, name) {
|
|
var input = form.querySelector('[name="' + name + '"]');
|
|
return input ? input.value : "";
|
|
}
|
|
|
|
function goToStart() {
|
|
return Skuld.api("GET", "/api/markets").then(function (markets) {
|
|
window.location.href = markets && markets.length ? "/" : "/marknader";
|
|
});
|
|
}
|
|
|
|
function showLogin() {
|
|
loginForm.hidden = false;
|
|
setupForm.hidden = true;
|
|
title.textContent = "Logg inn";
|
|
intro.textContent = "";
|
|
intro.hidden = true;
|
|
loginForm.querySelector('[name="username"]').focus();
|
|
}
|
|
|
|
function showSetup() {
|
|
setupForm.hidden = false;
|
|
loginForm.hidden = true;
|
|
title.textContent = "Første gong";
|
|
intro.textContent = "Lag administratoren som skal styre Skuld. "
|
|
+ "Brukarnamnet og passordet vert brukt på alle sidene.";
|
|
intro.hidden = false;
|
|
setupForm.querySelector('[name="username"]').focus();
|
|
}
|
|
|
|
loginForm.addEventListener("submit", function (event) {
|
|
event.preventDefault();
|
|
Skuld.clearErrors();
|
|
Skuld.api("POST", "/api/auth/login", {
|
|
username: readValue(loginForm, "username").trim(),
|
|
password: readValue(loginForm, "password")
|
|
}).then(goToStart).catch(function (error) {
|
|
Skuld.showError(scoped("login", error));
|
|
});
|
|
});
|
|
|
|
setupForm.addEventListener("submit", function (event) {
|
|
event.preventDefault();
|
|
Skuld.clearErrors();
|
|
Skuld.api("POST", "/api/auth/setup", {
|
|
username: readValue(setupForm, "username").trim(),
|
|
password: readValue(setupForm, "password")
|
|
}).then(goToStart).catch(function (error) {
|
|
Skuld.showError(scoped("setup", error));
|
|
});
|
|
});
|
|
|
|
Skuld.on("login", function () {
|
|
return Skuld.api("GET", "/api/auth/state").then(function (state) {
|
|
if (state.authenticated) {
|
|
return goToStart();
|
|
}
|
|
if (state.admin_exists) {
|
|
showLogin();
|
|
} else {
|
|
showSetup();
|
|
}
|
|
return null;
|
|
});
|
|
});
|
|
})();
|