feat: implement token expiration handling in authentication flow and update session management for improved security
This commit is contained in:
21
lib/auth.ts
21
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user