parse.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var signature = require('cookie-signature');
  2. /**
  3. * Parse signed cookies, returning an object
  4. * containing the decoded key/value pairs,
  5. * while removing the signed key from `obj`.
  6. *
  7. * @param {Object} obj
  8. * @return {Object}
  9. * @api private
  10. */
  11. exports.signedCookies = function(obj, secret){
  12. var cookies = Object.keys(obj);
  13. var dec;
  14. var key;
  15. var ret = Object.create(null);
  16. var val;
  17. for (var i = 0; i < cookies.length; i++) {
  18. key = cookies[i];
  19. val = obj[key];
  20. dec = exports.signedCookie(val, secret);
  21. if (val !== dec) {
  22. ret[key] = dec;
  23. delete obj[key];
  24. }
  25. }
  26. return ret;
  27. };
  28. /**
  29. * Parse a signed cookie string, return the decoded value
  30. *
  31. * @param {String} str signed cookie string
  32. * @param {String} secret
  33. * @return {String} decoded value
  34. * @api private
  35. */
  36. exports.signedCookie = function(str, secret){
  37. return str.substr(0, 2) === 's:'
  38. ? signature.unsign(str.slice(2), secret)
  39. : str;
  40. };
  41. /**
  42. * Parse JSON cookies.
  43. *
  44. * @param {Object} obj
  45. * @return {Object}
  46. * @api private
  47. */
  48. exports.JSONCookies = function(obj){
  49. var cookies = Object.keys(obj);
  50. var key;
  51. var val;
  52. for (var i = 0; i < cookies.length; i++) {
  53. key = cookies[i];
  54. val = exports.JSONCookie(obj[key]);
  55. if (val) {
  56. obj[key] = val;
  57. }
  58. }
  59. return obj;
  60. };
  61. /**
  62. * Parse JSON cookie string
  63. *
  64. * @param {String} str
  65. * @return {Object} Parsed object or null if not json cookie
  66. * @api private
  67. */
  68. exports.JSONCookie = function(str) {
  69. if (!str || str.substr(0, 2) !== 'j:') return;
  70. try {
  71. return JSON.parse(str.slice(2));
  72. } catch (err) {
  73. // no op
  74. }
  75. };