session.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Module dependencies.
  3. */
  4. var pause = require('pause')
  5. , util = require('util')
  6. , Strategy = require('passport-strategy');
  7. /**
  8. * `SessionStrategy` constructor.
  9. *
  10. * @api public
  11. */
  12. function SessionStrategy() {
  13. Strategy.call(this);
  14. this.name = 'session';
  15. }
  16. /**
  17. * Inherit from `Strategy`.
  18. */
  19. util.inherits(SessionStrategy, Strategy);
  20. /**
  21. * Authenticate request based on the current session state.
  22. *
  23. * The session authentication strategy uses the session to restore any login
  24. * state across requests. If a login session has been established, `req.user`
  25. * will be populated with the current user.
  26. *
  27. * This strategy is registered automatically by Passport.
  28. *
  29. * @param {Object} req
  30. * @param {Object} options
  31. * @api protected
  32. */
  33. SessionStrategy.prototype.authenticate = function(req, options) {
  34. if (!req._passport) { return this.error(new Error('passport.initialize() middleware not in use')); }
  35. options = options || {};
  36. var self = this
  37. , su = req._passport.session.user;
  38. if (su || su === 0) {
  39. // NOTE: Stream pausing is desirable in the case where later middleware is
  40. // listening for events emitted from request. For discussion on the
  41. // matter, refer to: https://github.com/jaredhanson/passport/pull/106
  42. var paused = options.pauseStream ? pause(req) : null;
  43. req._passport.instance.deserializeUser(su, req, function(err, user) {
  44. if (err) { return self.error(err); }
  45. if (!user) {
  46. delete req._passport.session.user;
  47. self.pass();
  48. if (paused) {
  49. paused.resume();
  50. }
  51. return;
  52. }
  53. var property = req._passport.instance._userProperty || 'user';
  54. req[property] = user;
  55. self.pass();
  56. if (paused) {
  57. paused.resume();
  58. }
  59. });
  60. } else {
  61. self.pass();
  62. }
  63. };
  64. /**
  65. * Expose `SessionStrategy`.
  66. */
  67. module.exports = SessionStrategy;