LoginRateLimiter.coffee 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. SandboxedModule = require('sandboxed-module')
  2. sinon = require('sinon')
  3. require('chai').should()
  4. modulePath = require('path').join __dirname, '../../../../app/js/Features/Security/LoginRateLimiter'
  5. buildKey = (k)->
  6. return "LoginRateLimit:#{k}"
  7. describe "LoginRateLimiter", ->
  8. beforeEach ->
  9. @email = "bob@bob.com"
  10. @incrStub = sinon.stub()
  11. @getStub = sinon.stub()
  12. @execStub = sinon.stub()
  13. @expireStub = sinon.stub()
  14. @delStub = sinon.stub().callsArgWith(1)
  15. @rclient =
  16. auth:->
  17. del: @delStub
  18. multi: =>
  19. incr: @incrStub
  20. expire: @expireStub
  21. get: @getStub
  22. exec: @execStub
  23. @LoginRateLimiter = SandboxedModule.require modulePath, requires:
  24. 'redis' : createClient: () => @rclient
  25. describe "processLoginRequest", ->
  26. it "should inc the counter for login requests in redis", (done)->
  27. @execStub.callsArgWith(0, "null", ["",""])
  28. @LoginRateLimiter.processLoginRequest @email, =>
  29. @incrStub.calledWith(buildKey(@email)).should.equal true
  30. done()
  31. it "should set a expire", (done)->
  32. @execStub.callsArgWith(0, "null", ["",""])
  33. @LoginRateLimiter.processLoginRequest @email, =>
  34. @expireStub.calledWith(buildKey(@email), 60 * 2).should.equal true
  35. done()
  36. it "should return true if the count is below 10", (done)->
  37. @execStub.callsArgWith(0, "null", ["", 9])
  38. @LoginRateLimiter.processLoginRequest @email, (err, isAllowed)=>
  39. isAllowed.should.equal true
  40. done()
  41. it "should return true if the count is 10", (done)->
  42. @execStub.callsArgWith(0, "null", ["", 10])
  43. @LoginRateLimiter.processLoginRequest @email, (err, isAllowed)=>
  44. isAllowed.should.equal true
  45. done()
  46. it "should return false if the count is above 10", (done)->
  47. @execStub.callsArgWith(0, "null", ["", 11])
  48. @LoginRateLimiter.processLoginRequest @email, (err, isAllowed)=>
  49. isAllowed.should.equal false
  50. done()
  51. describe "recordSuccessfulLogin", ->
  52. it "should delete the user key", (done)->
  53. @LoginRateLimiter.recordSuccessfulLogin @email, =>
  54. @delStub.calledWith(buildKey(@email)).should.equal true
  55. done()