import { createFetch } from "@vueuse/core"; import { inject, type Ref, toValue } from "vue"; import type { TicketResponse } from "../interfaces"; let cachedToken: string | null = null; export function useAgendaAuth() { const origin = inject("agenda_origin", "https://app.dpa-agenda.de"); const auth0Tenant = inject("auth0_tenant", ""); const accessToken = inject>>("access_token"); // Use relative paths in development to go through Vite proxy const apiBase = import.meta.env.DEV ? "" : origin; async function getAgendaToken(): Promise { if (cachedToken !== null) { return cachedToken; } const normalizedToken = toValue(accessToken) ?? ""; if (normalizedToken === "") { throw new Error('The "access_token" was not provided'); } const body: Partial> = { access_token: normalizedToken, }; if (auth0Tenant) { body.tenant = auth0Tenant; } const response = await fetch(`${apiBase}/useradmin/access-token-exchange`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!response.ok) { throw new Error("Failed to exchange access token"); } const data: TicketResponse = await response.json(); cachedToken = data.ticket; return data.ticket; } const useAuthenticatedFetch = createFetch({ baseUrl: apiBase, options: { fetch: async (input, init = {}) => { init.headers = init.headers instanceof Headers ? init.headers : new Headers(init.headers ?? {}); const agendaToken = await getAgendaToken(); init.headers.set("authorization", `Bearer ${agendaToken}`); const response = await fetch(input, init); if (response.status === 401) { cachedToken = null; const agendaToken = await getAgendaToken(); init.headers.set("authorization", `Bearer ${agendaToken}`); return fetch(input, init); } return response; }, }, }); return { origin, apiBase, getAgendaToken, useAuthenticatedFetch }; }