feat: SW-162 Updated redirect to rewrite reducing unnecessary redirects for user

This commit is contained in:
Hrishikesh Vaipurkar
2024-07-19 13:15:56 +02:00
parent 767f5b5d2e
commit e264e4d2e2
5 changed files with 19 additions and 108 deletions

View File

@@ -1,68 +0,0 @@
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
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"
)
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
*/
const redirectUrl = await signIn(
"curity-mfa",
{
redirectTo,
redirect: false,
},
{
ui_locales: context.params.lang,
}
)
if (redirectUrl) {
return NextResponse.redirect(redirectUrl, {
headers: redirectHeaders,
})
}
} catch (error) {
if (error instanceof AuthError) {
console.error({ signInAuthError: error })
} else {
console.error({ signInError: error })
}
}
return internalServerError()
}

View File

@@ -15,6 +15,7 @@ export async function GET(
let redirectTo: string
const returnUrl = request.headers.get("x-returnurl")
const isMFA = request.headers.get("mfa-login")
if (returnUrl) {
// Seamless login request from Current web
@@ -85,8 +86,9 @@ export async function GET(
console.log({ login_env: process.env })
console.log({ login_redirectTo: redirectTo })
const signInProvider = isMFA ? "curity-mfa" : "curity"
const redirectUrl = await signIn(
"curity",
signInProvider,
{
redirectTo,
redirect: false,