This commit is contained in:
49
app/plugins/open-fetch-auth.ts
Normal file
49
app/plugins/open-fetch-auth.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1,20 +0,0 @@
|
||||
export default defineNuxtPlugin({
|
||||
name: 'open-fetch-policy-auth',
|
||||
setup(nuxtApp) {
|
||||
const { policyApiToken } = useRuntimeConfig().public
|
||||
const token = typeof policyApiToken === 'string' ? policyApiToken : ''
|
||||
if (!token) return
|
||||
|
||||
nuxtApp.hook('openFetch:onRequest:policy', (ctx) => {
|
||||
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}` }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user