Files
saladeaula.digital/apps/id.saladeaula.digital/app/routes/authorize.ts
2025-12-03 01:49:32 -03:00

51 lines
1.2 KiB
TypeScript

import type { Route } from './+types'
import { redirect } from 'react-router'
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?.SID) {
return new Response(null, {
status: 302,
headers: {
Location: loginUrl.toString()
}
})
}
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 === 302) {
return new Response(await r.text(), {
status: r.status,
headers: r.headers
})
}
// Deny authorization if user lacks scopes requested by client
if (r.status === 403) {
throw redirect(new URL('/deny', url.origin).toString())
}
return new Response(null, {
status: 302,
headers: {
Location: loginUrl.toString()
}
})
}