Home > front end >  My auth app does not save data to session
My auth app does not save data to session

Time:05-11

Creating Auth application using express mongoose and passport js. after adding mail verification using nodemailer server sptoped adding user from req.user to res.locals.currentUser can be seen from middleware. before adding email verification it was functioning correctly.

    app.use(express.urlencoded({ extended: true }));
app.use(session(sessionObject));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use((req, res, next) => {
  res.locals.currentUser = req.user;
  res.locals.success = req.flash("success");
  res.locals.error = req.flash("error");
  next();
});
app.get("/", (req, res) => {
  console.log(res.locals);
  res.render("index");
});
app.get("/login", (req, res) => res.render("login"));
app.post(
  "/login",
  passport.authenticate("local", {
    failureFlash: true,
    failureRedirect: "/login",
  }),
  (req, res) => {
    req.flash("success", "Welcome Back!");
    res.redirect("/");
    console.log(req.user);
  }
);

source code

CodePudding user response:

Everything in req and res expires at the end of the request, only req.session is written to the session store (sessionObject) and from there carried over to the next request.

If you want to keep the current user in the session, write it to req.session.currentUser. Then you need passport.js and req.user only during the first request, where the session is established.

CodePudding user response:

the problem is than i was working in local enviroment and added to session options secured true so it was causing all the trouble thanks for everyone

  • Related