initialize.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Passport initialization.
  3. *
  4. * Intializes Passport for incoming requests, allowing authentication strategies
  5. * to be applied.
  6. *
  7. * If sessions are being utilized, applications must set up Passport with
  8. * functions to serialize a user into and out of a session. For example, a
  9. * common pattern is to serialize just the user ID into the session (due to the
  10. * fact that it is desirable to store the minimum amount of data in a session).
  11. * When a subsequent request arrives for the session, the full User object can
  12. * be loaded from the database by ID.
  13. *
  14. * Note that additional middleware is required to persist login state, so we
  15. * must use the `connect.session()` middleware _before_ `passport.initialize()`.
  16. *
  17. * If sessions are being used, this middleware must be in use by the
  18. * Connect/Express application for Passport to operate. If the application is
  19. * entirely stateless (not using sessions), this middleware is not necessary,
  20. * but its use will not have any adverse impact.
  21. *
  22. * Examples:
  23. *
  24. * app.use(connect.cookieParser());
  25. * app.use(connect.session({ secret: 'keyboard cat' }));
  26. * app.use(passport.initialize());
  27. * app.use(passport.session());
  28. *
  29. * passport.serializeUser(function(user, done) {
  30. * done(null, user.id);
  31. * });
  32. *
  33. * passport.deserializeUser(function(id, done) {
  34. * User.findById(id, function (err, user) {
  35. * done(err, user);
  36. * });
  37. * });
  38. *
  39. * @return {Function}
  40. * @api public
  41. */
  42. module.exports = function initialize(passport) {
  43. return function initialize(req, res, next) {
  44. req._passport = {};
  45. req._passport.instance = passport;
  46. if (req.session && req.session[passport._key]) {
  47. // load data from existing session
  48. req._passport.session = req.session[passport._key];
  49. }
  50. next();
  51. };
  52. };