I have implemented authentication system in my MERN application using Passport.js.The application cannot seems to persist the logged in session. When I reload the page, I get logged out automatically. I am also not getting anything except "undefined" on Postman when I try to get "request.user". The session is also being stored in MongoDB "sessions" collection but still the logged in state is not persistant. This was not the issue previously and has been occurring now since I continued to work on the front-end today.
Here is the code:
index.js
const app = express();
dotenv.config();
let port = process.env.EXPRESS_PORT;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.use(cors());
app.use(cookieParser());
connectToDb();
app.use(session({
secret: 'Secret Key',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000*60*60*24*7
},
store: MongoStore.create({mongoUrl: "mongodb://127.0.0.1:27017/db_name"})
}))
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy({usernameField: 'email'}, authController.authenticateUser));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use('/auth', authRoutes);
authController.js
login: (req, res) => {
res.send(req.user);
},
authenticateUser: async (email, password, done) => {
const user = await UserModel.findOne({email}).exec();
if(!user) return done(null, false, {message: "User not found"});
bcrypt.compare(password, user.password, (error, match) => {
if(error) return done(error);
done(null, match);
})
return done(null, user);
},
authRoutes.js
router.post('/login', passport.authenticate('local'), authController.login);
I haven't changed anything in this related code yet as this was working perfectly fine before till now. I confirmed the order of the session initialization code and other necessary stuff like the implementation of the serialize and deserialize functions etc. Still the issue persists.