Req.isAuthenticated变为false

时间:2017-10-20 08:13:19

标签: javascript node.js express passport.js

当我登录时,我已通过身份验证,但当我切换到另一个页面时,req.isAuthenticated返回false并且我在登录面板上。第二件事是当我登录时,我不断收到错误“无法在发送后设置标头”。这是我的代码:

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("/");
  });
};

1 个答案:

答案 0 :(得分:0)

登录页面当然会为您提供req.isAuthenticated true,因为您刚刚通过passport中间件进行了身份验证。

Passport将返回req.isAuthenticated true,直到您没有注销,并且当您点击/logout路径

时,它会设置req.isAuthenticated false

因此,维护用户状态必须使用会话来存储状态 应用

找到以下链接:https://www.npmjs.com/package/express-session

你得到了#34;在发送标题后不能设置标题&#34;。因为你要回复两次。一个在req.isAuthenticated()转为真之后,第二个就像你再次呈现map页面一样。

因此,您应该使用return res.end()

而不是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");
  }
}