1 var assert = require('assert')
2 , http = require('http')
3 , request = require('../index')
6 var numBasicRequests = 0;
8 var basicServer = http.createServer(function (req, res) {
9 console.error('Basic auth server: ', req.method, req.url);
14 if (req.headers.authorization) {
15 if (req.headers.authorization == 'Basic ' + new Buffer('test:testing2').toString('base64')) {
17 } else if ( req.headers.authorization == 'Basic ' + new Buffer(':apassword').toString('base64')) {
19 } else if ( req.headers.authorization == 'Basic ' + new Buffer('justauser').toString('base64')) {
22 // Bad auth header, don't send back WWW-Authenticate header
26 // No auth header, send back WWW-Authenticate header
28 res.setHeader('www-authenticate', 'Basic realm="Private"');
31 if (req.url == '/post/') {
32 var expectedContent = 'data_key=data_value';
33 req.on('data', function(data) {
34 assert.equal(data, expectedContent);
35 console.log('received request data: ' + data);
37 assert.equal(req.method, 'POST');
38 assert.equal(req.headers['content-length'], '' + expectedContent.length);
39 assert.equal(req.headers['content-type'], 'application/x-www-form-urlencoded; charset=utf-8');
43 console.log('request ok');
46 console.log('status=401');
52 basicServer.listen(6767);
58 'uri': 'http://localhost:6767/test/',
62 'sendImmediately': false
64 }, function(error, res, body) {
65 assert.equal(res.statusCode, 200);
66 assert.equal(numBasicRequests, 2);
72 // If we don't set sendImmediately = false, request will send basic auth
75 'uri': 'http://localhost:6767/test2/',
80 }, function(error, res, body) {
81 assert.equal(res.statusCode, 200);
82 assert.equal(numBasicRequests, 3);
90 'uri': 'http://test:testing2@localhost:6767/test2/'
91 }, function(error, res, body) {
92 assert.equal(res.statusCode, 200);
93 assert.equal(numBasicRequests, 4);
101 'form': { 'data_key': 'data_value' },
102 'uri': 'http://localhost:6767/post/',
106 'sendImmediately': false
108 }, function(error, res, body) {
109 assert.equal(res.statusCode, 200);
110 assert.equal(numBasicRequests, 6);
116 assert.doesNotThrow( function() {
119 'uri': 'http://localhost:6767/allow_empty_user/',
123 'sendImmediately': false
125 }, function(error, res, body ) {
126 assert.equal(res.statusCode, 200);
127 assert.equal(numBasicRequests, 8);
134 assert.doesNotThrow( function() {
137 'uri': 'http://localhost:6767/allow_undefined_password/',
141 'sendImmediately': false
143 }, function(error, res, body ) {
144 assert.equal(res.statusCode, 200);
145 assert.equal(numBasicRequests, 10);
152 function runTest(i) {
153 if (i < tests.length) {
154 tests[i](function() {
158 console.log('All tests passed');