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.

70 lines
1.9 KiB

  1. /// Serialize the a name value pair into a cookie string suitable for
  2. /// http headers. An optional options object specified cookie parameters
  3. ///
  4. /// serialize('foo', 'bar', { httpOnly: true })
  5. /// => "foo=bar; httpOnly"
  6. ///
  7. /// @param {String} name
  8. /// @param {String} val
  9. /// @param {Object} options
  10. /// @return {String}
  11. var serialize = function(name, val, opt){
  12. opt = opt || {};
  13. var enc = opt.encode || encode;
  14. var pairs = [name + '=' + enc(val)];
  15. if (opt.maxAge) pairs.push('Max-Age=' + opt.maxAge);
  16. if (opt.domain) pairs.push('Domain=' + opt.domain);
  17. if (opt.path) pairs.push('Path=' + opt.path);
  18. if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString());
  19. if (opt.httpOnly) pairs.push('HttpOnly');
  20. if (opt.secure) pairs.push('Secure');
  21. return pairs.join('; ');
  22. };
  23. /// Parse the given cookie header string into an object
  24. /// The object has the various cookies as keys(names) => values
  25. /// @param {String} str
  26. /// @return {Object}
  27. var parse = function(str, opt) {
  28. opt = opt || {};
  29. var obj = {}
  30. var pairs = str.split(/[;,] */);
  31. var dec = opt.decode || decode;
  32. pairs.forEach(function(pair) {
  33. var eq_idx = pair.indexOf('=')
  34. // skip things that don't look like key=value
  35. if (eq_idx < 0) {
  36. return;
  37. }
  38. var key = pair.substr(0, eq_idx).trim()
  39. var val = pair.substr(++eq_idx, pair.length).trim();
  40. // quoted values
  41. if ('"' == val[0]) {
  42. val = val.slice(1, -1);
  43. }
  44. // only assign once
  45. if (undefined == obj[key]) {
  46. try {
  47. obj[key] = dec(val);
  48. } catch (e) {
  49. obj[key] = val;
  50. }
  51. }
  52. });
  53. return obj;
  54. };
  55. var encode = encodeURIComponent;
  56. var decode = decodeURIComponent;
  57. module.exports.serialize = serialize;
  58. module.exports.parse = parse;