AuthenticationControllerTests.coffee 13 KB

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