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 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<Session | null> {
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);
}
}