AuthenticationControllerTests.coffee 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()}
  21. "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() }
  22. "settings-sharelatex": {}
  23. @user =
  24. _id: ObjectId()
  25. email: @email = "USER@example.com"
  26. first_name: "bob"
  27. last_name: "brown"
  28. referal_id: 1234
  29. isAdmin: false
  30. @password = "banana"
  31. @req = new MockRequest()
  32. @res = new MockResponse()
  33. @callback = @next = sinon.stub()
  34. tk.freeze(Date.now())
  35. afterEach ->
  36. tk.reset()
  37. describe "login", ->
  38. beforeEach ->
  39. @AuthenticationController._recordFailedLogin = sinon.stub()
  40. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  41. @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  42. @req.body =
  43. email: @email
  44. password: @password
  45. redir: @redir = "/path/to/redir/to"
  46. describe "when the users rate limit", ->
  47. it "should block the request if the limit has been exceeded", (done)->
  48. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  49. @res =
  50. send: (code)=>
  51. @res.statusCode.should.equal 429
  52. done()
  53. @AuthenticationController.login(@req, @res)
  54. describe 'when the user is authenticated', ->
  55. beforeEach ->
  56. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  57. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  58. @AuthenticationController.login(@req, @res)
  59. it "should attempt to authorise the user", ->
  60. @AuthenticationManager.authenticate
  61. .calledWith(email: @email.toLowerCase(), @password)
  62. .should.equal true
  63. it "should setup the user data in the background", ->
  64. @UserHandler.setupLoginData.calledWith(@user).should.equal true
  65. it "should establish the user's session", ->
  66. @AuthenticationController.establishUserSession
  67. .calledWith(@req, @user)
  68. .should.equal true
  69. it "should set res.session.justLoggedIn", ->
  70. @req.session.justLoggedIn.should.equal true
  71. it "should redirect the user to the specified location", ->
  72. expect(@res.body).to.deep.equal redir: @redir
  73. it "should record the successful login", ->
  74. @AuthenticationController._recordSuccessfulLogin
  75. .calledWith(@user._id)
  76. .should.equal true
  77. it "should tell the rate limiter that there was a success for that email", ->
  78. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true
  79. it "should log the successful login", ->
  80. @logger.log
  81. .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in")
  82. .should.equal true
  83. describe 'when the user is not authenticated', ->
  84. beforeEach ->
  85. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  86. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  87. @AuthenticationController.login(@req, @res)
  88. it "should return an error", ->
  89. # @res.body.should.exist
  90. expect(@res.body.message).to.exist
  91. # message:
  92. # text: 'Your email or password were incorrect. Please try again',
  93. # type: 'error'
  94. it "should not establish a session", ->
  95. @AuthenticationController.establishUserSession.called.should.equal false
  96. it "should not setup the user data in the background", ->
  97. @UserHandler.setupLoginData.called.should.equal false
  98. it "should record a failed login", ->
  99. @AuthenticationController._recordFailedLogin.called.should.equal true
  100. it "should log the failed login", ->
  101. @logger.log
  102. .calledWith(email: @email.toLowerCase(), "failed log in")
  103. .should.equal true
  104. describe "with a URL to a different domain", ->
  105. beforeEach ->
  106. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  107. @req.body.redir = "http://www.facebook.com/test"
  108. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  109. @AuthenticationController.login(@req, @res)
  110. it "should only redirect to the local path", ->
  111. expect(@res.body).to.deep.equal redir: "/test"
  112. describe "getLoggedInUserId", ->
  113. beforeEach ->
  114. @req =
  115. session :{}
  116. it "should return the user id from the session", (done)->
  117. @user_id = "2134"
  118. @req.session.user =
  119. _id:@user_id
  120. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  121. expect(user_id).to.equal @user_id
  122. done()
  123. it "should return null if there is no user on the session", (done)->
  124. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  125. expect(user_id).to.be.null
  126. done()
  127. it "should return null if there is no session", (done)->
  128. @req = {}
  129. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  130. expect(user_id).to.be.null
  131. done()
  132. it "should return null if there is no req", (done)->
  133. @req = {}
  134. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  135. expect(user_id).to.be.null
  136. done()
  137. describe "getLoggedInUser", ->
  138. beforeEach ->
  139. @UserGetter.getUser = sinon.stub().callsArgWith(1, null, @user)
  140. describe "with an established session", ->
  141. beforeEach ->
  142. @req.session =
  143. user: @user
  144. @AuthenticationController.getLoggedInUser(@req, @callback)
  145. it "should look up the user in the database", ->
  146. @UserGetter.getUser
  147. .calledWith(@user._id)
  148. .should.equal true
  149. it "should return the user", ->
  150. @callback.calledWith(null, @user).should.equal true
  151. describe "requireLogin", ->
  152. beforeEach ->
  153. @user =
  154. _id: "user-id-123"
  155. email: "user@sharelatex.com"
  156. @middleware = @AuthenticationController.requireLogin()
  157. describe "when the user is logged in", ->
  158. beforeEach ->
  159. @req.session =
  160. user: @user = {
  161. _id: "user-id-123"
  162. email: "user@sharelatex.com"
  163. }
  164. @middleware(@req, @res, @next)
  165. it "should set the user property on the request", ->
  166. @req.user.should.deep.equal @user
  167. it "should call the next method in the chain", ->
  168. @next.called.should.equal true
  169. describe "when the user is not logged in", ->
  170. beforeEach ->
  171. @req.session = {}
  172. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  173. @req.query = {}
  174. @middleware(@req, @res, @next)
  175. it "should redirect to the register or login page", ->
  176. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  177. describe "requireGlobalLogin", ->
  178. beforeEach ->
  179. @req.headers = {}
  180. @AuthenticationController.httpAuth = sinon.stub()
  181. describe "with white listed url", ->
  182. beforeEach ->
  183. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  184. @req._parsedUrl.pathname = "/login"
  185. @AuthenticationController.requireGlobalLogin @req, @res, @next
  186. it "should call next() directly", ->
  187. @next.called.should.equal true
  188. describe "with white listed url and a query string", ->
  189. beforeEach ->
  190. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  191. @req._parsedUrl.pathname = "/login"
  192. @req.url = "/login?query=something"
  193. @AuthenticationController.requireGlobalLogin @req, @res, @next
  194. it "should call next() directly", ->
  195. @next.called.should.equal true
  196. describe "with http auth", ->
  197. beforeEach ->
  198. @req.headers["authorization"] = "Mock Basic Auth"
  199. @AuthenticationController.requireGlobalLogin @req, @res, @next
  200. it "should pass the request onto httpAuth", ->
  201. @AuthenticationController.httpAuth
  202. .calledWith(@req, @res, @next)
  203. .should.equal true
  204. describe "with a user session", ->
  205. beforeEach ->
  206. @req.session =
  207. user: {"mock": "user"}
  208. @AuthenticationController.requireGlobalLogin @req, @res, @next
  209. it "should call next() directly", ->
  210. @next.called.should.equal true
  211. describe "with no login credentials", ->
  212. beforeEach ->
  213. @AuthenticationController.requireGlobalLogin @req, @res, @next
  214. it "should redirect to the /login page", ->
  215. @res.redirectedTo.should.equal "/login"
  216. describe "_redirectToLoginOrRegisterPage", ->
  217. beforeEach ->
  218. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  219. @req.session = {}
  220. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  221. @AuthenticationController._redirectToLoginPage = sinon.stub()
  222. @req.query = {}
  223. describe "they have come directly to the url", ->
  224. beforeEach ->
  225. @req.query = {}
  226. @middleware(@req, @res, @next)
  227. it "should redirect to the login page", ->
  228. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  229. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  230. describe "they have come via a templates link", ->
  231. beforeEach ->
  232. @req.query.zipUrl = "something"
  233. @middleware(@req, @res, @next)
  234. it "should redirect to the register page", ->
  235. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  236. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  237. describe "they have been invited to a project", ->
  238. beforeEach ->
  239. @req.query.project_name = "something"
  240. @middleware(@req, @res, @next)
  241. it "should redirect to the register page", ->
  242. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  243. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  244. describe "_redirectToRegisterPage", ->
  245. beforeEach ->
  246. @req.path = "/target/url"
  247. @req.query =
  248. extra_query: "foo"
  249. @AuthenticationController._redirectToRegisterPage(@req, @res)
  250. it "should redirect to the register page with a query string attached", ->
  251. @res.redirectedTo
  252. .should.equal "/register?extra_query=foo&redir=%2Ftarget%2Furl"
  253. it "should log out a message", ->
  254. @logger.log
  255. .calledWith(url: @url, "user not logged in so redirecting to register page")
  256. .should.equal true
  257. describe "_redirectToLoginPage", ->
  258. beforeEach ->
  259. @req.path = "/target/url"
  260. @req.query =
  261. extra_query: "foo"
  262. @AuthenticationController._redirectToLoginPage(@req, @res)
  263. it "should redirect to the register page with a query string attached", ->
  264. @res.redirectedTo.should.equal "/login?extra_query=foo&redir=%2Ftarget%2Furl"
  265. describe "_recordSuccessfulLogin", ->
  266. beforeEach ->
  267. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  268. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  269. it "should increment the user.login.success metric", ->
  270. @Metrics.inc
  271. .calledWith("user.login.success")
  272. .should.equal true
  273. it "should update the user's login count and last logged in date", ->
  274. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  275. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  276. it "should call the callback", ->
  277. @callback.called.should.equal true
  278. describe "_recordFailedLogin", ->
  279. beforeEach ->
  280. @AuthenticationController._recordFailedLogin(@callback)
  281. it "should increment the user.login.failed metric", ->
  282. @Metrics.inc
  283. .calledWith("user.login.failed")
  284. .should.equal true
  285. it "should call the callback", ->
  286. @callback.called.should.equal true
  287. describe "establishUserSession", ->
  288. beforeEach ->
  289. @req.session =
  290. save: sinon.stub().callsArg(0)
  291. destroy : sinon.stub()
  292. @req.sessionStore =
  293. generate: sinon.stub()
  294. @AuthenticationController.establishUserSession @req, @user, @callback
  295. it "should set the session user to a basic version of the user", ->
  296. @req.session.user._id.should.equal @user._id
  297. @req.session.user.email.should.equal @user.email
  298. @req.session.user.first_name.should.equal @user.first_name
  299. @req.session.user.last_name.should.equal @user.last_name
  300. @req.session.user.referal_id.should.equal @user.referal_id
  301. @req.session.user.isAdmin.should.equal @user.isAdmin
  302. it "should destroy the session", ->
  303. @req.session.destroy.called.should.equal true
  304. it "should regenerate the session to protect against session fixation", ->
  305. @req.sessionStore.generate.calledWith(@req).should.equal true
  306. it "should return the callback", ->
  307. @callback.called.should.equal true