Search code examples
node.jslocalpassport.js

Use multiple local strategies in PassportJS


I'm trying to use multiple LOCAL strategies with PassportJS. I'm not trying to use local, facebook, and gmail, etc. I have two sets of users stored in separate objects and I want to use a local strategy to authenticate both. As it stands, I cannot use the same local strategy for both because they have different object properties which has me querying different objects. Is there any way to do this? OR any suggestions around this would be greatly appreciated.


Solution

  • I don't think it's possible, because as far as I can see you need some method of 'handing off' a request to the second strategy when the first one fails, and I don't believe that's possible.

    But you might be able to use one local strategy, and just try to authenticate the incoming data using both methods.

    As a simple example (using Mongoose as an example database):

    passport.use(new LocalStrategy(function(username, password, done) {
      Model1.findOne({ username : username }, function(err, user) {
        // first method succeeded?
        if (!err && user && passwordMatches(...)) {
          return done(null, user);
        }
        // no, try second method:
        Model2.findOne({ name : username }, function(err, user) {
          // second method succeeded?
          if (! err && user && passwordMatches(...)) {
            return done(null, user);
          }
          // fail! 
          done(new Error('invalid user or password'));
        });
      }); 
    }));
    

    For serialization/deserialization you might need to store some property in the user object that you pass to done to signify which model is required to deserialize the user.