Files
saladeaula.digital/id.saladeaula.digital/client/app/routes/authorize.ts
2025-10-30 02:02:23 -03:00

67 lines
1.7 KiB
TypeScript

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 loginUrl = new URL('/', url.origin)
const issuerUrl = new URL('/authorize', context.cloudflare.env.ISSUER_URL)
issuerUrl.search = url.search
loginUrl.search = url.search
if (!cookies?.__session) {
return new Response(null, {
status: httpStatus.FOUND,
headers: {
Location: loginUrl.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.FOUND) {
return new Response(await r.text(), {
status: r.status,
headers: r.headers
})
}
console.log('Issuer response', {
json: await r.json(),
headers: r.headers,
status: r.status
})
// Deny authorization if user lacks scopes requested by client
if (r.status === httpStatus.FORBIDDEN) {
return new Response(null, {
status: httpStatus.FOUND,
headers: {
Location: new URL('/deny', url.origin).toString()
}
})
}
return new Response(null, {
status: httpStatus.FOUND,
headers: {
Location: loginUrl.toString()
}
})
} catch (error) {
console.error(error)
return new Response(null, { status: httpStatus.INTERNAL_SERVER })
}
}