AuthenticationControllerTests.coffee 18 KB

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