authenticate.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /**
  2. * Module dependencies.
  3. */
  4. var http = require('http')
  5. , IncomingMessageExt = require('../http/request')
  6. , AuthenticationError = require('../errors/authenticationerror');
  7. /**
  8. * Authenticates requests.
  9. *
  10. * Applies the `name`ed strategy (or strategies) to the incoming request, in
  11. * order to authenticate the request. If authentication is successful, the user
  12. * will be logged in and populated at `req.user` and a session will be
  13. * established by default. If authentication fails, an unauthorized response
  14. * will be sent.
  15. *
  16. * Options:
  17. * - `session` Save login state in session, defaults to _true_
  18. * - `successRedirect` After successful login, redirect to given URL
  19. * - `successMessage` True to store success message in
  20. * req.session.messages, or a string to use as override
  21. * message for success.
  22. * - `successFlash` True to flash success messages or a string to use as a flash
  23. * message for success (overrides any from the strategy itself).
  24. * - `failureRedirect` After failed login, redirect to given URL
  25. * - `failureMessage` True to store failure message in
  26. * req.session.messages, or a string to use as override
  27. * message for failure.
  28. * - `failureFlash` True to flash failure messages or a string to use as a flash
  29. * message for failures (overrides any from the strategy itself).
  30. * - `assignProperty` Assign the object provided by the verify callback to given property
  31. *
  32. * An optional `callback` can be supplied to allow the application to override
  33. * the default manner in which authentication attempts are handled. The
  34. * callback has the following signature, where `user` will be set to the
  35. * authenticated user on a successful authentication attempt, or `false`
  36. * otherwise. An optional `info` argument will be passed, containing additional
  37. * details provided by the strategy's verify callback - this could be information about
  38. * a successful authentication or a challenge message for a failed authentication.
  39. * An optional `status` argument will be passed when authentication fails - this could
  40. * be a HTTP response code for a remote authentication failure or similar.
  41. *
  42. * app.get('/protected', function(req, res, next) {
  43. * passport.authenticate('local', function(err, user, info, status) {
  44. * if (err) { return next(err) }
  45. * if (!user) { return res.redirect('/signin') }
  46. * res.redirect('/account');
  47. * })(req, res, next);
  48. * });
  49. *
  50. * Note that if a callback is supplied, it becomes the application's
  51. * responsibility to log-in the user, establish a session, and otherwise perform
  52. * the desired operations.
  53. *
  54. * Examples:
  55. *
  56. * passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' });
  57. *
  58. * passport.authenticate('basic', { session: false });
  59. *
  60. * passport.authenticate('twitter');
  61. *
  62. * @param {String|Array} name
  63. * @param {Object} options
  64. * @param {Function} callback
  65. * @return {Function}
  66. * @api public
  67. */
  68. module.exports = function authenticate(passport, name, options, callback) {
  69. if (typeof options == 'function') {
  70. callback = options;
  71. options = {};
  72. }
  73. options = options || {};
  74. var multi = true;
  75. // Cast `name` to an array, allowing authentication to pass through a chain of
  76. // strategies. The first strategy to succeed, redirect, or error will halt
  77. // the chain. Authentication failures will proceed through each strategy in
  78. // series, ultimately failing if all strategies fail.
  79. //
  80. // This is typically used on API endpoints to allow clients to authenticate
  81. // using their preferred choice of Basic, Digest, token-based schemes, etc.
  82. // It is not feasible to construct a chain of multiple strategies that involve
  83. // redirection (for example both Facebook and Twitter), since the first one to
  84. // redirect will halt the chain.
  85. if (!Array.isArray(name)) {
  86. name = [ name ];
  87. multi = false;
  88. }
  89. return function authenticate(req, res, next) {
  90. if (http.IncomingMessage.prototype.logIn
  91. && http.IncomingMessage.prototype.logIn !== IncomingMessageExt.logIn) {
  92. require('../framework/connect').__monkeypatchNode();
  93. }
  94. // accumulator for failures from each strategy in the chain
  95. var failures = [];
  96. function allFailed() {
  97. if (callback) {
  98. if (!multi) {
  99. return callback(null, false, failures[0].challenge, failures[0].status);
  100. } else {
  101. var challenges = failures.map(function(f) { return f.challenge; });
  102. var statuses = failures.map(function(f) { return f.status; });
  103. return callback(null, false, challenges, statuses);
  104. }
  105. }
  106. // Strategies are ordered by priority. For the purpose of flashing a
  107. // message, the first failure will be displayed.
  108. var failure = failures[0] || {}
  109. , challenge = failure.challenge || {}
  110. , msg;
  111. if (options.failureFlash) {
  112. var flash = options.failureFlash;
  113. if (typeof flash == 'string') {
  114. flash = { type: 'error', message: flash };
  115. }
  116. flash.type = flash.type || 'error';
  117. var type = flash.type || challenge.type || 'error';
  118. msg = flash.message || challenge.message || challenge;
  119. if (typeof msg == 'string') {
  120. req.flash(type, msg);
  121. }
  122. }
  123. if (options.failureMessage) {
  124. msg = options.failureMessage;
  125. if (typeof msg == 'boolean') {
  126. msg = challenge.message || challenge;
  127. }
  128. if (typeof msg == 'string') {
  129. req.session.messages = req.session.messages || [];
  130. req.session.messages.push(msg);
  131. }
  132. }
  133. if (options.failureRedirect) {
  134. return res.redirect(options.failureRedirect);
  135. }
  136. // When failure handling is not delegated to the application, the default
  137. // is to respond with 401 Unauthorized. Note that the WWW-Authenticate
  138. // header will be set according to the strategies in use (see
  139. // actions#fail). If multiple strategies failed, each of their challenges
  140. // will be included in the response.
  141. var rchallenge = []
  142. , rstatus, status;
  143. for (var j = 0, len = failures.length; j < len; j++) {
  144. failure = failures[j];
  145. challenge = failure.challenge;
  146. status = failure.status;
  147. rstatus = rstatus || status;
  148. if (typeof challenge == 'string') {
  149. rchallenge.push(challenge);
  150. }
  151. }
  152. res.statusCode = rstatus || 401;
  153. if (res.statusCode == 401 && rchallenge.length) {
  154. res.setHeader('WWW-Authenticate', rchallenge);
  155. }
  156. if (options.failWithError) {
  157. return next(new AuthenticationError(http.STATUS_CODES[res.statusCode], rstatus));
  158. }
  159. res.end(http.STATUS_CODES[res.statusCode]);
  160. }
  161. (function attempt(i) {
  162. var layer = name[i];
  163. // If no more strategies exist in the chain, authentication has failed.
  164. if (!layer) { return allFailed(); }
  165. // Get the strategy, which will be used as prototype from which to create
  166. // a new instance. Action functions will then be bound to the strategy
  167. // within the context of the HTTP request/response pair.
  168. var prototype = passport._strategy(layer);
  169. if (!prototype) { return next(new Error('Unknown authentication strategy "' + layer + '"')); }
  170. var strategy = Object.create(prototype);
  171. // ----- BEGIN STRATEGY AUGMENTATION -----
  172. // Augment the new strategy instance with action functions. These action
  173. // functions are bound via closure the the request/response pair. The end
  174. // goal of the strategy is to invoke *one* of these action methods, in
  175. // order to indicate successful or failed authentication, redirect to a
  176. // third-party identity provider, etc.
  177. /**
  178. * Authenticate `user`, with optional `info`.
  179. *
  180. * Strategies should call this function to successfully authenticate a
  181. * user. `user` should be an object supplied by the application after it
  182. * has been given an opportunity to verify credentials. `info` is an
  183. * optional argument containing additional user information. This is
  184. * useful for third-party authentication strategies to pass profile
  185. * details.
  186. *
  187. * @param {Object} user
  188. * @param {Object} info
  189. * @api public
  190. */
  191. strategy.success = function(user, info) {
  192. if (callback) {
  193. return callback(null, user, info);
  194. }
  195. info = info || {};
  196. var msg;
  197. if (options.successFlash) {
  198. var flash = options.successFlash;
  199. if (typeof flash == 'string') {
  200. flash = { type: 'success', message: flash };
  201. }
  202. flash.type = flash.type || 'success';
  203. var type = flash.type || info.type || 'success';
  204. msg = flash.message || info.message || info;
  205. if (typeof msg == 'string') {
  206. req.flash(type, msg);
  207. }
  208. }
  209. if (options.successMessage) {
  210. msg = options.successMessage;
  211. if (typeof msg == 'boolean') {
  212. msg = info.message || info;
  213. }
  214. if (typeof msg == 'string') {
  215. req.session.messages = req.session.messages || [];
  216. req.session.messages.push(msg);
  217. }
  218. }
  219. if (options.assignProperty) {
  220. req[options.assignProperty] = user;
  221. return next();
  222. }
  223. req.logIn(user, options, function(err) {
  224. if (err) { return next(err); }
  225. function complete() {
  226. if (options.successReturnToOrRedirect) {
  227. var url = options.successReturnToOrRedirect;
  228. if (req.session && req.session.returnTo) {
  229. url = req.session.returnTo;
  230. delete req.session.returnTo;
  231. }
  232. return res.redirect(url);
  233. }
  234. if (options.successRedirect) {
  235. return res.redirect(options.successRedirect);
  236. }
  237. next();
  238. }
  239. if (options.authInfo !== false) {
  240. passport.transformAuthInfo(info, req, function(err, tinfo) {
  241. if (err) { return next(err); }
  242. req.authInfo = tinfo;
  243. complete();
  244. });
  245. } else {
  246. complete();
  247. }
  248. });
  249. };
  250. /**
  251. * Fail authentication, with optional `challenge` and `status`, defaulting
  252. * to 401.
  253. *
  254. * Strategies should call this function to fail an authentication attempt.
  255. *
  256. * @param {String} challenge
  257. * @param {Number} status
  258. * @api public
  259. */
  260. strategy.fail = function(challenge, status) {
  261. if (typeof challenge == 'number') {
  262. status = challenge;
  263. challenge = undefined;
  264. }
  265. // push this failure into the accumulator and attempt authentication
  266. // using the next strategy
  267. failures.push({ challenge: challenge, status: status });
  268. attempt(i + 1);
  269. };
  270. /**
  271. * Redirect to `url` with optional `status`, defaulting to 302.
  272. *
  273. * Strategies should call this function to redirect the user (via their
  274. * user agent) to a third-party website for authentication.
  275. *
  276. * @param {String} url
  277. * @param {Number} status
  278. * @api public
  279. */
  280. strategy.redirect = function(url, status) {
  281. // NOTE: Do not use `res.redirect` from Express, because it can't decide
  282. // what it wants.
  283. //
  284. // Express 2.x: res.redirect(url, status)
  285. // Express 3.x: res.redirect(status, url) -OR- res.redirect(url, status)
  286. // - as of 3.14.0, deprecated warnings are issued if res.redirect(url, status)
  287. // is used
  288. // Express 4.x: res.redirect(status, url)
  289. // - all versions (as of 4.8.7) continue to accept res.redirect(url, status)
  290. // but issue deprecated versions
  291. res.statusCode = status || 302;
  292. res.setHeader('Location', url);
  293. res.setHeader('Content-Length', '0');
  294. res.end();
  295. };
  296. /**
  297. * Pass without making a success or fail decision.
  298. *
  299. * Under most circumstances, Strategies should not need to call this
  300. * function. It exists primarily to allow previous authentication state
  301. * to be restored, for example from an HTTP session.
  302. *
  303. * @api public
  304. */
  305. strategy.pass = function() {
  306. next();
  307. };
  308. /**
  309. * Internal error while performing authentication.
  310. *
  311. * Strategies should call this function when an internal error occurs
  312. * during the process of performing authentication; for example, if the
  313. * user directory is not available.
  314. *
  315. * @param {Error} err
  316. * @api public
  317. */
  318. strategy.error = function(err) {
  319. if (callback) {
  320. return callback(err);
  321. }
  322. next(err);
  323. };
  324. // ----- END STRATEGY AUGMENTATION -----
  325. strategy.authenticate(req, options);
  326. })(0); // attempt
  327. };
  328. };