owner-tests.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const assert = require('assert');
  2. const sinon = require('sinon');
  3. const proxyquire = require('proxyquire').noCallThru();
  4. const storage = {
  5. metadata: sinon.stub()
  6. };
  7. function request(id, owner_token) {
  8. return {
  9. params: { id },
  10. body: { owner_token }
  11. };
  12. }
  13. function response() {
  14. return {
  15. sendStatus: sinon.stub()
  16. };
  17. }
  18. const ownerMiddleware = proxyquire('../../server/middleware/auth', {
  19. '../storage': storage
  20. }).owner;
  21. describe('Owner Middleware', function() {
  22. afterEach(function() {
  23. storage.metadata.reset();
  24. });
  25. it('sends a 404 when the id is not found', async function() {
  26. const next = sinon.stub();
  27. storage.metadata.returns(Promise.resolve(null));
  28. const res = response();
  29. await ownerMiddleware(request('a', 'y'), res, next);
  30. sinon.assert.notCalled(next);
  31. sinon.assert.calledWith(res.sendStatus, 404);
  32. });
  33. it('sends a 401 when the owner_token is missing', async function() {
  34. const next = sinon.stub();
  35. const meta = { owner: 'y' };
  36. storage.metadata.returns(Promise.resolve(meta));
  37. const res = response();
  38. await ownerMiddleware(request('b', null), res, next);
  39. sinon.assert.notCalled(next);
  40. sinon.assert.calledWith(res.sendStatus, 401);
  41. });
  42. it('sends a 401 when the owner_token does not match', async function() {
  43. const next = sinon.stub();
  44. const meta = { owner: 'y' };
  45. storage.metadata.returns(Promise.resolve(meta));
  46. const res = response();
  47. await ownerMiddleware(request('c', 'z'), res, next);
  48. sinon.assert.notCalled(next);
  49. sinon.assert.calledWith(res.sendStatus, 401);
  50. });
  51. it('sends a 401 if the metadata call fails', async function() {
  52. const next = sinon.stub();
  53. storage.metadata.returns(Promise.reject(new Error()));
  54. const res = response();
  55. await ownerMiddleware(request('d', 'y'), res, next);
  56. sinon.assert.notCalled(next);
  57. sinon.assert.calledWith(res.sendStatus, 401);
  58. });
  59. it('sets req.meta and req.authorized on successful auth', async function() {
  60. const next = sinon.stub();
  61. const meta = { owner: 'y' };
  62. storage.metadata.returns(Promise.resolve(meta));
  63. const req = request('e', 'y');
  64. const res = response();
  65. await ownerMiddleware(req, res, next);
  66. assert.equal(req.meta, meta);
  67. assert.equal(req.authorized, true);
  68. sinon.assert.notCalled(res.sendStatus);
  69. sinon.assert.calledOnce(next);
  70. });
  71. });