request.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * Module dependencies.
  3. */
  4. //var http = require('http')
  5. // , req = http.IncomingMessage.prototype;
  6. var req = exports = module.exports = {};
  7. /**
  8. * Initiate a login session for `user`.
  9. *
  10. * Options:
  11. * - `session` Save login state in session, defaults to _true_
  12. *
  13. * Examples:
  14. *
  15. * req.logIn(user, { session: false });
  16. *
  17. * req.logIn(user, function(err) {
  18. * if (err) { throw err; }
  19. * // session saved
  20. * });
  21. *
  22. * @param {User} user
  23. * @param {Object} options
  24. * @param {Function} done
  25. * @api public
  26. */
  27. req.login =
  28. req.logIn = function(user, options, done) {
  29. if (typeof options == 'function') {
  30. done = options;
  31. options = {};
  32. }
  33. options = options || {};
  34. var property = 'user';
  35. if (this._passport && this._passport.instance) {
  36. property = this._passport.instance._userProperty || 'user';
  37. }
  38. var session = (options.session === undefined) ? true : options.session;
  39. this[property] = user;
  40. if (session) {
  41. if (!this._passport) { throw new Error('passport.initialize() middleware not in use'); }
  42. if (typeof done != 'function') { throw new Error('req#login requires a callback function'); }
  43. var self = this;
  44. this._passport.instance._sm.logIn(this, user, function(err) {
  45. if (err) { self[property] = null; return done(err); }
  46. done();
  47. });
  48. } else {
  49. done && done();
  50. }
  51. };
  52. /**
  53. * Terminate an existing login session.
  54. *
  55. * @api public
  56. */
  57. req.logout =
  58. req.logOut = function() {
  59. var property = 'user';
  60. if (this._passport && this._passport.instance) {
  61. property = this._passport.instance._userProperty || 'user';
  62. }
  63. this[property] = null;
  64. if (this._passport) {
  65. this._passport.instance._sm.logOut(this);
  66. }
  67. };
  68. /**
  69. * Test if request is authenticated.
  70. *
  71. * @return {Boolean}
  72. * @api public
  73. */
  74. req.isAuthenticated = function() {
  75. var property = 'user';
  76. if (this._passport && this._passport.instance) {
  77. property = this._passport.instance._userProperty || 'user';
  78. }
  79. return (this[property]) ? true : false;
  80. };
  81. /**
  82. * Test if request is unauthenticated.
  83. *
  84. * @return {Boolean}
  85. * @api public
  86. */
  87. req.isUnauthenticated = function() {
  88. return !this.isAuthenticated();
  89. };