authenticator.js 13 KB

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