Last active
June 30, 2017 02:57
-
-
Save rojasmi1/c34ec82539d4b42c842ab0789ecbdcd1 to your computer and use it in GitHub Desktop.
Multiple local strategies with passport
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let User = require('./models/userModel') | |
passport.use(User.createStrategy()); | |
let Enterprise = require('./models/enterpriseModel') | |
let EnterpriseStrategy = require('passport-local').Strategy | |
passport.use('enterprise-local', new EnterpriseStrategy(Enterprise.authenticate())) | |
passport.serializeUser(function(user, done) { | |
let type | |
if (isUser(user)) { | |
type = 'user' | |
} else if (isEnterprise(user)) { | |
type = 'enterprise' | |
} | |
const key = { | |
id: user.id, | |
// With ES6 we don't need to put 'type: type' | |
type | |
} | |
done(null, key) | |
}); | |
passport.deserializeUser(function(key, done) { | |
// Check if user should be searched in the User model or | |
// in the Enterprise one | |
const Model = key.type === 'user' ? User : Enterprise | |
// Find the user, if found then pass it to the done() function | |
Model.findOne({ | |
_id: key.id | |
}, '-salt -password', function(err, user) { | |
done(err, user); | |
} | |
} | |
// Checks if the user is an instance of the User model | |
const isUser = user => user instanceof User | |
// Checks if the user is an instance of the Enterprise model | |
const isEnterprise = user => user instanceof Enterprise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment