feat(SW-162): Updated MFA to use basic cookie validation

This commit is contained in:
Hrishikesh Vaipurkar
2024-08-09 13:18:49 +02:00
parent 1040c09147
commit 13ded529cc
3 changed files with 19 additions and 40 deletions

View File

@@ -1,4 +1,3 @@
import { decode } from "@auth/core/jwt"
import { cookies } from "next/headers"
import { NextResponse } from "next/server"
@@ -55,36 +54,19 @@ export const middleware = auth(async (request) => {
nextUrlClone.host = publicUrl.host
nextUrlClone.hostname = publicUrl.hostname
async function isMFAInvalid() {
/**
* Function to validate MFA cookie expiry
* @returns boolean
*/
function isMFAInvalid() {
const isMFAPath = mfaRequired.includes(nextUrl.pathname)
const cookieStore = cookies()
const mfaCookieValue = cookieStore.get("_SecureMFA-token")?.value
if (mfaCookieValue) {
try {
const mfaToken = await decode({
token: mfaCookieValue,
secret: env.NEXTAUTH_SECRET,
salt: "_SecureMFA-token",
})
if (mfaToken?.exp) {
return false
} else {
return true
}
} catch (e) {
console.log("JWT decode failed", e)
cookieStore.set("_SecureMFA-token", "", { maxAge: 0 })
return true
}
} else {
return true
}
return isMFAPath && !cookieStore.get("_MFA-validated-cookie")?.value
}
const isMFAPath = mfaRequired.includes(nextUrl.pathname)
const mfaInvalid = isMFAPath ? await isMFAInvalid() : false
if (isLoggedIn && mfaInvalid) {
if (isLoggedIn && isMFAInvalid()) {
const headers = new Headers(request.headers)
headers.set("mfa-login", "true")
headers.set("x-mfa-login", "true")
headers.set("x-returnurl", request.nextUrl.href)
return NextResponse.rewrite(new URL(`/${lang}/login`, request.nextUrl), {
request: {