diff --git a/backend/config/passportConfig.js b/backend/config/passportConfig.js index 173ff8a9..ccd25c89 100644 --- a/backend/config/passportConfig.js +++ b/backend/config/passportConfig.js @@ -7,9 +7,9 @@ passport.use( { usernameField: "email" }, async (email, password, done) => { try { - const user = await User.findOne( {email} ).select("+password");; + const user = await User.findOne({ email }).select("+password"); if (!user) { - return done(null, false, { message: 'Email is invalid '}); + return done(null, false, { message: 'Email is invalid ' }); } const isMatch = await user.comparePassword(password); @@ -18,7 +18,7 @@ passport.use( } return done(null, { - id : user._id.toString(), + id: user._id.toString(), username: user.username, email: user.email }); @@ -38,10 +38,14 @@ passport.serializeUser((user, done) => { passport.deserializeUser(async (id, done) => { try { const user = await User.findById(id); + + // 🛡️ Safety check: If the user record no longer exists in MongoDB, exit safely + // This prevents the application from throwing an unhandled TypeError downstream if (!user) { - return done(null, false); + return done(null, false); // Gracefully invalidates the cookie and ends the request loop } - done(null,user); + + done(null, user); } catch (err) { done(err, null); } diff --git a/backend/server.js b/backend/server.js index 48d6ccfb..b73d5446 100644 --- a/backend/server.js +++ b/backend/server.js @@ -28,10 +28,16 @@ app.use(cors({ // Middleware app.use(bodyParser.json()); + app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, + cookie: { + maxAge: 24 * 60 * 60 * 1000, + secure: process.env.NODE_ENV === "production", + sameSite: process.env.NODE_ENV === "production" ? "none" : "lax" + } })); app.use(passport.initialize()); app.use(passport.session());