jaredhanson / passport-local

Username and password authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-local/?utm_source=github&utm_medium=referral&utm_campaign=passport-local&utm_content=about
MIT License
2.74k stars 498 forks source link

No flash custom error message #141

Open nmnandakishore opened 8 years ago

nmnandakishore commented 8 years ago

I am trying to display custom error message. I am getting the error message while the login form is incomplete but not when the wrong credentials are provided.

Here are my routes

router.get('/login', (req, res, next) => {
if(req.isAuthenticated()){
    res.redirect('/');
} else {
    res.render('login', { title: 'Login',  layout:'external_forms_layout', error: req.flash('error') });
}
});

router.post('/login', passport.authenticate('local', 
                                            {failureRedirect: '/login', 
                                             successRedirect: '/',
                                             failureFlash: true}
));

Here is my strategy

passport.use(new LocalStrategy({
    passReqToCallback: true,
    usernameField: 'username',
    passwordField: 'password',
}, function(req, username, password, done) {
    User
        .query()
        .where('username', '=', username)
        .andWhere('password', '=', password)
        .then((user) => {
            return done(null, user[0]);
        }).catch((err) => {
            return done(null, false, {message : 'Incorrect username or password.'});

        });
  }

I also tried to return callback as below,

return done(null, false, req.flash('message', 'Incorrect username or password.'));

and also like this

return done(null, false, {error : 'Incorrect username or password.'});

But no luck.

thandonguocmo2020 commented 7 years ago

i also like this :(

wizzfizz94 commented 6 years ago

i also have this problem :((( setting req.flash attributes inside the LocalStrategy callback dont persist in the failure redirect routes. Even with sessions enabled.

nemmons commented 3 years ago

I ran into the same issue and it looks like you need to pass the message as a string, or as an object with a property of 'message', as the third parameter of the callback, like:

return done(null, false, "Login failed"); or return done(null, false, "Login failed");