authenticator.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /**
  2. * Module dependencies.
  3. */
  4. var SessionStrategy = require('./strategies/session')
  5. , SessionManager = require('./sessionmanager');
  6. /**
  7. * `Authenticator` constructor.
  8. *
  9. * @api public
  10. */
  11. function Authenticator() {
  12. this._key = 'passport';
  13. this._strategies = {};
  14. this._serializers = [];
  15. this._deserializers = [];
  16. this._infoTransformers = [];
  17. this._framework = null;
  18. this._userProperty = 'user';
  19. this.init();
  20. }
  21. /**
  22. * Initialize authenticator.
  23. *
  24. * @api protected
  25. */
  26. Authenticator.prototype.init = function() {
  27. this.framework(require('./framework/connect')());
  28. this.use(new SessionStrategy(this.deserializeUser.bind(this)));
  29. this._sm = new SessionManager({ key: this._key }, this.serializeUser.bind(this));
  30. };
  31. /**
  32. * Utilize the given `strategy` with optional `name`, overridding the strategy's
  33. * default name.
  34. *
  35. * Examples:
  36. *
  37. * passport.use(new TwitterStrategy(...));
  38. *
  39. * passport.use('api', new http.BasicStrategy(...));
  40. *
  41. * @param {String|Strategy} name
  42. * @param {Strategy} strategy
  43. * @return {Authenticator} for chaining
  44. * @api public
  45. */
  46. Authenticator.prototype.use = function(name, strategy) {
  47. if (!strategy) {
  48. strategy = name;
  49. name = strategy.name;
  50. }
  51. if (!name) { throw new Error('Authentication strategies must have a name'); }
  52. this._strategies[name] = strategy;
  53. return this;
  54. };
  55. /**
  56. * Un-utilize the `strategy` with given `name`.
  57. *
  58. * In typical applications, the necessary authentication strategies are static,
  59. * configured once and always available. As such, there is often no need to
  60. * invoke this function.
  61. *
  62. * However, in certain situations, applications may need dynamically configure
  63. * and de-configure authentication strategies. The `use()`/`unuse()`
  64. * combination satisfies these scenarios.
  65. *
  66. * Examples:
  67. *
  68. * passport.unuse('legacy-api');
  69. *
  70. * @param {String} name
  71. * @return {Authenticator} for chaining
  72. * @api public
  73. */
  74. Authenticator.prototype.unuse = function(name) {
  75. delete this._strategies[name];
  76. return this;
  77. };
  78. /**
  79. * Setup Passport to be used under framework.
  80. *
  81. * By default, Passport exposes middleware that operate using Connect-style
  82. * middleware using a `fn(req, res, next)` signature. Other popular frameworks
  83. * have different expectations, and this function allows Passport to be adapted
  84. * to operate within such environments.
  85. *
  86. * If you are using a Connect-compatible framework, including Express, there is
  87. * no need to invoke this function.
  88. *
  89. * Examples:
  90. *
  91. * passport.framework(require('hapi-passport')());
  92. *
  93. * @param {Object} name
  94. * @return {Authenticator} for chaining
  95. * @api public
  96. */
  97. Authenticator.prototype.framework = function(fw) {
  98. this._framework = fw;
  99. return this;
  100. };
  101. /**
  102. * Passport's primary initialization middleware.
  103. *
  104. * This middleware must be in use by the Connect/Express application for
  105. * Passport to operate.
  106. *
  107. * Options:
  108. * - `userProperty` Property to set on `req` upon login, defaults to _user_
  109. *
  110. * Examples:
  111. *
  112. * app.use(passport.initialize());
  113. *
  114. * app.use(passport.initialize({ userProperty: 'currentUser' }));
  115. *
  116. * @param {Object} options
  117. * @return {Function} middleware
  118. * @api public
  119. */
  120. Authenticator.prototype.initialize = function(options) {
  121. options = options || {};
  122. this._userProperty = options.userProperty || 'user';
  123. return this._framework.initialize(this, options);
  124. };
  125. /**
  126. * Middleware that will authenticate a request using the given `strategy` name,
  127. * with optional `options` and `callback`.
  128. *
  129. * Examples:
  130. *
  131. * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })(req, res);
  132. *
  133. * passport.authenticate('local', function(err, user) {
  134. * if (!user) { return res.redirect('/login'); }
  135. * res.end('Authenticated!');
  136. * })(req, res);
  137. *
  138. * passport.authenticate('basic', { session: false })(req, res);
  139. *
  140. * app.get('/auth/twitter', passport.authenticate('twitter'), function(req, res) {
  141. * // request will be redirected to Twitter
  142. * });
  143. * app.get('/auth/twitter/callback', passport.authenticate('twitter'), function(req, res) {
  144. * res.json(req.user);
  145. * });
  146. *
  147. * @param {String} strategy
  148. * @param {Object} options
  149. * @param {Function} callback
  150. * @return {Function} middleware
  151. * @api public
  152. */
  153. Authenticator.prototype.authenticate = function(strategy, options, callback) {
  154. return this._framework.authenticate(this, strategy, options, callback);
  155. };
  156. /**
  157. * Middleware that will authorize a third-party account using the given
  158. * `strategy` name, with optional `options`.
  159. *
  160. * If authorization is successful, the result provided by the strategy's verify
  161. * callback will be assigned to `req.account`. The existing login session and
  162. * `req.user` will be unaffected.
  163. *
  164. * This function is particularly useful when connecting third-party accounts
  165. * to the local account of a user that is currently authenticated.
  166. *
  167. * Examples:
  168. *
  169. * passport.authorize('twitter-authz', { failureRedirect: '/account' });
  170. *
  171. * @param {String} strategy
  172. * @param {Object} options
  173. * @return {Function} middleware
  174. * @api public
  175. */
  176. Authenticator.prototype.authorize = function(strategy, options, callback) {
  177. options = options || {};
  178. options.assignProperty = 'account';
  179. var fn = this._framework.authorize || this._framework.authenticate;
  180. return fn(this, strategy, options, callback);
  181. };
  182. /**
  183. * Middleware that will restore login state from a session.
  184. *
  185. * Web applications typically use sessions to maintain login state between
  186. * requests. For example, a user will authenticate by entering credentials into
  187. * a form which is submitted to the server. If the credentials are valid, a
  188. * login session is established by setting a cookie containing a session
  189. * identifier in the user's web browser. The web browser will send this cookie
  190. * in subsequent requests to the server, allowing a session to be maintained.
  191. *
  192. * If sessions are being utilized, and a login session has been established,
  193. * this middleware will populate `req.user` with the current user.
  194. *
  195. * Note that sessions are not strictly required for Passport to operate.
  196. * However, as a general rule, most web applications will make use of sessions.
  197. * An exception to this rule would be an API server, which expects each HTTP
  198. * request to provide credentials in an Authorization header.
  199. *
  200. * Examples:
  201. *
  202. * app.use(connect.cookieParser());
  203. * app.use(connect.session({ secret: 'keyboard cat' }));
  204. * app.use(passport.initialize());
  205. * app.use(passport.session());
  206. *
  207. * Options:
  208. * - `pauseStream` Pause the request stream before deserializing the user
  209. * object from the session. Defaults to _false_. Should
  210. * be set to true in cases where middleware consuming the
  211. * request body is configured after passport and the
  212. * deserializeUser method is asynchronous.
  213. *
  214. * @param {Object} options
  215. * @return {Function} middleware
  216. * @api public
  217. */
  218. Authenticator.prototype.session = function(options) {
  219. return this.authenticate('session', options);
  220. };
  221. // TODO: Make session manager pluggable
  222. /*
  223. Authenticator.prototype.sessionManager = function(mgr) {
  224. this._sm = mgr;
  225. return this;
  226. }
  227. */
  228. /**
  229. * Registers a function used to serialize user objects into the session.
  230. *
  231. * Examples:
  232. *
  233. * passport.serializeUser(function(user, done) {
  234. * done(null, user.id);
  235. * });
  236. *
  237. * @api public
  238. */
  239. Authenticator.prototype.serializeUser = function(fn, req, done) {
  240. if (typeof fn === 'function') {
  241. return this._serializers.push(fn);
  242. }
  243. // private implementation that traverses the chain of serializers, attempting
  244. // to serialize a user
  245. var user = fn;
  246. // For backwards compatibility
  247. if (typeof req === 'function') {
  248. done = req;
  249. req = undefined;
  250. }
  251. var stack = this._serializers;
  252. (function pass(i, err, obj) {
  253. // serializers use 'pass' as an error to skip processing
  254. if ('pass' === err) {
  255. err = undefined;
  256. }
  257. // an error or serialized object was obtained, done
  258. if (err || obj || obj === 0) { return done(err, obj); }
  259. var layer = stack[i];
  260. if (!layer) {
  261. return done(new Error('Failed to serialize user into session'));
  262. }
  263. function serialized(e, o) {
  264. pass(i + 1, e, o);
  265. }
  266. try {
  267. var arity = layer.length;
  268. if (arity == 3) {
  269. layer(req, user, serialized);
  270. } else {
  271. layer(user, serialized);
  272. }
  273. } catch(e) {
  274. return done(e);
  275. }
  276. })(0);
  277. };
  278. /**
  279. * Registers a function used to deserialize user objects out of the session.
  280. *
  281. * Examples:
  282. *
  283. * passport.deserializeUser(function(id, done) {
  284. * User.findById(id, function (err, user) {
  285. * done(err, user);
  286. * });
  287. * });
  288. *
  289. * @api public
  290. */
  291. Authenticator.prototype.deserializeUser = function(fn, req, done) {
  292. if (typeof fn === 'function') {
  293. return this._deserializers.push(fn);
  294. }
  295. // private implementation that traverses the chain of deserializers,
  296. // attempting to deserialize a user
  297. var obj = fn;
  298. // For backwards compatibility
  299. if (typeof req === 'function') {
  300. done = req;
  301. req = undefined;
  302. }
  303. var stack = this._deserializers;
  304. (function pass(i, err, user) {
  305. // deserializers use 'pass' as an error to skip processing
  306. if ('pass' === err) {
  307. err = undefined;
  308. }
  309. // an error or deserialized user was obtained, done
  310. if (err || user) { return done(err, user); }
  311. // a valid user existed when establishing the session, but that user has
  312. // since been removed
  313. if (user === null || user === false) { return done(null, false); }
  314. var layer = stack[i];
  315. if (!layer) {
  316. return done(new Error('Failed to deserialize user out of session'));
  317. }
  318. function deserialized(e, u) {
  319. pass(i + 1, e, u);
  320. }
  321. try {
  322. var arity = layer.length;
  323. if (arity == 3) {
  324. layer(req, obj, deserialized);
  325. } else {
  326. layer(obj, deserialized);
  327. }
  328. } catch(e) {
  329. return done(e);
  330. }
  331. })(0);
  332. };
  333. /**
  334. * Registers a function used to transform auth info.
  335. *
  336. * In some circumstances authorization details are contained in authentication
  337. * credentials or loaded as part of verification.
  338. *
  339. * For example, when using bearer tokens for API authentication, the tokens may
  340. * encode (either directly or indirectly in a database), details such as scope
  341. * of access or the client to which the token was issued.
  342. *
  343. * Such authorization details should be enforced separately from authentication.
  344. * Because Passport deals only with the latter, this is the responsiblity of
  345. * middleware or routes further along the chain. However, it is not optimal to
  346. * decode the same data or execute the same database query later. To avoid
  347. * this, Passport accepts optional `info` along with the authenticated `user`
  348. * in a strategy's `success()` action. This info is set at `req.authInfo`,
  349. * where said later middlware or routes can access it.
  350. *
  351. * Optionally, applications can register transforms to proccess this info,
  352. * which take effect prior to `req.authInfo` being set. This is useful, for
  353. * example, when the info contains a client ID. The transform can load the
  354. * client from the database and include the instance in the transformed info,
  355. * allowing the full set of client properties to be convieniently accessed.
  356. *
  357. * If no transforms are registered, `info` supplied by the strategy will be left
  358. * unmodified.
  359. *
  360. * Examples:
  361. *
  362. * passport.transformAuthInfo(function(info, done) {
  363. * Client.findById(info.clientID, function (err, client) {
  364. * info.client = client;
  365. * done(err, info);
  366. * });
  367. * });
  368. *
  369. * @api public
  370. */
  371. Authenticator.prototype.transformAuthInfo = function(fn, req, done) {
  372. if (typeof fn === 'function') {
  373. return this._infoTransformers.push(fn);
  374. }
  375. // private implementation that traverses the chain of transformers,
  376. // attempting to transform auth info
  377. var info = fn;
  378. // For backwards compatibility
  379. if (typeof req === 'function') {
  380. done = req;
  381. req = undefined;
  382. }
  383. var stack = this._infoTransformers;
  384. (function pass(i, err, tinfo) {
  385. // transformers use 'pass' as an error to skip processing
  386. if ('pass' === err) {
  387. err = undefined;
  388. }
  389. // an error or transformed info was obtained, done
  390. if (err || tinfo) { return done(err, tinfo); }
  391. var layer = stack[i];
  392. if (!layer) {
  393. // if no transformers are registered (or they all pass), the default
  394. // behavior is to use the un-transformed info as-is
  395. return done(null, info);
  396. }
  397. function transformed(e, t) {
  398. pass(i + 1, e, t);
  399. }
  400. try {
  401. var arity = layer.length;
  402. if (arity == 1) {
  403. // sync
  404. var t = layer(info);
  405. transformed(null, t);
  406. } else if (arity == 3) {
  407. layer(req, info, transformed);
  408. } else {
  409. layer(info, transformed);
  410. }
  411. } catch(e) {
  412. return done(e);
  413. }
  414. })(0);
  415. };
  416. /**
  417. * Return strategy with given `name`.
  418. *
  419. * @param {String} name
  420. * @return {Strategy}
  421. * @api private
  422. */
  423. Authenticator.prototype._strategy = function(name) {
  424. return this._strategies[name];
  425. };
  426. /**
  427. * Expose `Authenticator`.
  428. */
  429. module.exports = Authenticator;