如何向用户显示Passport.js故障消息

发布于 2025-01-21 12:14:31 字数 1390 浏览 2 评论 0原文

我正在尝试设置本地策略并使用FailureMessages向用户显示身份验证错误,但我不确定正确的方法。

每次发生故障时,会话 每次发生故障,但会话永远不会清除。这是结果:

“在此处输入图像描述”

显然,最后一条消息是最新消息,但是我如何知道这些消息是来自当前失败还是过去发生的消息,因为我只想显示错误消息如果是当前故障。

auth.js

  passport.use(new LocalStrategy(
    function(username, password, done) {      
      myDatabase.findOne({ username: username }, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Incorrect username or password.' }); }
        if (!bcrypt.compareSync(password, user.password)) { 
          return done(null, false, { message: 'Incorrect username or password.' }); 
        }
        return done(null, user);
      });
    }
  ));

routes.js

  app.route('/login').post(passport.authenticate('local', { failureRedirect: '/', failureMessage: true }), 
    (req, res) => {
      res.redirect('/profile');
    });

server.js

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  cookie: { secure: false },
  key: 'express.sid',
  store: store
}));

app.use(passport.initialize());
app.use(passport.session());

I'm trying to setup a Local Strategy and use failureMessages display authentication errors to the user but I'm unsure the correct way to do this.

The failureMessages are added to the req.session.messages each time a failure occurs but the session.messages are never cleared. Here is the result:

enter image description here

Obviously, the last message is the most recent, but how do I know if the messages are from a current failure or a one that occurred in the past because I only want to display an error message if it is a current failure.

auth.js

  passport.use(new LocalStrategy(
    function(username, password, done) {      
      myDatabase.findOne({ username: username }, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Incorrect username or password.' }); }
        if (!bcrypt.compareSync(password, user.password)) { 
          return done(null, false, { message: 'Incorrect username or password.' }); 
        }
        return done(null, user);
      });
    }
  ));

routes.js

  app.route('/login').post(passport.authenticate('local', { failureRedirect: '/', failureMessage: true }), 
    (req, res) => {
      res.redirect('/profile');
    });

server.js

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  cookie: { secure: false },
  key: 'express.sid',
  store: store
}));

app.use(passport.initialize());
app.use(passport.session());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

残疾 2025-01-28 12:14:31

我仍然是新手表达的新手,但是在尝试了许多不同的方式之后,当您想处理失败登录并想要发送错误消息或仅发送您的自定义消息并将其渲染时,我提出了此解决方案。您的登录页面(例如,使用EJS时):

app.post("/login", (req, res) => {
  passport.authenticate("local",
      (err, user, options) => {
        if (user) {
          // If the user exists log him in:
          req.login(user, (error)=>{
            if (error) {
              res.send(error);
            } else {
              console.log("Successfully authenticated");
              // HANDLE SUCCESSFUL LOGIN 
              // e.g. res.redirect("/home")
            };
          });
        } else {
          console.log(options.message); // Prints the reason of the failure
          // HANDLE FAILURE LOGGING IN 
          // e.g. res.redirect("/login"))
          // or
          // res.render("/login", { message: options.message || "custom message" })
        };
  })(req, res)
});

I'm still new to express but after trying many different ways, I came out with this solution when you want to be able to handle the failure logging in and want to send the error message generated or just send your custom message and render it in your login page (when using EJS for example):

app.post("/login", (req, res) => {
  passport.authenticate("local",
      (err, user, options) => {
        if (user) {
          // If the user exists log him in:
          req.login(user, (error)=>{
            if (error) {
              res.send(error);
            } else {
              console.log("Successfully authenticated");
              // HANDLE SUCCESSFUL LOGIN 
              // e.g. res.redirect("/home")
            };
          });
        } else {
          console.log(options.message); // Prints the reason of the failure
          // HANDLE FAILURE LOGGING IN 
          // e.g. res.redirect("/login"))
          // or
          // res.render("/login", { message: options.message || "custom message" })
        };
  })(req, res)
});
独闯女儿国 2025-01-28 12:14:31

我能够通过设置passreqtocallback选项来清理req.session.messages 。这样,我们知道req.session.messages中包含的任何消息都是新的失败。

  passport.use(new LocalStrategy({ passReqToCallback: true },
    function(req, username, password, done) {      
      myDatabase.findOne({ username: username }, function(err, user) {
        if (err) { return done(err); }
        if (!user) { 
          req.session.messages = [];
          return done(null, false, { message: 'Incorrect username or password.' }); }
        if (!bcrypt.compareSync(password, user.password)) { 
          return done(null, false, { message: 'Incorrect username or password.' }); 
        }
        return done(null, user);
      });
    }
  ));

I was able to clear the req.session.messages before sending a new failureMessage by setting the passReqToCallback option. This way we know that any message contained in req.session.messages is a new failure.

  passport.use(new LocalStrategy({ passReqToCallback: true },
    function(req, username, password, done) {      
      myDatabase.findOne({ username: username }, function(err, user) {
        if (err) { return done(err); }
        if (!user) { 
          req.session.messages = [];
          return done(null, false, { message: 'Incorrect username or password.' }); }
        if (!bcrypt.compareSync(password, user.password)) { 
          return done(null, false, { message: 'Incorrect username or password.' }); 
        }
        return done(null, user);
      });
    }
  ));
蓝眼泪 2025-01-28 12:14:31

在您的/登录请求中,您可以重新分配req.session.messages在发送响应后清除错误:

router.get('/login', async (req, res) => {
    res.render('login', { title: 'Login', errors: req.session.messages })
    req.session.messages = undefined
    }

In the GET request for your /login route you can re-assign req.session.messages to clear the error after the response has been sent:

router.get('/login', async (req, res) => {
    res.render('login', { title: 'Login', errors: req.session.messages })
    req.session.messages = undefined
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文