This commit is contained in:
Luke Vella 2025-02-13 10:53:39 +07:00
parent 1d4cd748c7
commit bd6c803a4b
No known key found for this signature in database
GPG key ID: 469CAD687F0D784C

View file

@ -2,6 +2,7 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import type { NextResponse } from "next/server"; import type { NextResponse } from "next/server";
import type { Session } from "next-auth"; import type { Session } from "next-auth";
import type { JWT } from "next-auth/jwt";
import { encode } from "next-auth/jwt"; import { encode } from "next-auth/jwt";
import { decodeLegacyJWT } from "./helpers/jwt"; import { decodeLegacyJWT } from "./helpers/jwt";
@ -16,7 +17,7 @@ const newCookieName = prefix + "authjs.session-token";
export async function getLegacySession(): Promise<Session | null> { export async function getLegacySession(): Promise<Session | null> {
const cookieStore = cookies(); const cookieStore = cookies();
const legacySessionCookie = cookieStore.get(oldCookieName); const legacySessionCookie = cookieStore.get(oldCookieName);
if (legacySessionCookie) { if (legacySessionCookie && legacySessionCookie.value) {
const decodedCookie = await decodeLegacyJWT(legacySessionCookie.value); const decodedCookie = await decodeLegacyJWT(legacySessionCookie.value);
if (decodedCookie?.sub) { if (decodedCookie?.sub) {
@ -45,15 +46,24 @@ async function getLegacyJWT() {
return null; return null;
} }
/** function deleteLegacyCookie(res: NextResponse) {
* Replace the old legacy cookie with the new one const cookieStore = cookies();
*/ const oldCookie = cookieStore.get(oldCookieName);
export async function migrateLegacyJWT(res: NextResponse) { if (oldCookie) {
const legacyJWT = await getLegacyJWT(); // Delete the old cookie
res.cookies.set(oldCookieName, oldCookie.value, {
httpOnly: true,
secure: isSecureCookie,
expires: new Date(0),
sameSite: "lax",
path: "/",
});
}
}
if (legacyJWT) { async function setNewSessionCookie(res: NextResponse, jwt: JWT) {
const newJWT = await encode({ const newJWT = await encode({
token: legacyJWT, token: jwt,
secret: process.env.SECRET_PASSWORD, secret: process.env.SECRET_PASSWORD,
salt: newCookieName, salt: newCookieName,
}); });
@ -66,14 +76,16 @@ export async function migrateLegacyJWT(res: NextResponse) {
sameSite: "lax", sameSite: "lax",
path: "/", path: "/",
}); });
}
// Delete the old cookie /**
res.cookies.set(oldCookieName, "", { * Replace the old legacy cookie with the new one
httpOnly: true, */
secure: isSecureCookie, export async function migrateLegacyJWT(res: NextResponse) {
expires: new Date(0), const legacyJWT = await getLegacyJWT();
sameSite: "lax",
path: "/", if (legacyJWT) {
}); await setNewSessionCookie(res, legacyJWT);
deleteLegacyCookie(res);
} }
} }