Passport callback isn't called

I build an application using Passport lib using this tutorial (part of it).

Note, I don't need a registration, only login form.

One of the issues is that my LocalStrategy callback is never called. For storing I use mongo:

mongoose.connect(dbConfig.url, {
    useMongoClient: true
});

//dbConfig

module.exports = {
    'url' : 'mongodb://localhost/passport'
}

Login route looks like this:

module.exports = function(app, passport) {
    app.get('/login', function(req, res) {
        res.render('login', {
            message: req.flash('loginMessage')
        });
    });

    app.post('/login', passport.authenticate('login', {
        successRedirect: '/', // redirect to the secure profile section
        failureRedirect: '/login', // redirect back to the signup page if there is an error
        failureFlash: true // allow flash messages
    }));
}

Passport logic is:

module.exports = function(passport) {    
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    passport.use('login', new LocalStrategy({
        passReqToCallback: true 
    }, function(req, username, password, done) {
        console.log('start'); // never called

        User.findOne({
            'local.email': email
        }, function(err, user) {
            if (err) {
                return done(err);
            }

            if (!user) {
                return done(null, false, req.flash('loginMessage', 'No user found.'));
            }

            if (!user.validPassword(password)) {
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
            }

            return done(null, user);
        });
    }));
};

console.log('start'); is never called, although passport.authenticate('login' ...) is called.

What can be an issue?

javascriptpassport.js

Answers

answered 1 year ago Vladyslav Zavalykhatko #1

I finally fixed it and everything works. In case anyone face the same issues I'm posting here several problems and solutions.

The req.body was empty in my app.post, because I didn't add body parser. Fixed it with:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Username field was empty all the time because I named it as email and passport expected username. Fixed with:

new LocalStrategy({
        usernameField: 'email', // this parameter
        passReqToCallback: true
    }

comments powered by Disqus