AuthenticationControllerTests.coffee 15 KB

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