AuthenticationControllerTests.coffee 15 KB

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