You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.4 KiB

  1. /*!
  2. * Connect - cookieParser
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var utils = require('./../utils')
  11. , cookie = require('cookie');
  12. /**
  13. * Cookie parser:
  14. *
  15. * Parse _Cookie_ header and populate `req.cookies`
  16. * with an object keyed by the cookie names. Optionally
  17. * you may enabled signed cookie support by passing
  18. * a `secret` string, which assigns `req.secret` so
  19. * it may be used by other middleware.
  20. *
  21. * Examples:
  22. *
  23. * connect()
  24. * .use(connect.cookieParser('optional secret string'))
  25. * .use(function(req, res, next){
  26. * res.end(JSON.stringify(req.cookies));
  27. * })
  28. *
  29. * @param {String} secret
  30. * @return {Function}
  31. * @api public
  32. */
  33. module.exports = function cookieParser(secret){
  34. return function cookieParser(req, res, next) {
  35. if (req.cookies) return next();
  36. var cookies = req.headers.cookie;
  37. req.secret = secret;
  38. req.cookies = {};
  39. req.signedCookies = {};
  40. if (cookies) {
  41. try {
  42. req.cookies = cookie.parse(cookies);
  43. if (secret) {
  44. req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
  45. req.signedCookies = utils.parseJSONCookies(req.signedCookies);
  46. }
  47. req.cookies = utils.parseJSONCookies(req.cookies);
  48. } catch (err) {
  49. err.status = 400;
  50. return next(err);
  51. }
  52. }
  53. next();
  54. };
  55. };