Files
policy-ui/app/plugins/open-fetch-auth.ts
HaimKortovich 3a52768b97
Some checks failed
Build and Publish / build-release (push) Failing after 1m31s
fix auth
2026-05-14 12:12:03 -05:00

50 lines
1.6 KiB
TypeScript

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<string, string> | 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<string, string>
if (!h.Authorization && !h.authorization) {
ctx.options.headers = { ...h, Authorization: `Bearer ${token}` }
}
}
}
const setOrgHeader = (ctx: { options: { headers?: Headers | Record<string, string> | 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<string, string>
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)
}
}
})
}
}
})