function fillTemplate(templateId, values) { var tpl = document.getElementById(templateId).text; Object.keys(values).forEach(key => { tpl = tpl.replace(new RegExp("\\[\\[ \\." + key + " \\]\\]", "g"), values[key]); }); var out = []; tpl.split("\n").forEach(line => { line = line.replace(/^\s+/, "").replace(/\s+$/, ""); if (line !== "") { out.push(line); } }); return out.join("\n"); } function getJSON(response) { if (!response.ok) { document.getElementById("api-error").style.display = "block"; throw new Error("Error loading api"); } return response.json(); } function accountTableLinkClick(event) { event.preventDefault(); var thisRow = event.target.parentElement.parentElement; var account = thisRow.dataset["accountName"]; var oldText = event.target.text; var existingTr = document.getElementById("credentials-for-" + account); if (existingTr) { existingTr.remove(); } event.target.text = "Loading..."; fetch(thisRow.dataset["globalCredentialEndpoint"], { "headers": { "Accept": event.target.dataset["contentType"] } }).then(r => r.text()).then(text => { var newTr = fillTemplate("credential_row_template", { "Account": account, "Content": text, }); event.target.text = oldText; thisRow.insertAdjacentHTML("afterend", newTr); thisRow.nextElementSibling.getElementsByTagName("button")[0].addEventListener("click", e => { e.target.parentNode.parentNode.remove(); }); }); return false; } function populateAccountRow(row) { document.querySelector("#account-table tr").insertAdjacentHTML("afterend", fillTemplate(row["vendor"] + "_account_row_template", row)); document.querySelectorAll(".account-row a[data-content-type]").forEach(e => { e.addEventListener("click", accountTableLinkClick); }); } function getCookie(name) { return document.cookie.match(new RegExp(name + "=\"?([^;\"]*)\"?;?"))[1]; } function parseJWT() { return JSON.parse(atob(getCookie("github-token").split(".")[1])); } function parseJWTExpires() { return new Date(parseJWT()["exp"] * 1000); } function isAdmin() { return parseJWT()["admin"]; } function setupHomePage() { fetch("/api/account").then(getJSON).then(r => r.forEach(populateAccountRow)); document.getElementById("username").innerText = parseJWT()["sub"]; if (isAdmin()) { document.body.classList.add("isAdmin"); } document.getElementById("show-api-key").addEventListener("click", _ => { document.querySelector("#api-key textarea").innerText = getCookie("github-token"); document.querySelector("#session-expires").innerText = parseJWTExpires(); document.getElementById("api-key-block").style.display = "block"; }); }