When I log in I'm authenticated but when I switch to another page req.isAuthenticated returns false and I'm on login panel. The second thing is when I log in I keep getting an error "can't set headers after they are sent". Here is my code:
const isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
return res.end();
} else {
return res.redirect("/login");
}
}
module.exports = (app, passport) => {
app.post("/login", (req, res, next) => {
passport.authenticate("local-login",
(err, user, info) => {
if(!user) {
res.render("index", { message: "Wrong password or login!" })
} else {
req.login(user, (error) => {
if (error) return next(error);
console.log("AUTH: ", req.isAuthenticated()) <--- RETURNS TRUE
return res.render("map", { name: user.name });
});
}
})(req, res, next);
});
app.get("/", (req, res) => {
return res.render("index"); // load the index file
})
app.get("/login", (req, res) => {
return res.render("index"); // load the index file
})
app.get("/map", isLoggedIn, (req, res) => {
return res.render("map");
});
app.get("/vehicles", isLoggedIn, (req, res) => {
return
});
app.get("/settings", isLoggedIn, (req, res) => {
res.render("settings");
});
app.get("/logout", (req, res) => {
req.logout();
res.redirect("/");
});
};
Login page will of course give you req.isAuthenticated
true
because you are just authenticated by passport
middleware.
Passport will return req.isAuthenticated
true
until you are not getting logged out and it will set req.isAuthenticated false when you hit /logout
route
So maintaining the state of user you have to use sessions for storing state of application.
find below link : https://www.npmjs.com/package/express-session
you are getting "can't set headers after they are sent". because you are returning response twice. one that is after req.isAuthenticated()
getting turn true and second is like you are again rendering a map
page.
so instead of return res.end()
you should have to use next()
const isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
req.session.isAuthenticated = true;
res.locals.isAuthenticated = true;
res.locals.user =req.user;
next(); //If you are authenticated, run the next
} else {
return res.redirect("/login");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.