const CLIENTS = ['customer', 'policy', 'providers', 'workload', 'document'] as const const ORG_STORAGE_KEY = 'policy-ui.selected-org-id' const setAuthHeader = (ctx: { options: { headers?: Headers | Record | undefined } }, token: string) => { const headers = ctx.options.headers if (headers instanceof Headers) { if (!headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`) } else { const h = (headers ?? {}) as Record if (!h.Authorization && !h.authorization) { ctx.options.headers = { ...h, Authorization: `Bearer ${token}` } } } } const setOrgHeader = (ctx: { options: { headers?: Headers | Record | undefined } }, orgId: string) => { const headers = ctx.options.headers if (headers instanceof Headers) { if (!headers.has('x-organization-id')) headers.set('x-organization-id', orgId) } else { const h = (headers ?? {}) as Record if (!h['x-organization-id']) { ctx.options.headers = { ...h, 'x-organization-id': orgId } } } } export default defineNuxtPlugin({ name: 'open-fetch-auth', setup(nuxtApp) { for (const client of CLIENTS) { const hook = `openFetch:onRequest:${client}` as const nuxtApp.hook(hook, (ctx) => { const { data } = useAuth() const token = data.value?.user?.accessToken as string | undefined if (!token) return setAuthHeader(ctx, token) if (import.meta.client) { const orgId = localStorage.getItem(ORG_STORAGE_KEY) if (orgId) { setOrgHeader(ctx, orgId) } } }) } } })