Search code examples
javascriptnode.jsexpresspassport.js

Passport.js - Custom unauthorized message


Hello, I'm building the backend for my website when I reached the login part everything was ok until when I tried to put the false information to check what will happen. So when I tried it redirected me to another page and shows me "Unauthorized". So I tried fixing it and here is what I wrote.

app.post("/login", function (req, res) {
  // Other code...
  req.login(user, function (err) {
    if (err) {
      res.render("login", {
        alert: [{ field: "none", msg: "Username/password is incorrect!" }],
      });
    } else {
      passport.authenticate("local")(req, res, function () {
        if (res.statusCode == 401) {
          res.render("login", {
            alert: [{ field: "none", msg: "Username/password is incorrect!" }],
          });
        } else {
          res.redirect("/");
        }
      });
    }
  });
});

if anyone can help I will appreciate it! 🧡


Solution

  • I think you need to authenticate the user first and then render the page based on error or you can pass the error message to the express default error handler.

    app.post('/login', (req, res, next) => {
      passport.authenticate('local',
      (err, user, info) => {
        if (err) {
          return next(err);  // default express error handler - unauthorized 
        }
    
        if (!user) {
          return res.redirect('/signup'); // you can redirect user to signup page if needed
        }
    
        req.logIn(user, function(err) {
          if (err) {
            return next(err);
          }
          return res.redirect('/dashboard');
        });
    
      })(req, res, next);
    });