I'm new to nodejs, I'm trying to develop a website with two users, a normal user, and a freelancer. When the user logs in res.locals.currentUser
is set as the req.user
by using the middleware app.use
(I'm using the same middle-ware for both types of user).
app.use(session({
secret: "Rusty is the best and cutest dog in the world",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
cookie: { maxAge: 180 * 60 *1000 }
}));
My app.use
code is
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next){
console.log("inside app use");
res.locals.currentUser = req.user;
res.locals.session = req.session;
console.log(req.user);
next();
});
When the user logsin req.user shows the right user but when the freelancer logsin req.user here inside app.use is undefined.
My passport configuration for the user is
passport.use('user', new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
My passport configuration for the admin is
passport.use('freelancer', new LocalStrategy(Freelancer.authenticate()));
passport.serializeUser(Freelancer.serializeUser());
passport.deserializeUser(Freelancer.deserializeUser());
The user login which works fine is
app.post("/user-login", passport.authenticate("user", {
failureRedirect: "/user-login"
}) ,function(req, res){
console.log("success");
if(req.session.oldUrl){
var oldUrl = req.session.oldUrl;
req.session.oldUrl = null;
res.redirect(oldUrl);
}else{
console.log("inside else");
res.redirect("/my-user-profile/"+req.user._id);
}
});
The problem is with the other type of user the Freelancer. My freelancer login route is
app.post("/freelancer-login", passport.authenticate("freelancer", {
failureRedirect: "/freelancer-login"
}) ,function(req, res){
res.locals.currentUser = req.user;
res.locals.session = req.session;
console.log("currentUser ------>");
console.log(res.locals.currentUser);
res.redirect("f-profile/"+req.user._id);
});
on my console.log(res.locals.currentUser); Im getting the correct information of the user and also the req.user shows the correct information inside this route but when Im trying to access currentUser in other ejs views , currentUser is undefined just for the freelancer The current user inside app.use also shows undefined (just for the freelancer).
I've been stuck at this for a long time and any kind of help would be a lifesaver
Thanks in advance :-)
app.use(function(req, res, next){ console.log("inside app use"); res.locals.currentUser = req.user; res.locals.session = req.session; console.log(req.user); next(); });
Is there any solution to why its not adding? – Sasuke Uchiha