feat: implement token expiration handling in authentication flow and update session management for improved security

This commit is contained in:
Julien Froidefond
2025-12-06 12:38:36 +01:00
parent b1a8f9cd60
commit ad8b936c7a
2 changed files with 19 additions and 4 deletions

View File

@@ -12,13 +12,13 @@ if (process.env.NODE_ENV === "development") {
"🔐 NextAuth secret:", "🔐 NextAuth secret:",
process.env.NEXTAUTH_SECRET process.env.NEXTAUTH_SECRET
? "✅ Loaded from .env.local" ? "✅ Loaded from .env.local"
: "⚠️ Using fallback", : "⚠️ Using fallback"
); );
} }
if (!process.env.NEXTAUTH_SECRET && process.env.NODE_ENV === "production") { if (!process.env.NEXTAUTH_SECRET && process.env.NODE_ENV === "production") {
throw new Error( 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( const isValid = await authService.verifyPassword(
credentials.password, credentials.password
); );
if (!isValid) { if (!isValid) {
return null; return null;
@@ -59,16 +59,29 @@ export const authOptions: NextAuthOptions = {
}, },
session: { session: {
strategy: "jwt", strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days maxAge: 24 * 60 * 60, // 24 hours
}, },
callbacks: { callbacks: {
async jwt({ token, user }) { async jwt({ token, user }) {
// On first sign in, set expiration time
if (user) { if (user) {
token.id = user.id; 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; return token;
}, },
async session({ session, 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) { if (session.user && token.id) {
session.user.id = token.id; session.user.id = token.id;
} }

View File

@@ -18,5 +18,7 @@ declare module "next-auth" {
declare module "next-auth/jwt" { declare module "next-auth/jwt" {
interface JWT { interface JWT {
id: string; id: string;
exp?: number;
error?: "TokenExpired";
} }
} }