auth.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var test = require('tape');
  2. var http = require('http');
  3. var hyperquest = require('../');
  4. var server = http.createServer(function (req, res) {
  5. var au = req.headers.authorization;
  6. if (!au) return res.end('ACCESS DENIED');
  7. var buf = Buffer(au.replace(/^Basic\s+/, ''), 'base64');
  8. var s = buf.toString().split(':');
  9. if (s[0] === 'moo' && s[1] === 'hax') {
  10. res.end('WELCOME TO ZOMBO COM');
  11. }
  12. else {
  13. res.end('ACCESS DENIED!!!');
  14. }
  15. });
  16. test('basic auth', function (t) {
  17. t.plan(3);
  18. server.listen(0, function () {
  19. var port = server.address().port;
  20. checkUnauth(t, port);
  21. checkValid(t, port);
  22. checkInvalid(t, port);
  23. });
  24. t.on('end', server.close.bind(server));
  25. });
  26. function checkUnauth (t, port) {
  27. var r = hyperquest('http://localhost:' + port);
  28. var data = '';
  29. r.on('data', function (buf) { data += buf });
  30. r.on('end', function () { t.equal(data, 'ACCESS DENIED') });
  31. }
  32. function checkValid (t, port) {
  33. var r = hyperquest('http://moo:hax@localhost:' + port);
  34. var data = '';
  35. r.on('data', function (buf) { data += buf });
  36. r.on('end', function () { t.equal(data, 'WELCOME TO ZOMBO COM') });
  37. }
  38. function checkInvalid (t, port) {
  39. var r = hyperquest('http://beep:boop@localhost:' + port);
  40. var data = '';
  41. r.on('data', function (buf) { data += buf });
  42. r.on('end', function () { t.equal(data, 'ACCESS DENIED!!!') });
  43. }