async function gcp_fetch(url) { return await fetch( //"https://europe-west3-mgcp-1252957-omg-shared.cloudfunctions.net/Barclays-Assistants-Make-Request?origin=" + encodeURI(window?.location?.origin), //"https://europe-west2-arctic-surf-386912.cloudfunctions.net/Barclays-Assistants-Make-Request?origin=" + encodeURI(window?.location?.origin), "https://aifunctions.oliver.solutions/baic-auth?origin=" + encodeURI(window?.location?.origin), //"https://europe-west3-mgcp-1252957-omg-shared.cloudfunctions.net/baic_auth?origin=" + encodeURI(window?.location?.origin), //"https://us-central1-optical-414516.cloudfunctions.net/baic_auth?origin=" + encodeURI(window?.location?.origin), { method: "POST", mode: "cors", credentials: "include", headers: { "Content-type": "application/json" }, body: JSON.stringify({ url }), } ); } async function authenticate() { const url = new URL(window.location.href); const redirect_uri = window.location.href.split("?")[0] === "http://127.0.0.1:5500/baic/" ? "http://localhost:5500/baic/" : window.location.href.split("?")[0]; login_url = `https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/authorize?client_id=${client_id}&response_type=code&redirect_uri=${redirect_uri}&response_mode=query&scope=User.Read`; const auth_code_url_parameter = url.searchParams.get("code"); if (auth_code_url_parameter) { await new Promise((resolve) => { gcp_fetch(make_url + `?Login=True&Code=${encodeURI(auth_code_url_parameter)}&RedirectURI=${redirect_uri}`) .then((response) => response.json()) .then((res) => { if (res?.error || res?.token === undefined) { history.pushState({}, "", window.location.href); window.location.href = login_url; window.location.replace(login_url); } else { let params = new URLSearchParams(window.location.href.split("?")[1]); params.delete("code"); params.delete("session_state"); var new_url = window.location.href.split("?")[0] + (params.toString().length === 0 ? "" : "?" + params.toString()); window.location.href = new_url; window.location.replace(new_url); resolve(true); } }) .catch((error) => { console.error(error); resolve(true); }); }); } await new Promise((resolve) => { gcp_fetch(make_url + "?CheckAuth=True") .then((response) => response.text()) .then((text) => { let data; try { data = JSON.parse(text); } catch (error) { data = { authenticated: false, msg: "Login was failed or not done. Tech note: check Make.com activation or error", }; } return data; }) .then((data) => { if (data.authenticated) { onAuthenticated(); } else { history.pushState({}, "", window.location.href); window.location.href = login_url; window.location.replace(login_url); } resolve(true); }) .catch((error) => { console.error(error); resolve(true); }); }); } async function logOut() { await gcp_fetch("clear_cookies"); const logout_url = "https://login.microsoftonline.com/" + tenant_id + "/oauth2/logout"; window.location.href = logout_url; window.location.replace(logout_url); } // Runs on Start Up authenticate();