Files
org_web/assets/scripts/api-auth.js
Zaine Arch a76b559a0e Revert "hehe"
This reverts commit 138193ce13.
2026-05-09 01:18:08 +01:00

49 lines
1.3 KiB
JavaScript

(function () {
"use strict";
const STORAGE_KEY = "orgBackendApiKey";
const HEADER = "X-Org-Api-Key";
function getStoredKey() {
return window.localStorage.getItem(STORAGE_KEY) || "";
}
function requestKey() {
const key = window.prompt("API key");
if (key && key.trim()) {
window.localStorage.setItem(STORAGE_KEY, key.trim());
return key.trim();
}
return "";
}
function authHeaders(existingHeaders = {}, options = {}) {
const headers = new Headers(existingHeaders);
let key = getStoredKey();
if (!key && options.prompt !== false) {
key = requestKey();
}
if (key) headers.set(HEADER, key);
return headers;
}
async function authFetch(input, options = {}) {
const headers = authHeaders(options.headers, options);
const response = await fetch(input, { ...options, headers });
if (response.status !== 401) return response;
window.localStorage.removeItem(STORAGE_KEY);
if (options.retry === false) return response;
const retryHeaders = authHeaders(options.headers, options);
if (!retryHeaders.has(HEADER)) return response;
return fetch(input, { ...options, headers: retryHeaders, retry: false });
}
window.orgAuth = {
fetch: authFetch,
headers: authHeaders,
clear: () => window.localStorage.removeItem(STORAGE_KEY),
};
})();