Alon
Alon

Reputation: 377

passportjs failed to authenticate express session

I'm using passportjs to authenticate my express app. What I did is very similar to the tutorial code, but authenticating session always messes me up.

In my main workflow I authenticate user using local strategy

passport.authenticate('local', function (err, user, info) {
    if (err) {
      req.flash('error', { msg: err.message });
      return res.redirect('back');
    }

    if (!user) {
      // punish abuser...
      })
      .catch( function (err) {
        req.flash('error', { msg: err.message });
        return res.redirect('back');
      });
    } else {
      // Log user in
      debug('Info: ' + 'Logging in'.green.bold);
      req.logIn(user, function (err) {
        if (err) {
          debug('Info: ' + 'Error occured '.red.bold);
          req.flash('error', { msg: err.message });
          res.redirect('back');
        }
        // req.session.passport.user = user.id;  // <-- even tried hack, didn't work
        // Send user on their merry way
        res.redirect('/homepage');
      });
    }
  })

Then for all req to /homepage I force them to verify if user is authenticated

  app.all('/api*', passportConf.isAuthenticated);

where isAuthenticated() is defined as

exports.isAuthenticated = function (req, res, next) {
  // Is the user authenticated?
  if (req.isAuthenticated()) {
    debug('Info: ' + '----authentication verified');
    return next();
  } else {
    debug('Info: ' + '----authentication verification failed');
    // flash error message etc...
    return res.redirect('/login');
  }
};

The result shows:

Info: --->> Password Matched! <<--- +0ms
Info: Logging in +0ms
Info: serializing user +0ms
...
POST /login 302 295.015 ms - 64
...
Executing (default): UPDATE "Sessions" SET "data"='{"cookie":{"//cookie"},"passport":{"user":37}}'
...
Info: ----authentication verification failed +0ms
....
GET /api 302 19.094 ms - 68

Executing (default): UPDATE "Sessions" SET "data"='{"cookie":{"//cookie"},"passport":{}, "attemptedURL":"/api"}
...
Info: de-serializing user +20ms
...
Executing (default): SELECT "//fields" FROM "Users" AS "User" WHERE "User"."id" = 37 LIMIT 1;
Error: 500 [object SequelizeInstance:User] +5ms

The request certainly passes the password check and makes all the way until right before redirect and dies after being redirected.

There are 3 potential causes that I observed:

Stuck in this for many nights... any help into this is greatly appreciated...

Upvotes: 1

Views: 333

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28778

500 [object SequelizeInstance:User] seems to indicate that you are passing a sequelize instance to something somewhere which thinks it is an error. Perhaps you are calling a callback that expects err, user with just user:

fn(user)
// Where it should have been 
fn(null, user)

Upvotes: 1

Related Questions