AuthenticationControllerTests.coffee 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. sinon = require('sinon')
  2. chai = require('chai')
  3. should = chai.should()
  4. expect = chai.expect
  5. modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js"
  6. SandboxedModule = require('sandboxed-module')
  7. events = require "events"
  8. tk = require("timekeeper")
  9. MockRequest = require("../helpers/MockRequest")
  10. MockResponse = require("../helpers/MockResponse")
  11. ObjectId = require("mongojs").ObjectId
  12. describe "AuthenticationController", ->
  13. beforeEach ->
  14. @AuthenticationController = SandboxedModule.require modulePath, requires:
  15. "./AuthenticationManager": @AuthenticationManager = {}
  16. "../User/UserGetter" : @UserGetter = {}
  17. "../User/UserUpdater" : @UserUpdater = {}
  18. "../../infrastructure/Metrics": @Metrics = { inc: sinon.stub() }
  19. "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() }
  20. "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() }
  21. @user =
  22. _id: ObjectId()
  23. email: @email = "USER@example.com"
  24. first_name: "bob"
  25. last_name: "brown"
  26. referal_id: 1234
  27. isAdmin: false
  28. @password = "banana"
  29. @req = new MockRequest()
  30. @res = new MockResponse()
  31. @callback = @next = sinon.stub()
  32. tk.freeze(Date.now())
  33. afterEach ->
  34. tk.reset()
  35. describe "login", ->
  36. beforeEach ->
  37. @AuthenticationController._recordFailedLogin = sinon.stub()
  38. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  39. @AuthenticationController._establishUserSession = sinon.stub().callsArg(2)
  40. @req.body =
  41. email: @email
  42. password: @password
  43. redir: @redir = "/path/to/redir/to"
  44. describe "when the users rate limit", ->
  45. it "should block the request if the limit has been exceeded", (done)->
  46. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  47. @res =
  48. send: (code)=>
  49. @res.statusCode.should.equal 429
  50. done()
  51. @AuthenticationController.login(@req, @res)
  52. describe 'when the user is authenticated', ->
  53. beforeEach ->
  54. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  55. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  56. @AuthenticationController.login(@req, @res)
  57. it "should attempt to authorise the user", ->
  58. @AuthenticationManager.authenticate
  59. .calledWith(email: @email.toLowerCase(), @password)
  60. .should.equal true
  61. it "should establish the user's session", ->
  62. @AuthenticationController._establishUserSession
  63. .calledWith(@req, @user)
  64. .should.equal true
  65. it "should redirect the user to the specified location", ->
  66. expect(@res.body).to.deep.equal redir: @redir
  67. it "should record the successful login", ->
  68. @AuthenticationController._recordSuccessfulLogin
  69. .calledWith(@user._id)
  70. .should.equal true
  71. it "should tell the rate limiter that there was a success for that email", ->
  72. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true
  73. it "should log the successful login", ->
  74. @logger.log
  75. .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in")
  76. .should.equal true
  77. describe 'when the user is not authenticated', ->
  78. beforeEach ->
  79. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  80. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  81. @AuthenticationController.login(@req, @res)
  82. it "should return an error", ->
  83. # @res.body.should.exist
  84. expect(@res.body.message).to.exist
  85. # message:
  86. # text: 'Your email or password were incorrect. Please try again',
  87. # type: 'error'
  88. it "should not establish a session", ->
  89. @AuthenticationController._establishUserSession.called.should.equal false
  90. it "should record a failed login", ->
  91. @AuthenticationController._recordFailedLogin.called.should.equal true
  92. it "should log the failed login", ->
  93. @logger.log
  94. .calledWith(email: @email.toLowerCase(), "failed log in")
  95. .should.equal true
  96. describe "with a URL to a different domain", ->
  97. beforeEach ->
  98. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  99. @req.body.redir = "http://www.facebook.com/test"
  100. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  101. @AuthenticationController.login(@req, @res)
  102. it "should only redirect to the local path", ->
  103. expect(@res.body).to.deep.equal redir: "/test"
  104. describe "getLoggedInUserId", ->
  105. beforeEach ->
  106. @req =
  107. session :{}
  108. it "should return the user id from the session", (done)->
  109. @user_id = "2134"
  110. @req.session.user =
  111. _id:@user_id
  112. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  113. expect(user_id).to.equal @user_id
  114. done()
  115. it "should return null if there is no user on the session", (done)->
  116. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  117. expect(user_id).to.be.null
  118. done()
  119. it "should return null if there is no session", (done)->
  120. @req = {}
  121. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  122. expect(user_id).to.be.null
  123. done()
  124. it "should return null if there is no req", (done)->
  125. @req = {}
  126. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  127. expect(user_id).to.be.null
  128. done()
  129. describe "getLoggedInUser", ->
  130. beforeEach ->
  131. @UserGetter.getUser = sinon.stub().callsArgWith(1, null, @user)
  132. describe "with an established session", ->
  133. beforeEach ->
  134. @req.session =
  135. user: @user
  136. @AuthenticationController.getLoggedInUser(@req, {}, @callback)
  137. it "should look up the user in the database", ->
  138. @UserGetter.getUser
  139. .calledWith(@user._id)
  140. .should.equal true
  141. it "should return the user", ->
  142. @callback.calledWith(null, @user).should.equal true
  143. describe "with an auth token, but without auth_token_allowed set to true", ->
  144. beforeEach ->
  145. @req.query =
  146. auth_token: "auth-token"
  147. @AuthenticationController.getLoggedInUser(@req, {}, @callback)
  148. it "should not look up the user in the database", ->
  149. @UserGetter.getUser.called.should.equal false
  150. it "should return null in the callback", ->
  151. @callback.calledWith(null, null).should.equal true
  152. describe "with an auth token and auth_token_allowed set to true", ->
  153. beforeEach ->
  154. @req.query =
  155. auth_token: "auth-token"
  156. @AuthenticationController.getLoggedInUser(@req, {allow_auth_token: true}, @callback)
  157. it "should look up the user in the database", ->
  158. @UserGetter.getUser
  159. .calledWith(auth_token: @req.query.auth_token)
  160. .should.equal true
  161. it "should return the user", ->
  162. @callback.calledWith(null, @user).should.equal true
  163. describe "requireLogin", ->
  164. beforeEach ->
  165. @user =
  166. _id: "user-id-123"
  167. email: "user@sharelatex.com"
  168. describe "when loading from the database", ->
  169. beforeEach ->
  170. @middleware = @AuthenticationController.requireLogin(@options = { allow_auth_token: true, load_from_db: true })
  171. describe "when the user is logged in", ->
  172. beforeEach ->
  173. @AuthenticationController.getLoggedInUser = sinon.stub().callsArgWith(2, null, @user)
  174. @middleware(@req, @res, @next)
  175. it "should call getLoggedInUser with the passed options", ->
  176. @AuthenticationController.getLoggedInUser
  177. .calledWith(@req, { allow_auth_token: true })
  178. .should.equal true
  179. it "should set the user property on the request", ->
  180. @req.user.should.deep.equal @user
  181. it "should call the next method in the chain", ->
  182. @next.called.should.equal true
  183. describe "when the user is not logged in", ->
  184. beforeEach ->
  185. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  186. @AuthenticationController.getLoggedInUser = sinon.stub().callsArgWith(2, null, null)
  187. @middleware(@req, @res, @next)
  188. it "should redirect to the register page", ->
  189. @AuthenticationController._redirectToRegisterPage
  190. .calledWith(@req, @res)
  191. .should.equal true
  192. describe "when not loading from the database", ->
  193. beforeEach ->
  194. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  195. describe "when the user is logged in", ->
  196. beforeEach ->
  197. @req.session =
  198. user: @user = {
  199. _id: "user-id-123"
  200. email: "user@sharelatex.com"
  201. }
  202. @middleware(@req, @res, @next)
  203. it "should set the user property on the request", ->
  204. @req.user.should.deep.equal @user
  205. it "should call the next method in the chain", ->
  206. @next.called.should.equal true
  207. describe "when the user is not logged in", ->
  208. beforeEach ->
  209. @req.session = {}
  210. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  211. @middleware(@req, @res, @next)
  212. it "should redirect to the register page", ->
  213. @AuthenticationController._redirectToRegisterPage
  214. .calledWith(@req, @res)
  215. .should.equal true
  216. describe "when not loading from the database but an auth_token is provided", ->
  217. beforeEach ->
  218. @AuthenticationController.getLoggedInUser = sinon.stub().callsArgWith(2, null, @user)
  219. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false, allow_auth_token: true })
  220. @req.query = auth_token: @auth_token = "auth-token-provided"
  221. @middleware(@req, @res, @next)
  222. it "should try to load the user from the database anyway", ->
  223. @AuthenticationController.getLoggedInUser
  224. .calledWith(@req, {allow_auth_token: true})
  225. .should.equal true
  226. describe "_redirectToRegisterPage", ->
  227. beforeEach ->
  228. @req.path = "/target/url"
  229. @req.query =
  230. extra_query: "foo"
  231. @AuthenticationController._redirectToRegisterPage(@req, @res)
  232. it "should redirect to the register page with a query string attached", ->
  233. @res.redirectedTo
  234. .should.equal "/register?extra_query=foo&redir=%2Ftarget%2Furl"
  235. it "should log out a message", ->
  236. @logger.log
  237. .calledWith(url: @url, "user not logged in so redirecting to register page")
  238. .should.equal true
  239. it "should increase the security.login-redirect metric", ->
  240. @Metrics.inc.calledWith("security.login-redirect").should.equal true
  241. describe "_recordSuccessfulLogin", ->
  242. beforeEach ->
  243. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  244. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  245. it "should increment the user.login.success metric", ->
  246. @Metrics.inc
  247. .calledWith("user.login.success")
  248. .should.equal true
  249. it "should update the user's login count and last logged in date", ->
  250. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  251. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  252. it "should call the callback", ->
  253. @callback.called.should.equal true
  254. describe "_recordFailedLogin", ->
  255. beforeEach ->
  256. @AuthenticationController._recordFailedLogin(@callback)
  257. it "should increment the user.login.failed metric", ->
  258. @Metrics.inc
  259. .calledWith("user.login.failed")
  260. .should.equal true
  261. it "should call the callback", ->
  262. @callback.called.should.equal true
  263. describe "_establishUserSession", ->
  264. beforeEach ->
  265. @req.session =
  266. save: sinon.stub().callsArg(0)
  267. @AuthenticationController._establishUserSession @req, @user, @callback
  268. it "should set the session user to a basic version of the user", ->
  269. @req.session.user._id.should.equal @user._id
  270. @req.session.user.email.should.equal @user.email
  271. @req.session.user.first_name.should.equal @user.first_name
  272. @req.session.user.last_name.should.equal @user.last_name
  273. @req.session.user.referal_id.should.equal @user.referal_id
  274. @req.session.user.isAdmin.should.equal @user.isAdmin
  275. it "should return the callback", ->
  276. @callback.called.should.equal true