auth_opt.js 1.5 KB

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