Edu
Edu

Reputation: 470

Avoid to use passport.serializeUser functions

is there any way to avoid the use of this functions into a node.js app?

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

passport.deserializeUser(function(user, done) {
  done(null, user);
});

Upvotes: 0

Views: 435

Answers (1)

sarveshseri
sarveshseri

Reputation: 13985

the serializeUser function is used by req.logIn function provided by passport.

req.login =
req.logIn = function(user, options, done) {
  if (typeof options == 'function') {
    done = options;
    options = {};
  }
  options = options || {};

  var property = 'user';
  if (this._passport && this._passport.instance) {
    property = this._passport.instance._userProperty || 'user';
  }
  var session = (options.session === undefined) ? true : options.session;

  this[property] = user;
  if (session) {
    if (!this._passport) { throw new Error('passport.initialize() middleware not in use'); }
    if (typeof done != 'function') { throw new Error('req#login requires a callback function'); }

    var self = this;
    this._passport.instance.serializeUser(user, this, function(err, obj) {
      if (err) { self[property] = null; return done(err); }
      self._passport.session.user = obj;
      done();
    });
  } else {
    done && done();
  }
};

This req.logIn function can be called to persist the serialized user in the session and thus for doing the login. This function is automatically called by passport.authenticate function, which calls it after getting the user according to the defined strategy,

Creating a passport strategy create a procedure for passport to find your user, it does not perform the login by itself. The isAuthenticated is false because the login is never happening.

So to create an auth route for your facebook authentication strategy, add something like this to your routes,

app.get('/auth/facebook', passport.authenticate('facebook', { state: 'SOME STATE' }));

Now this on going to this route passport will find the user using your facebook strategy and automatically perform the login for this user.

Assuming your facebook stragtegy has no error.. it should work just fine..

Now you can override either of the passport.logIn (Not recommended) or passport.authenticte (Not recommended) or you can give a custom callback to passport.authenticte as explained on this page - http://passportjs.org/guide/authenticate

Upvotes: 2

Related Questions