AuthenticationControllerTests.coffee 13 KB

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