AuthenticationControllerTests.coffee 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. tk.freeze(Date.now())
  15. @AuthenticationController = SandboxedModule.require modulePath, requires:
  16. "./AuthenticationManager": @AuthenticationManager = {}
  17. "../User/UserGetter" : @UserGetter = {}
  18. "../User/UserUpdater" : @UserUpdater = {}
  19. "metrics-sharelatex": @Metrics = { inc: sinon.stub() }
  20. "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() }
  21. "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()}
  22. "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() }
  23. "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() }
  24. "settings-sharelatex": {}
  25. "passport": @passport =
  26. authenticate: sinon.stub().returns(sinon.stub())
  27. "../User/UserSessionsManager": @UserSessionsManager =
  28. trackSession: sinon.stub()
  29. untrackSession: sinon.stub()
  30. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  31. @user =
  32. _id: ObjectId()
  33. email: @email = "USER@example.com"
  34. first_name: "bob"
  35. last_name: "brown"
  36. referal_id: 1234
  37. isAdmin: false
  38. @password = "banana"
  39. @req = new MockRequest()
  40. @res = new MockResponse()
  41. @callback = @next = sinon.stub()
  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 = {
  84. passport: {user: @user},
  85. postLoginRedirect: "/path/to/redir/to"
  86. }
  87. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  88. @req.session.save = sinon.stub().callsArgWith(0, null)
  89. @req.sessionStore = {generate: sinon.stub()}
  90. @AuthenticationController.finishLogin = sinon.stub()
  91. @passport.authenticate.callsArgWith(1, null, @user, @info)
  92. @err = new Error('woops')
  93. it 'should call passport.authenticate', () ->
  94. @AuthenticationController.passportLogin @req, @res, @next
  95. @passport.authenticate.callCount.should.equal 1
  96. describe 'when authenticate produces an error', ->
  97. beforeEach ->
  98. @passport.authenticate.callsArgWith(1, @err)
  99. it 'should return next with an error', () ->
  100. @AuthenticationController.passportLogin @req, @res, @next
  101. @next.calledWith(@err).should.equal true
  102. describe 'when authenticate produces a user', ->
  103. beforeEach ->
  104. @req.session.postLoginRedirect = 'some_redirect'
  105. @passport.authenticate.callsArgWith(1, null, @user, @info)
  106. afterEach ->
  107. delete @req.session.postLoginRedirect
  108. it 'should call finishLogin', () ->
  109. @AuthenticationController.passportLogin @req, @res, @next
  110. @AuthenticationController.finishLogin.callCount.should.equal 1
  111. @AuthenticationController.finishLogin.calledWith(@user).should.equal true
  112. describe 'when authenticate does not produce a user', ->
  113. beforeEach ->
  114. @info = {text: 'a', type: 'b'}
  115. @passport.authenticate.callsArgWith(1, null, false, @info)
  116. it 'should not call finishLogin', () ->
  117. @AuthenticationController.passportLogin @req, @res, @next
  118. @AuthenticationController.finishLogin.callCount.should.equal 0
  119. it 'should not send a json response with redirect', () ->
  120. @AuthenticationController.passportLogin @req, @res, @next
  121. @res.json.callCount.should.equal 1
  122. @res.json.calledWith({message: @info}).should.equal true
  123. expect(@res.json.lastCall.args[0].redir?).to.equal false
  124. describe 'afterLoginSessionSetup', ->
  125. beforeEach ->
  126. @req.login = sinon.stub().callsArgWith(1, null)
  127. @req.session = @session = {passport: {user: @user}}
  128. @req.session =
  129. passport: {user: {_id: "one"}}
  130. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  131. @req.session.save = sinon.stub().callsArgWith(0, null)
  132. @req.sessionStore = {generate: sinon.stub()}
  133. @UserSessionsManager.trackSession = sinon.stub()
  134. @call = (callback) =>
  135. @AuthenticationController.afterLoginSessionSetup @req, @user, callback
  136. it 'should not produce an error', (done) ->
  137. @call (err) =>
  138. expect(err).to.equal null
  139. done()
  140. it 'should call req.login', (done) ->
  141. @call (err) =>
  142. @req.login.callCount.should.equal 1
  143. done()
  144. it 'should call req.session.save', (done) ->
  145. @call (err) =>
  146. @req.session.save.callCount.should.equal 1
  147. done()
  148. it 'should call UserSessionsManager.trackSession', (done) ->
  149. @call (err) =>
  150. @UserSessionsManager.trackSession.callCount.should.equal 1
  151. done()
  152. describe 'when req.session.save produces an error', ->
  153. beforeEach ->
  154. @req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  155. it 'should produce an error', (done) ->
  156. @call (err) =>
  157. expect(err).to.not.be.oneOf [null, undefined]
  158. expect(err).to.be.instanceof Error
  159. done()
  160. it 'should not call UserSessionsManager.trackSession', (done) ->
  161. @call (err) =>
  162. @UserSessionsManager.trackSession.callCount.should.equal 0
  163. done()
  164. describe 'getSessionUser', ->
  165. it 'should get the user object from session', ->
  166. @req.session =
  167. passport:
  168. user: {_id: 'one'}
  169. user = @AuthenticationController.getSessionUser(@req)
  170. expect(user).to.deep.equal {_id: 'one'}
  171. it 'should work with legacy sessions', ->
  172. @req.session =
  173. user: {_id: 'one'}
  174. user = @AuthenticationController.getSessionUser(@req)
  175. expect(user).to.deep.equal {_id: 'one'}
  176. describe "doPassportLogin", ->
  177. beforeEach ->
  178. @AuthenticationController._recordFailedLogin = sinon.stub()
  179. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  180. # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  181. @req.body =
  182. email: @email
  183. password: @password
  184. session:
  185. postLoginRedirect: "/path/to/redir/to"
  186. @cb = sinon.stub()
  187. describe "when the users rate limit", ->
  188. beforeEach ->
  189. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  190. it "should block the request if the limit has been exceeded", (done)->
  191. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  192. @cb.callCount.should.equal 1
  193. @cb.calledWith(null, null).should.equal true
  194. done()
  195. describe 'when the user is authenticated', ->
  196. beforeEach ->
  197. @cb = sinon.stub()
  198. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  199. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  200. @req.sessionID = Math.random()
  201. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  202. it "should attempt to authorise the user", ->
  203. @AuthenticationManager.authenticate
  204. .calledWith(email: @email.toLowerCase(), @password)
  205. .should.equal true
  206. it "should establish the user's session", ->
  207. @cb.calledWith(null, @user).should.equal true
  208. # TODO: move these to a test for the async handlers, or for finishLogin
  209. # it "should call identifyUser", ->
  210. # @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true
  211. # it "should setup the user data in the background", ->
  212. # @UserHandler.setupLoginData.calledWith(@user).should.equal true
  213. # it "should set res.session.justLoggedIn", ->
  214. # @req.session.justLoggedIn.should.equal true
  215. # it "should record the successful login", ->
  216. # @AuthenticationController._recordSuccessfulLogin
  217. # .calledWith(@user._id)
  218. # .should.equal true
  219. # it "should tell the rate limiter that there was a success for that email", ->
  220. # @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true
  221. # it "should log the successful login", ->
  222. # @logger.log
  223. # .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in")
  224. # .should.equal true
  225. # it "should track the login event", ->
  226. # @AnalyticsManager.recordEvent
  227. # .calledWith(@user._id, "user-logged-in")
  228. # .should.equal true
  229. describe 'when the user is not authenticated', ->
  230. beforeEach ->
  231. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  232. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  233. @cb = sinon.stub()
  234. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  235. it "should not establish the login", ->
  236. @cb.callCount.should.equal 1
  237. @cb.calledWith(null, false)
  238. # @res.body.should.exist
  239. expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type']
  240. # message:
  241. # text: 'Your email or password were incorrect. Please try again',
  242. # type: 'error'
  243. it "should not setup the user data in the background", ->
  244. @UserHandler.setupLoginData.called.should.equal false
  245. it "should record a failed login", ->
  246. @AuthenticationController._recordFailedLogin.called.should.equal true
  247. it "should log the failed login", ->
  248. @logger.log
  249. .calledWith(email: @email.toLowerCase(), "failed log in")
  250. .should.equal true
  251. describe "getLoggedInUserId", ->
  252. beforeEach ->
  253. @req =
  254. session :{}
  255. it "should return the user id from the session", ()->
  256. @user_id = "2134"
  257. @req.session.user =
  258. _id:@user_id
  259. result = @AuthenticationController.getLoggedInUserId @req
  260. expect(result).to.equal @user_id
  261. it 'should return user for passport session', () ->
  262. @user_id = "2134"
  263. @req.session = {
  264. passport: {
  265. user: {
  266. _id:@user_id
  267. }
  268. }
  269. }
  270. result = @AuthenticationController.getLoggedInUserId @req
  271. expect(result).to.equal @user_id
  272. it "should return null if there is no user on the session", ()->
  273. result = @AuthenticationController.getLoggedInUserId @req
  274. expect(result).to.equal null
  275. it "should return null if there is no session", ()->
  276. @req = {}
  277. result = @AuthenticationController.getLoggedInUserId @req
  278. expect(result).to.equal null
  279. it "should return null if there is no req", ()->
  280. @req = {}
  281. result = @AuthenticationController.getLoggedInUserId @req
  282. expect(result).to.equal null
  283. describe "requireLogin", ->
  284. beforeEach ->
  285. @user =
  286. _id: "user-id-123"
  287. email: "user@sharelatex.com"
  288. @middleware = @AuthenticationController.requireLogin()
  289. describe "when the user is logged in", ->
  290. beforeEach ->
  291. @req.session =
  292. user: @user = {
  293. _id: "user-id-123"
  294. email: "user@sharelatex.com"
  295. }
  296. @middleware(@req, @res, @next)
  297. it "should call the next method in the chain", ->
  298. @next.called.should.equal true
  299. describe "when the user is not logged in", ->
  300. beforeEach ->
  301. @req.session = {}
  302. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  303. @req.query = {}
  304. @middleware(@req, @res, @next)
  305. it "should redirect to the register or login page", ->
  306. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  307. describe "requireGlobalLogin", ->
  308. beforeEach ->
  309. @req.headers = {}
  310. @AuthenticationController.httpAuth = sinon.stub()
  311. @_setRedirect = sinon.spy(@AuthenticationController, '_setRedirectInSession')
  312. afterEach ->
  313. @_setRedirect.restore()
  314. describe "with white listed url", ->
  315. beforeEach ->
  316. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  317. @req._parsedUrl.pathname = "/login"
  318. @AuthenticationController.requireGlobalLogin @req, @res, @next
  319. it "should call next() directly", ->
  320. @next.called.should.equal true
  321. describe "with white listed url and a query string", ->
  322. beforeEach ->
  323. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  324. @req._parsedUrl.pathname = "/login"
  325. @req.url = "/login?query=something"
  326. @AuthenticationController.requireGlobalLogin @req, @res, @next
  327. it "should call next() directly", ->
  328. @next.called.should.equal true
  329. describe "with http auth", ->
  330. beforeEach ->
  331. @req.headers["authorization"] = "Mock Basic Auth"
  332. @AuthenticationController.requireGlobalLogin @req, @res, @next
  333. it "should pass the request onto httpAuth", ->
  334. @AuthenticationController.httpAuth
  335. .calledWith(@req, @res, @next)
  336. .should.equal true
  337. describe "with a user session", ->
  338. beforeEach ->
  339. @req.session =
  340. user: {"mock": "user", "_id": "some_id"}
  341. @AuthenticationController.requireGlobalLogin @req, @res, @next
  342. it "should call next() directly", ->
  343. @next.called.should.equal true
  344. describe "with no login credentials", ->
  345. beforeEach ->
  346. @req.session = {}
  347. @AuthenticationController.requireGlobalLogin @req, @res, @next
  348. it 'should have called setRedirectInSession', ->
  349. @_setRedirect.callCount.should.equal 1
  350. it "should redirect to the /login page", ->
  351. @res.redirectedTo.should.equal "/login"
  352. describe "_redirectToLoginOrRegisterPage", ->
  353. beforeEach ->
  354. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  355. @req.session = {}
  356. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  357. @AuthenticationController._redirectToLoginPage = sinon.stub()
  358. @req.query = {}
  359. describe "they have come directly to the url", ->
  360. beforeEach ->
  361. @req.query = {}
  362. @middleware(@req, @res, @next)
  363. it "should redirect to the login page", ->
  364. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  365. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  366. describe "they have come via a templates link", ->
  367. beforeEach ->
  368. @req.query.zipUrl = "something"
  369. @middleware(@req, @res, @next)
  370. it "should redirect to the register page", ->
  371. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  372. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  373. describe "they have been invited to a project", ->
  374. beforeEach ->
  375. @req.query.project_name = "something"
  376. @middleware(@req, @res, @next)
  377. it "should redirect to the register page", ->
  378. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  379. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  380. describe "_redirectToRegisterPage", ->
  381. beforeEach ->
  382. @req.path = "/target/url"
  383. @req.query =
  384. extra_query: "foo"
  385. @AuthenticationController._redirectToRegisterPage(@req, @res)
  386. it "should redirect to the register page with a query string attached", ->
  387. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  388. @res.redirectedTo.should.equal "/register?extra_query=foo"
  389. it "should log out a message", ->
  390. @logger.log
  391. .calledWith(url: @url, "user not logged in so redirecting to register page")
  392. .should.equal true
  393. describe "_redirectToLoginPage", ->
  394. beforeEach ->
  395. @req.path = "/target/url"
  396. @req.query =
  397. extra_query: "foo"
  398. @AuthenticationController._redirectToLoginPage(@req, @res)
  399. it "should redirect to the register page with a query string attached", ->
  400. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  401. @res.redirectedTo.should.equal "/login?extra_query=foo"
  402. describe "_recordSuccessfulLogin", ->
  403. beforeEach ->
  404. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  405. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  406. it "should increment the user.login.success metric", ->
  407. @Metrics.inc
  408. .calledWith("user.login.success")
  409. .should.equal true
  410. it "should update the user's login count and last logged in date", ->
  411. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  412. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  413. it "should call the callback", ->
  414. @callback.called.should.equal true
  415. describe "_recordFailedLogin", ->
  416. beforeEach ->
  417. @AuthenticationController._recordFailedLogin(@callback)
  418. it "should increment the user.login.failed metric", ->
  419. @Metrics.inc
  420. .calledWith("user.login.failed")
  421. .should.equal true
  422. it "should call the callback", ->
  423. @callback.called.should.equal true
  424. describe '_setRedirectInSession', ->
  425. beforeEach ->
  426. @req = {session: {}}
  427. @req.path = "/somewhere"
  428. @req.query = {one: "1"}
  429. it 'should set redirect property on session', ->
  430. @AuthenticationController._setRedirectInSession(@req)
  431. expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1"
  432. it 'should set the supplied value', ->
  433. @AuthenticationController._setRedirectInSession(@req, '/somewhere/specific')
  434. expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific"
  435. describe 'with a png', ->
  436. beforeEach ->
  437. @req = {session: {}}
  438. it 'should not set the redirect', ->
  439. @AuthenticationController._setRedirectInSession(@req, '/something.png')
  440. expect(@req.session.postLoginRedirect).to.equal undefined
  441. describe 'with a js path', ->
  442. beforeEach ->
  443. @req = {session: {}}
  444. it 'should not set the redirect', ->
  445. @AuthenticationController._setRedirectInSession(@req, '/js/something.js')
  446. expect(@req.session.postLoginRedirect).to.equal undefined
  447. describe '_getRedirectFromSession', ->
  448. beforeEach ->
  449. @req = {session: {postLoginRedirect: "/a?b=c"}}
  450. it 'should get redirect property from session', ->
  451. expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c"
  452. describe '_clearRedirectFromSession', ->
  453. beforeEach ->
  454. @req = {session: {postLoginRedirect: "/a?b=c"}}
  455. it 'should remove the redirect property from session', ->
  456. @AuthenticationController._clearRedirectFromSession(@req)
  457. expect(@req.session.postLoginRedirect).to.equal undefined