97 lines
2.8 KiB
TypeScript
97 lines
2.8 KiB
TypeScript
import { encode } from "@auth/core/jwt"
|
|
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 value: string
|
|
|
|
redirectTo =
|
|
request.cookies.get("redirectTo")?.value || // Cookie gets set by authRequired middleware
|
|
request.nextUrl.searchParams.get("redirectTo") ||
|
|
"/"
|
|
|
|
// 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
|
|
}
|
|
|
|
// Clean up cookie from authRequired middleware
|
|
redirectHeaders = new Headers()
|
|
redirectHeaders.append(
|
|
"set-cookie",
|
|
"redirectTo=; Expires=Thu, 01 Jan 1970 00:00:00 UTC; Path=/; HttpOnly; SameSite=Lax"
|
|
)
|
|
value = "" + request.nextUrl.searchParams.get("nonce")?.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],
|
|
["nonce", value],
|
|
["acr_values", "cat"],
|
|
]
|
|
)
|
|
|
|
if (redirectUrl) {
|
|
// Check if needed based on discussion with Curity support for custom nonce
|
|
const token = { value }
|
|
const secret = env.NEXTAUTH_SECRET
|
|
const maxAge = 60 * 15
|
|
const name = "authjs.nonce"
|
|
const testingCookie = await encode({ secret, maxAge, token, salt: name })
|
|
console.log(testingCookie)
|
|
const expires = new Date()
|
|
expires.setTime(expires.getTime() + maxAge * 1000)
|
|
redirectHeaders.append(
|
|
"set-cookie",
|
|
"authjs.nonce=" +
|
|
testingCookie +
|
|
"; Expires=" +
|
|
expires +
|
|
"; Path=/; HttpOnly; SameSite=Lax"
|
|
)
|
|
redirectUrl = redirectUrl.replace(
|
|
/nonce=.*&code_challenge=/gi,
|
|
"nonce=" + value + "&code_challenge="
|
|
)
|
|
|
|
return NextResponse.redirect(redirectUrl, {
|
|
headers: redirectHeaders,
|
|
})
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof AuthError) {
|
|
console.error({ signInAuthError: error })
|
|
} else {
|
|
console.error({ signInError: error })
|
|
}
|
|
}
|
|
|
|
return internalServerError()
|
|
}
|