76 lines
2.0 KiB
TypeScript
76 lines
2.0 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 { badRequest, internalServerError } from "@/server/errors/next"
|
|
|
|
import { signIn } from "@/auth"
|
|
|
|
export async function GET(
|
|
request: NextRequest,
|
|
context: { params: { lang: Lang } }
|
|
) {
|
|
let redirectTo: string
|
|
|
|
// Set redirect url from the magicLinkRedirect Cookie which is set when intiating login
|
|
redirectTo =
|
|
request.cookies.get("magicLinkRedirectTo")?.value ||
|
|
"/" + context.params.lang
|
|
|
|
if (!env.PUBLIC_URL) {
|
|
throw internalServerError("No value for env.PUBLIC_URL")
|
|
}
|
|
|
|
// Make relative URL to absolute URL
|
|
if (redirectTo.startsWith("/")) {
|
|
redirectTo = new URL(redirectTo, env.PUBLIC_URL).href
|
|
}
|
|
|
|
// Update Seamless login url as Magic link login has a different authenticator in Curity
|
|
redirectTo = redirectTo.replace("updatelogin", "updateloginemail")
|
|
|
|
const loginKey = request.nextUrl.searchParams.get("loginKey")
|
|
|
|
if (!loginKey) {
|
|
return badRequest()
|
|
}
|
|
|
|
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,
|
|
scope: ["openid", "profile"].join(" "),
|
|
loginKey: loginKey,
|
|
for_origin: env.PUBLIC_URL,
|
|
acr_values: "abc",
|
|
version: "2",
|
|
}
|
|
)
|
|
|
|
if (redirectUrl) {
|
|
return NextResponse.redirect(redirectUrl)
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof AuthError) {
|
|
console.error({ signInAuthError: error })
|
|
} else {
|
|
console.error({ signInError: error })
|
|
}
|
|
}
|
|
|
|
return internalServerError()
|
|
}
|