From ad8b936c7af6cbfd05e710d9e31ce61e76651aa0 Mon Sep 17 00:00:00 2001 From: Julien Froidefond Date: Sat, 6 Dec 2025 12:38:36 +0100 Subject: [PATCH] feat: implement token expiration handling in authentication flow and update session management for improved security --- lib/auth.ts | 21 +++++++++++++++++---- types/next-auth.d.ts | 2 ++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/auth.ts b/lib/auth.ts index 176a369..845a556 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -12,13 +12,13 @@ if (process.env.NODE_ENV === "development") { "🔐 NextAuth secret:", process.env.NEXTAUTH_SECRET ? "✅ Loaded from .env.local" - : "⚠️ Using fallback", + : "⚠️ Using fallback" ); } if (!process.env.NEXTAUTH_SECRET && process.env.NODE_ENV === "production") { throw new Error( - "NEXTAUTH_SECRET is required in production. Please set it in your environment variables.", + "NEXTAUTH_SECRET is required in production. Please set it in your environment variables." ); } @@ -36,7 +36,7 @@ export const authOptions: NextAuthOptions = { } const isValid = await authService.verifyPassword( - credentials.password, + credentials.password ); if (!isValid) { return null; @@ -59,16 +59,29 @@ export const authOptions: NextAuthOptions = { }, session: { strategy: "jwt", - maxAge: 30 * 24 * 60 * 60, // 30 days + maxAge: 24 * 60 * 60, // 24 hours }, callbacks: { async jwt({ token, user }) { + // On first sign in, set expiration time if (user) { token.id = user.id; + token.exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours from now } + + // Check if token has expired + if (token.exp && Date.now() >= token.exp * 1000) { + return { ...token, error: "TokenExpired" }; + } + return token; }, async session({ session, token }) { + // If token is expired, return null session + if (token.error === "TokenExpired") { + return null as unknown as typeof session; + } + if (session.user && token.id) { session.user.id = token.id; } diff --git a/types/next-auth.d.ts b/types/next-auth.d.ts index 056e57e..7089626 100644 --- a/types/next-auth.d.ts +++ b/types/next-auth.d.ts @@ -18,5 +18,7 @@ declare module "next-auth" { declare module "next-auth/jwt" { interface JWT { id: string; + exp?: number; + error?: "TokenExpired"; } }