🐛 Handle expired jwt

This commit is contained in:
Luke Vella 2025-03-10 12:10:35 +00:00
parent 701875a158
commit a13418306e
No known key found for this signature in database
GPG key ID: 469CAD687F0D784C
4 changed files with 27 additions and 15 deletions

View file

@ -5,6 +5,7 @@ import NextAuth from "next-auth";
import { nextAuthConfig } from "@/next-auth.config";
import {
deleteLegacyCookie,
getLegacySession,
migrateLegacyJWT,
} from "../legacy/next-auth-cookie-migration";
@ -24,6 +25,7 @@ export const withAuth = (
}
let isLegacySession = false;
let isExpiredLegacySession = false;
if (!session) {
try {
@ -32,7 +34,7 @@ export const withAuth = (
isLegacySession = true;
}
} catch (e) {
console.error(e);
isExpiredLegacySession = true;
}
}
@ -54,6 +56,7 @@ export const withAuth = (
const middlewareRes = await middleware(request);
if (isLegacySession) {
console.warn("Found legacy session, migrating…");
try {
await migrateLegacyJWT(middlewareRes);
} catch (e) {
@ -61,6 +64,11 @@ export const withAuth = (
}
}
if (isExpiredLegacySession) {
console.warn("Found expired legacy session, deleting…");
deleteLegacyCookie(middlewareRes);
}
return middlewareRes;
};
};

View file

@ -9,15 +9,11 @@ export async function decodeLegacyJWT(token: string): Promise<JWT | null> {
process.env.SECRET_PASSWORD,
"",
);
try {
const { payload } = await jwtDecrypt(token, encryptionSecret, {
clockTolerance: 15,
});
return payload;
} catch (e) {
console.error(e);
return null;
}
const { payload } = await jwtDecrypt(token, encryptionSecret, {
clockTolerance: 15,
});
return payload;
}
async function getDerivedEncryptionKey(

View file

@ -46,7 +46,7 @@ async function getLegacyJWT() {
return null;
}
function deleteLegacyCookie(res: NextResponse) {
export function deleteLegacyCookie(res: NextResponse) {
const cookieStore = cookies();
const oldCookie = cookieStore.get(oldCookieName);
if (oldCookie) {

View file

@ -195,12 +195,20 @@ const {
});
const auth = cache(async () => {
const session = await originalAuth();
if (session) {
return session;
try {
const session = await originalAuth();
if (session) {
return session;
}
} catch (e) {
console.error("FAILED TO GET SESSION");
}
return getLegacySession();
try {
return await getLegacySession();
} catch (e) {
console.error("FAILED TO GET LEGACY SESSION");
}
});
const requireUser = async () => {