Question

Ok, I've been looking into this for a couple of days and I really don't know what the problem is. For some reason, the authentication fails (actually, Passportjs thinks it fails), but in my opinion everything works correctly. When I login, it invokes the failureRedirect-url. But when I print out the values of the req.user object, everything is correct.

Situation: I have a login form at /login where 2 fields are displayed, one for the e-mailaddress and one for the password.

This is the setup for Express:

var app = express();
app.configure(function () {
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({secret: 'Idioticlargesecretekeygoeshere.'}));
    app.use(express.static(path.join(__dirname, 'public')));

    // Initialize passport
    app.use(flash());
    app.use(passport.initialize());
    app.use(passport.session());

    app.use(app.router);
});

This is how I configure passport (added to app.js, before the initialization of express):

passport.serializeUser(function (user, fn) {
    fn(null, user.id);
});

passport.deserializeUser(function (userId, fn) {
    User.get(userId, function (err, user) {
        fn(err, user);
    });
});

passport.use(User.passwordStrategy);

This is the User.passwordStrategy-method:

User.passwordStrategy = new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
    },
    function (username, password, fn) {
        User.authenticate(username, password, function (err, user) {
            if(err) return fn(err);
            if(user) {
                fn(null, user);
            }

            fn(null, null);
        });
    }
);

This is the routing-line:

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

I've tested and debugged the authentication method and it works. If I try to login, I enter the serializeUser method and the id is filled in correctly. However, something fails along the line, because the login doesn't work. Can someone give me some guidance on this one? Because I have tried nearly everything I can think of. I don't see any differences between my code and the code that is posted on the passportjs.org site.

User data is stored in redis btw. Retrieving data is not a problem, as all the correct data is passed to the serialization-method. But for some reason, somewhere along the line, the correct login is not detected.

I've tried the example on the passportjs site, and that one runs correctly.

Was it helpful?

Solution

Your code is calling fn twice if user is trueish, so adding a return may solve it:

if (user) {
  return fn(null, user);
}
fn(null, null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top