import { NextRequest, NextResponse } from "next/server" import { AuthError } from "next-auth" import { Lang } from "@/constants/languages" 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 redirectHeaders: Headers | undefined = undefined let redirectTo: string let loginKey: string 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")?.toString() 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() }