AuthenticationControllerTests.coffee 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. expect(@res.body).to.deep.equal
  84. message:
  85. text: 'Your email or password were incorrect. Please try again',
  86. type: 'error'
  87. it "should not establish a session", ->
  88. @AuthenticationController._establishUserSession.called.should.equal false
  89. it "should record a failed login", ->
  90. @AuthenticationController._recordFailedLogin.called.should.equal true
  91. it "should log the failed login", ->
  92. @logger.log
  93. .calledWith(email: @email.toLowerCase(), "failed log in")
  94. .should.equal true
  95. describe "with a URL to a different domain", ->
  96. beforeEach ->
  97. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  98. @req.body.redir = "http://www.facebook.com/test"
  99. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  100. @AuthenticationController.login(@req, @res)
  101. it "should only redirect to the local path", ->
  102. expect(@res.body).to.deep.equal redir: "/test"
  103. describe "getLoggedInUserId", ->
  104. beforeEach ->
  105. @req =
  106. session :{}
  107. it "should return the user id from the session", (done)->
  108. @user_id = "2134"
  109. @req.session.user =
  110. _id:@user_id
  111. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  112. expect(user_id).to.equal @user_id
  113. done()
  114. it "should return null if there is no user on the session", (done)->
  115. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  116. expect(user_id).to.be.null
  117. done()
  118. it "should return null if there is no session", (done)->
  119. @req = {}
  120. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  121. expect(user_id).to.be.null
  122. done()
  123. it "should return null if there is no req", (done)->
  124. @req = {}
  125. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  126. expect(user_id).to.be.null
  127. done()
  128. describe "getLoggedInUser", ->
  129. beforeEach ->
  130. @UserGetter.getUser = sinon.stub().callsArgWith(1, null, @user)
  131. describe "with an established session", ->
  132. beforeEach ->
  133. @req.session =
  134. user: @user
  135. @AuthenticationController.getLoggedInUser(@req, {}, @callback)
  136. it "should look up the user in the database", ->
  137. @UserGetter.getUser
  138. .calledWith(@user._id)
  139. .should.equal true
  140. it "should return the user", ->
  141. @callback.calledWith(null, @user).should.equal true
  142. describe "with an auth token, but without auth_token_allowed set to true", ->
  143. beforeEach ->
  144. @req.query =
  145. auth_token: "auth-token"
  146. @AuthenticationController.getLoggedInUser(@req, {}, @callback)
  147. it "should not look up the user in the database", ->
  148. @UserGetter.getUser.called.should.equal false
  149. it "should return null in the callback", ->
  150. @callback.calledWith(null, null).should.equal true
  151. describe "with an auth token and auth_token_allowed set to true", ->
  152. beforeEach ->
  153. @req.query =
  154. auth_token: "auth-token"
  155. @AuthenticationController.getLoggedInUser(@req, {allow_auth_token: true}, @callback)
  156. it "should look up the user in the database", ->
  157. @UserGetter.getUser
  158. .calledWith(auth_token: @req.query.auth_token)
  159. .should.equal true
  160. it "should return the user", ->
  161. @callback.calledWith(null, @user).should.equal true
  162. describe "requireLogin", ->
  163. beforeEach ->
  164. @user =
  165. _id: "user-id-123"
  166. email: "user@sharelatex.com"
  167. describe "when loading from the database", ->
  168. beforeEach ->
  169. @middleware = @AuthenticationController.requireLogin(@options = { allow_auth_token: true, load_from_db: true })
  170. describe "when the user is logged in", ->
  171. beforeEach ->
  172. @AuthenticationController.getLoggedInUser = sinon.stub().callsArgWith(2, null, @user)
  173. @middleware(@req, @res, @next)
  174. it "should call getLoggedInUser with the passed options", ->
  175. @AuthenticationController.getLoggedInUser
  176. .calledWith(@req, { allow_auth_token: true })
  177. .should.equal true
  178. it "should set the user property on the request", ->
  179. @req.user.should.deep.equal @user
  180. it "should call the next method in the chain", ->
  181. @next.called.should.equal true
  182. describe "when the user is not logged in", ->
  183. beforeEach ->
  184. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  185. @AuthenticationController.getLoggedInUser = sinon.stub().callsArgWith(2, null, null)
  186. @middleware(@req, @res, @next)
  187. it "should redirect to the register page", ->
  188. @AuthenticationController._redirectToRegisterPage
  189. .calledWith(@req, @res)
  190. .should.equal true
  191. describe "when not loading from the database", ->
  192. beforeEach ->
  193. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  194. describe "when the user is logged in", ->
  195. beforeEach ->
  196. @req.session =
  197. user: @user = {
  198. _id: "user-id-123"
  199. email: "user@sharelatex.com"
  200. }
  201. @middleware(@req, @res, @next)
  202. it "should set the user property on the request", ->
  203. @req.user.should.deep.equal @user
  204. it "should call the next method in the chain", ->
  205. @next.called.should.equal true
  206. describe "when the user is not logged in", ->
  207. beforeEach ->
  208. @req.session = {}
  209. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  210. @middleware(@req, @res, @next)
  211. it "should redirect to the register page", ->
  212. @AuthenticationController._redirectToRegisterPage
  213. .calledWith(@req, @res)
  214. .should.equal true
  215. describe "when not loading from the database but an auth_token is provided", ->
  216. beforeEach ->
  217. @AuthenticationController.getLoggedInUser = sinon.stub().callsArgWith(2, null, @user)
  218. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false, allow_auth_token: true })
  219. @req.query = auth_token: @auth_token = "auth-token-provided"
  220. @middleware(@req, @res, @next)
  221. it "should try to load the user from the database anyway", ->
  222. @AuthenticationController.getLoggedInUser
  223. .calledWith(@req, {allow_auth_token: true})
  224. .should.equal true
  225. describe "_redirectToRegisterPage", ->
  226. beforeEach ->
  227. @req.path = "/target/url"
  228. @req.query =
  229. extra_query: "foo"
  230. @AuthenticationController._redirectToRegisterPage(@req, @res)
  231. it "should redirect to the register page with a query string attached", ->
  232. @res.redirectedTo
  233. .should.equal "/register?extra_query=foo&redir=%2Ftarget%2Furl"
  234. it "should log out a message", ->
  235. @logger.log
  236. .calledWith(url: @url, "user not logged in so redirecting to register page")
  237. .should.equal true
  238. it "should increase the security.login-redirect metric", ->
  239. @Metrics.inc.calledWith("security.login-redirect").should.equal true
  240. describe "_recordSuccessfulLogin", ->
  241. beforeEach ->
  242. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  243. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  244. it "should increment the user.login.success metric", ->
  245. @Metrics.inc
  246. .calledWith("user.login.success")
  247. .should.equal true
  248. it "should update the user's login count and last logged in date", ->
  249. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  250. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  251. it "should call the callback", ->
  252. @callback.called.should.equal true
  253. describe "_recordFailedLogin", ->
  254. beforeEach ->
  255. @AuthenticationController._recordFailedLogin(@callback)
  256. it "should increment the user.login.failed metric", ->
  257. @Metrics.inc
  258. .calledWith("user.login.failed")
  259. .should.equal true
  260. it "should call the callback", ->
  261. @callback.called.should.equal true
  262. describe "_establishUserSession", ->
  263. beforeEach ->
  264. @req.session =
  265. save: sinon.stub().callsArg(0)
  266. @AuthenticationController._establishUserSession @req, @user, @callback
  267. it "should set the session user to a basic version of the user", ->
  268. @req.session.user._id.should.equal @user._id
  269. @req.session.user.email.should.equal @user.email
  270. @req.session.user.first_name.should.equal @user.first_name
  271. @req.session.user.last_name.should.equal @user.last_name
  272. @req.session.user.referal_id.should.equal @user.referal_id
  273. @req.session.user.isAdmin.should.equal @user.isAdmin
  274. it "should return the callback", ->
  275. @callback.called.should.equal true