Files
web/app/[lang]/(live)/(public)/verifymagiclink/route.ts
2024-08-19 12:02:05 +02:00

81 lines
2.4 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server"
import { AuthError } from "next-auth"
import { Lang } from "@/constants/languages"
import { login } from "@/constants/routes/handleAuth"
import { env } from "@/env/server"
import { internalServerError } from "@/server/errors/next"
import { signIn } from "@/auth"
export async function GET(
request: NextRequest,
context: { params: { lang: Lang } }
) {
let redirectTo: string
let loginKey: string | null
redirectTo = request.cookies.get("Scandic-auth.callback-url")?.value || "/" // Cookie gets set by NextAuth from login initiation
// Make relative URL to absolute URL
if (redirectTo.startsWith("/")) {
if (!env.PUBLIC_URL) {
throw internalServerError("No value for env.PUBLIC_URL")
}
redirectTo = new URL(redirectTo, env.PUBLIC_URL).href
}
// Remove Seamless login as it doesn't work with Magic link login
if (redirectTo.indexOf("updatelogin?returnurl") !== -1) {
// Additional URL decode required as url in the query parameter is encoded twice due to passed in query param and further in cookie value.
redirectTo = decodeURIComponent(
redirectTo.substring(redirectTo.indexOf("returnurl") + 10)
)
}
loginKey = request.nextUrl.searchParams.get("loginKey")
if (!loginKey) {
if (!env.PUBLIC_URL) {
throw internalServerError("No value for env.PUBLIC_URL")
}
const publicUrl = new URL(env.PUBLIC_URL)
const loginUrl = login[context.params.lang]
return NextResponse.redirect(new URL(loginUrl, publicUrl))
}
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_redirectTo: redirectTo })
let redirectUrl = await signIn(
"curity",
{
redirectTo,
redirect: false,
},
{
ui_locales: context.params.lang,
loginKey: loginKey,
acr_values: "cat",
prompt: "login",
}
)
if (redirectUrl) {
return NextResponse.redirect(redirectUrl)
}
} catch (error) {
if (error instanceof AuthError) {
console.error({ signInAuthError: error })
} else {
console.error({ signInError: error })
}
}
return internalServerError()
}