1

I have a problem to send back error message back to fronted while logging in with passport.js.

Here's my route:

users.post('/login',
  passport.authenticate('local'),
  (req, res) => {
    res.sendStatus(201);
  },
);

And the strategy:

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
  },
  async (username, password, done) => {
    // let's assume we are checking here if there is a user in db

    if(user) {
      if(bcrypt.compareSync(password, user.password)) {
        return done(null, user);
      }
    } else {
        return done(null, false, { message: 'No user in db' });
    }
  }
));

This gives me 401 Anauthorized error in the browser. However I'd like to pass message ('No user in db') as well and maybe change status code.

Murakami
  • 3,474
  • 7
  • 35
  • 89

1 Answers1

-1

Try this, the first parameter in the callback is the error parameter

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
  },
  async (username, password, done) => {
    // let's assume we are checking here if there is a user in db

    if(user) {
      if(bcrypt.compareSync(password, user.password)) {
        return done(null, user);
      }
    } else {
        return done({ message: 'No user in db' }, false);
    }
  }
));
Abishek Aditya
  • 802
  • 4
  • 11