2

I'm having problem with sending a flash if authentication fails. Except that everything is OK. When I'm copying example (https://github.com/jaredhanson/connect-flash) to my app flash messages are working fine...

Here is my code:

//routes
app.get('/login', function (req,res){
    res.render('login', {
        authMessage: req.flash('authMessage')
    });
});

app.post('/login', passport.authenticate('local', {
    failureRedirect: '/login',
    failureFlash: true
    }), function(req,res){
    res.send('ok');
});

//local strategy
passport.use(new LocalStrategy(
    function(username, password, authCheckDone) {
        UserDetails.findOne({username : username}).then(
            function(user){
                if (!user) {
                    console.log('bad username');
                    return authCheckDone(null, false, {authMessage: 'Wrong name'});
                }
                if (user.password !== password) {
                    console.log('bad password');
                    return authCheckDone(null, false, {authMessage: 'Wrong password'});
                }
                return authCheckDone(null, user);
            }),
            function(error){
                return authCheckDone(error);
        };
    }
));

//ejs
<% if (authMessage.length > 0) { %>
    <p>test</p>
    <%= authMessage %>
<% } %>

I've read somewhere this problem may be related with security and not using https, but if that would be the case example from github wouldn't work either...

nbro
  • 15,395
  • 32
  • 113
  • 196
Jarosław Rewers
  • 1,059
  • 3
  • 14
  • 23

1 Answers1

2

If I am not wrong, the callback you pass to LocalStrategy should have as first parameter the request object. So your function would look like this:

function(req, username, password, authCheckDone) {
    // your code

After that, according to an example that I have, you should return the result of authCheckDone in the following way:

return authCheckDone(null, false, req.flash('authMessage', "your message"));

But make sure you create the LocalStrategy object in the following way:

new LocalStrategy({
    passReqToCallback: true // don't forget this
}, function(req, username, password, authCheckDone) {
nbro
  • 15,395
  • 32
  • 113
  • 196