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