Files
automatic/javascript/authWrap.js
T
Vladimir Mandic 5baa23300d improve connection monitor and server restart
Signed-off-by: Vladimir Mandic <mandic00@live.com>
2026-04-25 08:50:57 +02:00

35 lines
881 B
JavaScript

let user;
let token;
async function getToken() {
if (token === undefined || user === undefined) {
const res = await fetch(`${window.subpath}/token`);
if (res.ok) {
const data = await res.json();
user = data.user;
token = data.token;
log('getToken', user);
}
}
return { user, token };
}
async function authFetch(url, options = {}) {
await getToken();
if (user && token) {
if (!options.headers) options.headers = {};
const encoded = btoa(`${user}:${token}`);
options.headers.Authorization = `Basic ${encoded}`;
}
let res;
try {
res = await fetch(url, options);
if (!res.ok) error('fetch', { status: res?.status || 503, url, user, token });
} catch (err) {
if (ConnectionMonitorState.online) {
error('fetch', { status: res?.status || 503, url, user, token, error: err });
}
}
return res;
}