import type { Route } from './+types' import * as httpStatus from '@/lib/http-status' import { parse } from 'cookie' export async function loader({ request, context }: Route.LoaderArgs) { const cookies = parse(request.headers.get('Cookie') || '') const url = new URL(request.url) const redirect = new URL('/', url.origin) const issuerUrl = new URL('/authorize', context.cloudflare.env.ISSUER_URL) issuerUrl.search = url.search redirect.search = url.search if (!cookies.session_id) { return new Response(null, { status: httpStatus.FOUND, headers: { Location: redirect.toString() } }) } try { const r = await fetch(issuerUrl.toString(), { method: 'GET', headers: new Headers([ ['Content-Type', 'application/json'], ['Cookie', request.headers.get('Cookie') as string] ]), redirect: 'manual' }) if (r.status === httpStatus.BAD_REQUEST) { return new Response(null, { status: httpStatus.FOUND, headers: { Location: redirect.toString() } }) } return new Response(await r.text(), { status: r.status, headers: r.headers }) } catch { return new Response(null, { status: httpStatus.INTERNAL_SERVER }) } }