diff --git a/www/res/access-multiple.js b/www/res/access-multiple.js index d2791cf..3322fd4 100644 --- a/www/res/access-multiple.js +++ b/www/res/access-multiple.js @@ -1,85 +1,58 @@ "use strict"; -window.CLIENTS = window.CLIENTS || []; +window.CLIENT = window.CLIENT || null; +window.CLIENTS = window.CLIENTS || {}; -function getCredentialsUsername(client) { +function getStoredUsername(client) { return window.localStorage.getItem(`${CLIENT}/${client}/username`); } -function getCredentialsPassword(client) { - return window.localStorage.getItem(`${CLIENT}/${client}/password`); +function getStoredToken(client) { + return window.localStorage.getItem(`${CLIENT}/${client}/token`); } -function getBasicAuth(client) { +function getAuthorizationHeader(client) { return { - 'Authorization': 'Basic ' + btoa(getCredentialsUsername(client) + ':' + getCredentialsPassword(client)), + 'Authorization': 'Bearer ' + window.localStorage.getItem(`${CLIENT}/${client}/token`), }; } -async function _get(client, path) { +async function authenticate(client, username, password) { + const res = await fetch(`${CLIENTS[client]['api']}/auth`, { + method: 'GET', + headers: {'Authorization': 'Basic ' + btoa(username + ':' + password)}, + }); + const json = await res.json(); + if (!res.ok) throw new ApiError(res.status, json['message']); + return json['token']; +} + +async function get(client, path) { const res = await fetch(`${CLIENTS[client]['api']}${path}`, { method: 'GET', - headers: {...getBasicAuth(client)}, + headers: {...getAuthorizationHeader(client)}, }); const json = await res.json(); if (!res.ok) throw new ApiError(res.status, json['message']); return json; } -async function get(client, path) { - return (await _get(client, path))['data']; -} - -async function getWineVarieties(client) { - return Object.fromEntries((await get(client, '/wine/varieties')).map(item => [item['sortid'], item])); -} - -async function getWineQualityLevels(client) { - return Object.fromEntries((await get(client, '/wine/quality_levels')).map(item => [item['qualid'], item])); -} - async function getDeliverySchedules(client, filters, limit, offset) { const query = []; if (!!filters) query.push(`filters=${filters.join(',')}`); if (!!limit) query.push(`limit=${limit}`); if (!!offset) query.push(`offset=${offset}`); - return await _get(client, `/delivery_schedules${!!query ? '?' : ''}${query.join('&')}`); -} - -async function load(client) { - const main = document.getElementById("access"); - const form = main.getElementsByTagName("form")[0]; - if (form) { - const elements = form.getElementsByClassName('error'); - for (const e of elements) form.removeChild(e); - } - try { - window.WINE_VARIETIES = await getWineVarieties(client); - window.WINE_QUALITY_LEVELS = await getWineQualityLevels(client); - return true; - } catch (e) { - if (form) { - window.localStorage.removeItem(`${CLIENT}/${client}/password`); - const error = document.createElement('div'); - error.className = 'error'; - error.innerText = e.localizedMessage ?? ERROR_MESSAGES[e.message] ?? 'Unbekannter Fehler'; - form.insertBefore(error, form.lastChild.previousSibling); - } else { - window.location.hash = `#/${client}/login`; - } - return false; - } + return await get(client, `/delivery_schedules${!!query ? '?' : ''}${query.join('&')}`); } async function init() { - //await load(); render(); } async function updateOverview(client) { const [schedules] = await Promise.all([getDeliverySchedules(client, [`year=${getCurrentLastSeason()}`])]); const rows = []; - const days = groupBy(schedules.data, 'date'); + const days = groupBy(schedules['data'], 'date'); const now = new Date(); for (const [dateString, day] of Object.entries(days)) { const date = new Date(dateString); @@ -132,12 +105,12 @@ function render() { const client = Object.keys(CLIENTS).find(id => hash.startsWith(`#/${id}/`) || hash === `#/${id}`); if (client === undefined) { - window.location.hash = `#/${Object.keys(CLIENTS).find(id => !!getCredentialsUsername(id) && !!getCredentialsPassword(id)) || Object.keys(CLIENTS)[0]}`; + window.location.hash = `#/${Object.keys(CLIENTS).find(id => !!getStoredUsername(id) && !!getStoredToken(id)) || Object.keys(CLIENTS)[0]}`; return; } nav.children[Object.keys(CLIENTS).indexOf(client)].className = 'active'; - if ((!getCredentialsUsername(client) || !getCredentialsPassword(client)) && window.location.hash !== `#/${client}/login`) { + if ((!getStoredUsername(client) || !getStoredToken(client)) && window.location.hash !== `#/${client}/login`) { window.location.hash = `#/${client}/login`; return; } @@ -147,7 +120,7 @@ function render() { main.innerHTML = `

Anmelden

- + @@ -179,19 +152,29 @@ document.addEventListener('DOMContentLoaded', async () => { setInterval(update, 60_000); }); -window.addEventListener('hashchange', () => { - render(); -}); +window.addEventListener('hashchange', render); window.addEventListener('pageshow', update) document.addEventListener('visibilitychange', update); function actionLogin(form) { - window.localStorage.setItem(`${CLIENT}/${form.client.value}/username`, form.username.value); - window.localStorage.setItem(`${CLIENT}/${form.client.value}/password`, form.password.value); - load(form.client.value).then(success => { - if (success) window.location.hash = `#/${form.client.value}`; - }); + const elements = form.getElementsByClassName('error'); + for (const e of elements) form.removeChild(e); + + const client = form['client'].value; + window.localStorage.setItem(`${CLIENT}/${client}/username`, form['username'].value); + + authenticate(client, form['username'].value, form['password'].value) + .then(token => { + window.localStorage.setItem(`${CLIENT}/${client}/token`, token); + window.location.hash = `#/${client}`; + }).catch(e => { + const error = document.createElement('div'); + error.className = 'error'; + error.innerText = e.localizedMessage ?? ERROR_MESSAGES[e.message] ?? 'Unbekannter Fehler'; + form.insertBefore(error, form.lastChild.previousSibling); + }); + return false; } diff --git a/www/res/access-single.js b/www/res/access-single.js index 5a79c62..5ff4ea2 100644 --- a/www/res/access-single.js +++ b/www/res/access-single.js @@ -1,5 +1,6 @@ "use strict"; +window.CLIENT = window.CLIENT || null; window.ELWIG_API = window.ELWIG_API || null; function getCredentialsUsername() {