Permalink
Browse files

using an agent thing to thread cookies

  • Loading branch information...
1 parent 18bd9e9 commit f225efa0906641500630b96bfe90968c402f08f2 @substack substack committed Sep 15, 2010
Showing with 49 additions and 5 deletions.
  1. +49 −5 test/web.js
View
@@ -1,6 +1,7 @@
var Cart = require('cart');
var connect = require('connect');
var request = require('request');
+var Hash = require('traverse/hash');
var qs = require('querystring');
exports.webserver = function (assert) {
@@ -20,23 +21,66 @@ exports.webserver = function (assert) {
res.write('catface');
res.end();
});
+
app.post('/login', function (req, res) {
res.writeHead(200, { 'Content-Type' : 'text/html' });
+ if (req.body.user == 'substack' && req.body.pass == 'hax') {
+
+ res.write('ok');
+ }
+ else {
+ res.write('failed');
+ }
+ res.end();
+ });
+
+ app.get('/logout', function (req, res) {
+ res.writeHead(200, { 'Content-Type' : 'text/html' });
res.write('meow');
res.end();
});
}));
server.listen(port, 'localhost');
- var uri = 'http://localhost:' + port + '/';
+
+ var agent = new Agent('http://localhost:' + port);
setTimeout(function () {
- request({ uri : uri }, function (err, res, body) {
+ agent.request({ uri : '/' }, function (err, res, body) {
+console.log(body);
assert.equal('catface', body);
- var cookie = res.headers['set-cookie'][0];
- var cookies = qs.parse(cookie);
- assert.ok(cookies.connect.sid);
+console.dir(agent.cookies);
});
}, 100);
setTimeout(function () { server.close() }, 500);
};
+
+function Agent (uri) {
+ var self = this;
+ self.cookies = {};
+
+ self.request = function (params, cb) {
+ request(Hash.merge(params, {
+ uri : uri + params.uri,
+ headers : Hash.merge(params.headers, {
+ cookie : qs.stringify(Hash.merge(
+ self.cookies,
+ qs.parse((params.headers || {}).cookie)
+ ))
+ })}),
+ function (err, res, body) {
+ ((res.headers || {})['set-cookie'] || [])
+ .forEach(function (raw) {
+ var key = raw.split(/=/)[0];
+ self.cookies[key] = {};
+ raw.replace(key, 'value').split(/;\s*/)
+ .forEach(function (kv) {
+ var k = kv.split(/=/)[0];
+ self.cookies[key][k] = kv.split(/=/)[1] || true;
+ });
+ });
+ cb(err, res, body);
+ }
+ );
+ };
+}

0 comments on commit f225efa

Please sign in to comment.