initialize.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.configure(function() {
  25. * app.use(connect.cookieParser());
  26. * app.use(connect.session({ secret: 'keyboard cat' }));
  27. * app.use(passport.initialize());
  28. * app.use(passport.session());
  29. * });
  30. *
  31. * passport.serializeUser(function(user, done) {
  32. * done(null, user.id);
  33. * });
  34. *
  35. * passport.deserializeUser(function(id, done) {
  36. * User.findById(id, function (err, user) {
  37. * done(err, user);
  38. * });
  39. * });
  40. *
  41. * @return {Function}
  42. * @api public
  43. */
  44. module.exports = function initialize(passport) {
  45. return function initialize(req, res, next) {
  46. req._passport = {};
  47. req._passport.instance = passport;
  48. if (req.session && req.session[passport._key]) {
  49. // load data from existing session
  50. req._passport.session = req.session[passport._key];
  51. } else if (req.session) {
  52. // initialize new session
  53. req.session[passport._key] = {};
  54. req._passport.session = req.session[passport._key];
  55. } else {
  56. // no session is available
  57. req._passport.session = {};
  58. }
  59. next();
  60. };
  61. };