Skip to content

Instantly share code, notes, and snippets.

@nrstott
Created August 12, 2010 02:24
Show Gist options
  • Save nrstott/520196 to your computer and use it in GitHub Desktop.
Save nrstott/520196 to your computer and use it in GitHub Desktop.
exports.CookieJar = function(nextApp) {
var domainToCookies = {};
return function(req) {
var querystring = require("./querystring");
if (req.url) {
throw new Error("CookieJar does not support 'url' shortcut yet");
}
if (req.hostname && domainToCookies[req.hostname]) {
var cookieString = "";
req.headers["Cookie"] = querystring.toQueryString(domainToCookies[req.hostname]);
}
console.log("request:"+JSON.stringify(req));
return when(nextApp(req), function(response) {
var cookies;
if (response.headers["set-cookie"]) {
var path, domain = req.hostname + (req.port ? ":"+req.port : "");
cookies = querystring.parseQuery(response.headers["set-cookie"], /[;,]/g);
if (cookies.Version !== undefined) { delete cookies.Version; }
if (cookies.Path !== undefined) { path = cookies.Path; delete cookies.Path; }
if (cookies.HttpOnly !== undefined) { delete cookies.HttpOnly; }
if (cookies.Domain !== undefined) { domain = cookies.Domain; delete cookies.Domain; }
for (var k in cookies) {
if (Array.isArray(cookies[k])) {
cookies[k] = cookies[k][0];
}
}
if (cookies) {
domainToCookies[req.hostname] = cookies;
}
}
return response;
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment