NodeJS Passport NodeJS Passport mongoose mongoose

NodeJS Passport


This is what I do. Please comment if you need more help tailoring it to your code.

First Step

Put your passport code in a separate file. e.g. pass.js. (I see you have already done that) Then, in that file, put all the code inside this:

module.exports = function(passport, LocalStrategy){};

Remember to add to the function input anything else that you are using. In your case, besides passport and LocalStrategy, you will probably need to add mongoDbConnection as an input too.

Second Step

In your app.js, include this line. Just before "app.listen" if possible to ensure that everything has been properly defined/declared/included.

require('./pass.js')(passport, LocalStrategy);

Explanation

The "wrapper" in step one defines the chunk of code you will be including into your app. The "require" in step two is the code that actually includes it. You are basically defining the entire "pass.js" file as a function and passing it the tools it needs to carry out the code (passport, LocalStrategy etc)

In your case, you will probably need to modify my code to:

module.exports = function(passport, LocalStrategy, mongoDbConnection){};require('./pass.js')(passport, LocalStrategy, mongoDbConnection);

This should works. I googled about this a while ago and this appears to be the "correct" way to break up your app.js (I say this with great trepidation though :) ). Feel free to comment if you need anymore help.


This github repo also has a good example of this.

https://github.com/madhums/nodejs-express-mongoose-demo

The server.js file would be your app.js. And the /config/passport.js is the included passport setup.


For this I'll suggest to do this In app.js

 require('./mypassport')(app);

And mypassport.js

var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, MongoDBConnection = require('./database/DatabaseConnector').MongoDBConnection;  module.exports = function(app){    passport.serializeUser(function(user, done) {     done(null, user.id);   });  passport.deserializeUser(function(id, done) {   mongoDbConnection.findUserById(id, function(err, user){    done(err, user);  });});passport.use(new LocalStrategy(function(username, password, done) {    process.nextTick(function () {        mongoDbConnection.findUser(username, function(err, user) {            if (err) {                return done(err);            }            if (!user) {                return done(null, false, { message: 'Unknown user ' + username });            }            if (user.password != password) {                return done(null, false, { message: 'Invalid password' });            }              return done(null, user);        });      });} ));}