33 lines
1.0 KiB
TypeScript
33 lines
1.0 KiB
TypeScript
import type { H3Event } from 'h3'
|
|
import { joinURL } from 'ufo'
|
|
import { jwtDecode } from 'jwt-decode'
|
|
|
|
export default defineEventHandler(async (event: H3Event) => {
|
|
const { serverApiBaseUrl, clientProxyBasePath } = useRuntimeConfig().public
|
|
const escapedClientProxyBasePath = clientProxyBasePath.replace(/^\//, '\\/')
|
|
// Use the escaped value in the regex
|
|
const path = event.path.replace(new RegExp(`^${escapedClientProxyBasePath}`), '')
|
|
const target = joinURL(serverApiBaseUrl, path)
|
|
|
|
const session = await getUserSession(event)
|
|
const accessToken = session?.jwt?.accessToken
|
|
|
|
console.log('🔍 PROXY: proxying request, found access token:', accessToken)
|
|
console.log('🔍 PROXY: Expiration:', new Date(jwtDecode(accessToken).exp! * 1000).toISOString())
|
|
|
|
if (!accessToken) {
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: 'Not authenticated'
|
|
})
|
|
}
|
|
|
|
console.log('🔀 proxying request to', target)
|
|
|
|
return proxyRequest(event, target, {
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`
|
|
}
|
|
})
|
|
})
|