Where to put PassportJs local strategy in an expre

2020-03-07 12:07发布

问题:

I have an expressjs application and I am trying to get passportjs set up for simple user authentication. My routes are stored in a separate file. I have a routes file (users.js) for all my user related routes. I also have a controller file called UserController that contains all the functions for user related stuff and deals with my database.

My question is, where should I declare the passport strategy so that it follows the MVC pattern?

Putting it in any other file besides the routes file doesn't work as it does not have the passport object.

回答1:

I put my passport file in a config folder. Here is an example of a passport.js file. This is for the local-login strategy.

module.exports = function(passport) {

    passport.serializeUser(function(user, done) {
      done(null, user.id);
    }); // if you are using sessions

    passport.deserializeUser(function(id, done) {
      User.findById(id, function(err, user) {
        done(err, user);
      });
    }); // if you are using sessions

    passport.use('local-login', new LocalStrategy({
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true
   },
   function(req, email, password, done) {
     // mongodb example - you have to query for user, 
     // check password, and return user if successful
     User.findOne({ 'local.email' : email },
     function(err, user) {
       if (err) return done(err);

       if (!user) return done(null, false);

       if (!user.validPassword(password) {
         return done(null, false);
       }

       else
         return done(null, user); // all good return user
     });
   });
};

then in app.js I do:

require('./config/passport.js')(passport);


app.use(passport.initialize())

var usersRoutes = require('./server/routes/usersRoutes')(app, express, passport);
app.use('/users', usersRoutes);

then in your routes file:

module.exports = function(app, express, passport) {
  var usersRouter = express.Router();

  return usersRouter;

};

now your passport functions are available in your route. I would search 'easy-node-authentication' for good examples on the web.