fix: improve auth handling and logging

This commit is contained in:
Michael Zetterberg
2024-08-22 13:39:06 +02:00
parent 71d93864dd
commit a33a69fb58
15 changed files with 174 additions and 84 deletions

View File

@@ -11,6 +11,10 @@ export async function GET(
request: NextRequest,
context: { params: { lang: Lang } }
) {
if (!env.PUBLIC_URL) {
throw internalServerError("No value for env.PUBLIC_URL")
}
let redirectHeaders: Headers | undefined = undefined
let redirectTo: string
@@ -20,10 +24,6 @@ export async function GET(
const isSeamlessMagicLink =
request.headers.get("x-login-source") === "seamless-magiclink"
if (!env.PUBLIC_URL) {
throw internalServerError("No value for env.PUBLIC_URL")
}
console.log(
`[login] source: ${request.headers.get("x-login-source") || "normal"}`
)
@@ -32,6 +32,7 @@ export async function GET(
const redirectToSearchParamValue =
request.nextUrl.searchParams.get("redirectTo")
const redirectToFallback = "/"
console.log(`[login] redirectTo cookie value: ${redirectToCookieValue}`)
console.log(
`[login] redirectTo search param value: ${redirectToSearchParamValue}`
@@ -104,20 +105,16 @@ export async function GET(
)
} catch (e) {
console.error(
"Unable to create URL for seamless login, proceeding without it."
"[login] unable to create URL for seamless login, proceeding without it.",
e
)
console.error(e)
}
}
try {
/**
* Passing `redirect: false` to `signIn` will return the URL instead of
* automatically redirecting to it inside of `signIn`.
* https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L76
*/
console.log(`[login] final redirectUrl: ${redirectTo}`)
console.log({ login_env: process.env })
/** Record<string, any> is next-auth typings */
const params: Record<string, any> = {
ui_locales: context.params.lang,
@@ -152,6 +149,11 @@ export async function GET(
params.acr_values = "abc"
}
params.scope = params.scope.join(" ")
/**
* Passing `redirect: false` to `signIn` will return the URL instead of
* automatically redirecting to it inside of `signIn`.
* https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L76
*/
const redirectUrl = await signIn(
"curity",
{
@@ -162,9 +164,13 @@ export async function GET(
)
if (redirectUrl) {
return NextResponse.redirect(redirectUrl, {
const redirectOpts = {
headers: redirectHeaders,
})
}
console.log(`[login] redirecting to: ${redirectUrl}`, redirectOpts)
return NextResponse.redirect(redirectUrl, redirectOpts)
} else {
console.error(`[login] missing redirectUrl reponse from signIn()`)
}
} catch (error) {
if (error instanceof AuthError) {