index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*!
  2. * cookie-parser
  3. * MIT Licensed
  4. */
  5. /**
  6. * Module dependencies.
  7. */
  8. var cookie = require('cookie');
  9. var parse = require('./lib/parse');
  10. /**
  11. * Parse Cookie header and populate `req.cookies`
  12. * with an object keyed by the cookie names.
  13. *
  14. * @param {String} [secret]
  15. * @param {Object} [options]
  16. * @return {Function}
  17. * @api public
  18. */
  19. exports = module.exports = function cookieParser(secret, options){
  20. return function cookieParser(req, res, next) {
  21. if (req.cookies) return next();
  22. var cookies = req.headers.cookie;
  23. req.secret = secret;
  24. req.cookies = Object.create(null);
  25. req.signedCookies = Object.create(null);
  26. // no cookies
  27. if (!cookies) {
  28. return next();
  29. }
  30. req.cookies = cookie.parse(cookies, options);
  31. // parse signed cookies
  32. if (secret) {
  33. req.signedCookies = parse.signedCookies(req.cookies, secret);
  34. req.signedCookies = parse.JSONCookies(req.signedCookies);
  35. }
  36. // parse JSON cookies
  37. req.cookies = parse.JSONCookies(req.cookies);
  38. next();
  39. };
  40. };
  41. /**
  42. * Export parsing functions.
  43. */
  44. exports.JSONCookie = parse.JSONCookie;
  45. exports.JSONCookies = parse.JSONCookies;
  46. exports.signedCookie = parse.signedCookie;
  47. exports.signedCookies = parse.signedCookies;