fix: improve auth handling and logging

This commit is contained in:
Michael Zetterberg
2024-08-22 13:39:06 +02:00
parent 71d93864dd
commit a33a69fb58
15 changed files with 174 additions and 84 deletions
+10 -7
View File
@@ -49,9 +49,9 @@ export const middleware = auth(async (request) => {
}
const publicUrl = new URL(env.PUBLIC_URL)
const nextUrlClone = nextUrl.clone()
nextUrlClone.host = publicUrl.host
nextUrlClone.hostname = publicUrl.hostname
const nextUrlPublic = nextUrl.clone()
nextUrlPublic.host = publicUrl.host
nextUrlPublic.hostname = publicUrl.hostname
/**
* Function to validate MFA from token data
@@ -67,7 +67,7 @@ export const middleware = auth(async (request) => {
if (isLoggedIn && isMFAPath && isMFAInvalid()) {
const headers = new Headers(request.headers)
headers.set("x-returnurl", nextUrlClone.href)
headers.set("x-returnurl", nextUrlPublic.href)
headers.set("x-login-source", "mfa")
return NextResponse.rewrite(new URL(`/${lang}/login`, request.nextUrl), {
request: {
@@ -87,13 +87,16 @@ export const middleware = auth(async (request) => {
const headers = new Headers()
headers.append(
"set-cookie",
`redirectTo=${encodeURIComponent(nextUrlClone.href)}; Path=/; HttpOnly; SameSite=Lax`
`redirectTo=${encodeURIComponent(nextUrlPublic.href)}; Path=/; HttpOnly; SameSite=Lax`
)
const loginUrl = login[lang]
return NextResponse.redirect(new URL(loginUrl, nextUrlClone), {
const redirectUrl = new URL(loginUrl, nextUrlPublic)
const redirectOpts = {
headers,
})
}
console.log(`[authRequired] redirecting to: ${redirectUrl}`, redirectOpts)
return NextResponse.redirect(redirectUrl, redirectOpts)
}) as NextMiddleware // See comment above
export const matcher: MiddlewareMatcher = (request) => {