session.js 2.0 KB

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