authenticate.js 12 KB

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