From bd6c803a4becced8f4ad3ee67fb6c138118a8e95 Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Thu, 13 Feb 2025 10:53:39 +0700 Subject: [PATCH] Update --- .../auth/legacy/next-auth-cookie-migration.ts | 60 +++++++++++-------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/apps/web/src/auth/legacy/next-auth-cookie-migration.ts b/apps/web/src/auth/legacy/next-auth-cookie-migration.ts index 8995c2357..0f41b4451 100644 --- a/apps/web/src/auth/legacy/next-auth-cookie-migration.ts +++ b/apps/web/src/auth/legacy/next-auth-cookie-migration.ts @@ -2,6 +2,7 @@ import { absoluteUrl } from "@rallly/utils/absolute-url"; import { cookies } from "next/headers"; import type { NextResponse } from "next/server"; import type { Session } from "next-auth"; +import type { JWT } from "next-auth/jwt"; import { encode } from "next-auth/jwt"; import { decodeLegacyJWT } from "./helpers/jwt"; @@ -16,7 +17,7 @@ const newCookieName = prefix + "authjs.session-token"; export async function getLegacySession(): Promise { const cookieStore = cookies(); const legacySessionCookie = cookieStore.get(oldCookieName); - if (legacySessionCookie) { + if (legacySessionCookie && legacySessionCookie.value) { const decodedCookie = await decodeLegacyJWT(legacySessionCookie.value); if (decodedCookie?.sub) { @@ -45,30 +46,12 @@ async function getLegacyJWT() { return null; } -/** - * Replace the old legacy cookie with the new one - */ -export async function migrateLegacyJWT(res: NextResponse) { - const legacyJWT = await getLegacyJWT(); - - if (legacyJWT) { - const newJWT = await encode({ - token: legacyJWT, - secret: process.env.SECRET_PASSWORD, - salt: newCookieName, - }); - - // Set new session cookie - res.cookies.set(newCookieName, newJWT, { - httpOnly: true, - secure: isSecureCookie, - expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7), - sameSite: "lax", - path: "/", - }); - +function deleteLegacyCookie(res: NextResponse) { + const cookieStore = cookies(); + const oldCookie = cookieStore.get(oldCookieName); + if (oldCookie) { // Delete the old cookie - res.cookies.set(oldCookieName, "", { + res.cookies.set(oldCookieName, oldCookie.value, { httpOnly: true, secure: isSecureCookie, expires: new Date(0), @@ -77,3 +60,32 @@ export async function migrateLegacyJWT(res: NextResponse) { }); } } + +async function setNewSessionCookie(res: NextResponse, jwt: JWT) { + const newJWT = await encode({ + token: jwt, + secret: process.env.SECRET_PASSWORD, + salt: newCookieName, + }); + + // Set new session cookie + res.cookies.set(newCookieName, newJWT, { + httpOnly: true, + secure: isSecureCookie, + expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7), + sameSite: "lax", + path: "/", + }); +} + +/** + * Replace the old legacy cookie with the new one + */ +export async function migrateLegacyJWT(res: NextResponse) { + const legacyJWT = await getLegacyJWT(); + + if (legacyJWT) { + await setNewSessionCookie(res, legacyJWT); + deleteLegacyCookie(res); + } +}