AuthenticationControllerTests.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const modulePath =
  5. '../../../../app/src/Features/Authentication/AuthenticationController.js'
  6. const SandboxedModule = require('sandboxed-module')
  7. const tk = require('timekeeper')
  8. const MockRequest = require('../helpers/MockRequest')
  9. const MockResponse = require('../helpers/MockResponse')
  10. const { ObjectId } = require('mongojs')
  11. describe('AuthenticationController', function() {
  12. beforeEach(function() {
  13. tk.freeze(Date.now())
  14. this.UserModel = { findOne: sinon.stub() }
  15. this.httpAuthUsers = {
  16. 'valid-test-user': Math.random()
  17. .toString(16)
  18. .slice(2)
  19. }
  20. this.AuthenticationController = SandboxedModule.require(modulePath, {
  21. globals: {
  22. console: console
  23. },
  24. requires: {
  25. '../Helpers/AsyncFormHelper': (this.AsyncFormHelper = {
  26. redirect: sinon.stub()
  27. }),
  28. '../../infrastructure/RequestContentTypeDetection': {
  29. acceptsJson: (this.acceptsJson = sinon.stub().returns(false))
  30. },
  31. './AuthenticationManager': (this.AuthenticationManager = {}),
  32. '../User/UserUpdater': (this.UserUpdater = {
  33. updateUser: sinon.stub()
  34. }),
  35. 'metrics-sharelatex': (this.Metrics = { inc: sinon.stub() }),
  36. '../Security/LoginRateLimiter': (this.LoginRateLimiter = {
  37. processLoginRequest: sinon.stub(),
  38. recordSuccessfulLogin: sinon.stub()
  39. }),
  40. '../User/UserHandler': (this.UserHandler = {
  41. setupLoginData: sinon.stub()
  42. }),
  43. '../Analytics/AnalyticsManager': (this.AnalyticsManager = {
  44. recordEvent: sinon.stub(),
  45. identifyUser: sinon.stub()
  46. }),
  47. '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = {}),
  48. 'logger-sharelatex': (this.logger = {
  49. log: sinon.stub(),
  50. warn: sinon.stub(),
  51. error: sinon.stub(),
  52. err: sinon.stub()
  53. }),
  54. 'settings-sharelatex': (this.Settings = {
  55. siteUrl: 'http://www.foo.bar',
  56. httpAuthUsers: this.httpAuthUsers
  57. }),
  58. passport: (this.passport = {
  59. authenticate: sinon.stub().returns(sinon.stub())
  60. }),
  61. '../User/UserSessionsManager': (this.UserSessionsManager = {
  62. trackSession: sinon.stub(),
  63. untrackSession: sinon.stub(),
  64. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  65. }),
  66. '../../infrastructure/Modules': (this.Modules = {
  67. hooks: { fire: sinon.stub().yields(null, []) }
  68. }),
  69. '../SudoMode/SudoModeHandler': (this.SudoModeHandler = {
  70. activateSudoMode: sinon.stub().callsArgWith(1, null)
  71. }),
  72. '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
  73. ipMatcherAffiliation: sinon.stub()
  74. }),
  75. '../../models/User': { User: this.UserModel },
  76. '../../../../modules/oauth2-server/app/src/Oauth2Server': (this.Oauth2Server = {
  77. Request: sinon.stub(),
  78. Response: sinon.stub(),
  79. server: {
  80. authenticate: sinon.stub()
  81. }
  82. }),
  83. '../Helpers/UrlHelper': (this.UrlHelper = {
  84. getSafeRedirectPath: sinon.stub()
  85. })
  86. }
  87. })
  88. this.UrlHelper.getSafeRedirectPath
  89. .withArgs('https://evil.com')
  90. .returns(undefined)
  91. this.UrlHelper.getSafeRedirectPath.returnsArg(0)
  92. this.user = {
  93. _id: ObjectId(),
  94. email: (this.email = 'USER@example.com'),
  95. first_name: 'bob',
  96. last_name: 'brown',
  97. referal_id: 1234,
  98. isAdmin: false
  99. }
  100. this.password = 'banana'
  101. this.req = new MockRequest()
  102. this.res = new MockResponse()
  103. this.callback = sinon.stub()
  104. this.next = sinon.stub()
  105. })
  106. afterEach(function() {
  107. tk.reset()
  108. })
  109. describe('validateAdmin', function() {
  110. beforeEach(function() {
  111. this.Settings.adminDomains = ['good.example.com']
  112. this.goodAdmin = {
  113. email: 'alice@good.example.com',
  114. isAdmin: true
  115. }
  116. this.badAdmin = {
  117. email: 'beatrice@bad.example.com',
  118. isAdmin: true
  119. }
  120. this.normalUser = {
  121. email: 'claire@whatever.example.com',
  122. isAdmin: false
  123. }
  124. })
  125. it('should skip when adminDomains are not configured', function(done) {
  126. this.Settings.adminDomains = []
  127. this.AuthenticationController.getSessionUser = sinon
  128. .stub()
  129. .returns(this.normalUser)
  130. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  131. this.AuthenticationController.getSessionUser.called.should.equal(false)
  132. expect(err).to.not.exist
  133. done()
  134. })
  135. })
  136. it('should skip non-admin user', function(done) {
  137. this.AuthenticationController.getSessionUser = sinon
  138. .stub()
  139. .returns(this.normalUser)
  140. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  141. this.AuthenticationController.getSessionUser.called.should.equal(true)
  142. expect(err).to.not.exist
  143. done()
  144. })
  145. })
  146. it('should permit an admin with the right doman', function(done) {
  147. this.AuthenticationController.getSessionUser = sinon
  148. .stub()
  149. .returns(this.goodAdmin)
  150. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  151. this.AuthenticationController.getSessionUser.called.should.equal(true)
  152. expect(err).to.not.exist
  153. done()
  154. })
  155. })
  156. it('should block an admin with a missing email', function(done) {
  157. this.AuthenticationController.getSessionUser = sinon
  158. .stub()
  159. .returns({ isAdmin: true })
  160. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  161. this.AuthenticationController.getSessionUser.called.should.equal(true)
  162. expect(err).to.exist
  163. done()
  164. })
  165. })
  166. it('should block an admin with a bad domain', function(done) {
  167. this.AuthenticationController.getSessionUser = sinon
  168. .stub()
  169. .returns(this.badAdmin)
  170. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  171. this.AuthenticationController.getSessionUser.called.should.equal(true)
  172. expect(err).to.exist
  173. done()
  174. })
  175. })
  176. })
  177. describe('isUserLoggedIn', function() {
  178. beforeEach(function() {
  179. this.stub = sinon.stub(this.AuthenticationController, 'getLoggedInUserId')
  180. })
  181. afterEach(function() {
  182. this.stub.restore()
  183. })
  184. it('should do the right thing in all cases', function() {
  185. this.AuthenticationController.getLoggedInUserId.returns('some_id')
  186. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  187. true
  188. )
  189. this.AuthenticationController.getLoggedInUserId.returns(null)
  190. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  191. false
  192. )
  193. this.AuthenticationController.getLoggedInUserId.returns(false)
  194. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  195. false
  196. )
  197. this.AuthenticationController.getLoggedInUserId.returns(undefined)
  198. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  199. false
  200. )
  201. })
  202. })
  203. describe('setInSessionUser', function() {
  204. beforeEach(function() {
  205. this.user = {
  206. _id: 'id',
  207. first_name: 'a',
  208. last_name: 'b',
  209. email: 'c'
  210. }
  211. this.AuthenticationController.getSessionUser = sinon
  212. .stub()
  213. .returns(this.user)
  214. })
  215. it('should update the right properties', function() {
  216. this.AuthenticationController.setInSessionUser(this.req, {
  217. first_name: 'new_first_name',
  218. email: 'new_email'
  219. })
  220. const expectedUser = {
  221. _id: 'id',
  222. first_name: 'new_first_name',
  223. last_name: 'b',
  224. email: 'new_email'
  225. }
  226. expect(this.user).to.deep.equal(expectedUser)
  227. expect(this.user).to.deep.equal(expectedUser)
  228. })
  229. })
  230. describe('passportLogin', function() {
  231. beforeEach(function() {
  232. this.info = null
  233. this.req.login = sinon.stub().callsArgWith(1, null)
  234. this.res.json = sinon.stub()
  235. this.req.session = {
  236. passport: { user: this.user },
  237. postLoginRedirect: '/path/to/redir/to'
  238. }
  239. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  240. this.req.session.save = sinon.stub().callsArgWith(0, null)
  241. this.req.sessionStore = { generate: sinon.stub() }
  242. this.AuthenticationController.finishLogin = sinon.stub()
  243. this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
  244. this.err = new Error('woops')
  245. })
  246. it('should call passport.authenticate', function() {
  247. this.AuthenticationController.passportLogin(this.req, this.res, this.next)
  248. this.passport.authenticate.callCount.should.equal(1)
  249. })
  250. describe('when authenticate produces an error', function() {
  251. beforeEach(function() {
  252. this.passport.authenticate.callsArgWith(1, this.err)
  253. })
  254. it('should return next with an error', function() {
  255. this.AuthenticationController.passportLogin(
  256. this.req,
  257. this.res,
  258. this.next
  259. )
  260. this.next.calledWith(this.err).should.equal(true)
  261. })
  262. })
  263. describe('when authenticate produces a user', function() {
  264. beforeEach(function() {
  265. this.req.session.postLoginRedirect = 'some_redirect'
  266. this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
  267. })
  268. afterEach(function() {
  269. delete this.req.session.postLoginRedirect
  270. })
  271. it('should call finishLogin', function() {
  272. this.AuthenticationController.passportLogin(
  273. this.req,
  274. this.res,
  275. this.next
  276. )
  277. this.AuthenticationController.finishLogin.callCount.should.equal(1)
  278. this.AuthenticationController.finishLogin
  279. .calledWith(this.user)
  280. .should.equal(true)
  281. })
  282. })
  283. describe('when authenticate does not produce a user', function() {
  284. beforeEach(function() {
  285. this.info = { text: 'a', type: 'b' }
  286. this.passport.authenticate.callsArgWith(1, null, false, this.info)
  287. })
  288. it('should not call finishLogin', function() {
  289. this.AuthenticationController.passportLogin(
  290. this.req,
  291. this.res,
  292. this.next
  293. )
  294. this.AuthenticationController.finishLogin.callCount.should.equal(0)
  295. })
  296. it('should not send a json response with redirect', function() {
  297. this.AuthenticationController.passportLogin(
  298. this.req,
  299. this.res,
  300. this.next
  301. )
  302. this.res.json.callCount.should.equal(1)
  303. this.res.json.calledWith({ message: this.info }).should.equal(true)
  304. expect(this.res.json.lastCall.args[0].redir != null).to.equal(false)
  305. })
  306. })
  307. })
  308. describe('doPassportLogin', function() {
  309. beforeEach(function() {
  310. this.AuthenticationController._recordFailedLogin = sinon.stub()
  311. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  312. this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
  313. // @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  314. this.req.body = {
  315. email: this.email,
  316. password: this.password,
  317. session: {
  318. postLoginRedirect: '/path/to/redir/to'
  319. }
  320. }
  321. this.cb = sinon.stub()
  322. })
  323. describe('when the preDoPassportLogin hooks produce an info object', function() {
  324. beforeEach(function() {
  325. this.Modules.hooks.fire = sinon
  326. .stub()
  327. .callsArgWith(3, null, [null, { redir: '/somewhere' }, null])
  328. })
  329. it('should stop early and call done with this info object', function(done) {
  330. this.AuthenticationController.doPassportLogin(
  331. this.req,
  332. this.req.body.email,
  333. this.req.body.password,
  334. this.cb
  335. )
  336. this.cb.callCount.should.equal(1)
  337. this.cb
  338. .calledWith(null, false, { redir: '/somewhere' })
  339. .should.equal(true)
  340. this.LoginRateLimiter.processLoginRequest.callCount.should.equal(0)
  341. done()
  342. })
  343. })
  344. describe('when the users rate limit', function() {
  345. beforeEach(function() {
  346. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  347. })
  348. it('should block the request if the limit has been exceeded', function(done) {
  349. this.AuthenticationController.doPassportLogin(
  350. this.req,
  351. this.req.body.email,
  352. this.req.body.password,
  353. this.cb
  354. )
  355. this.cb.callCount.should.equal(1)
  356. this.cb.calledWith(null, null).should.equal(true)
  357. done()
  358. })
  359. })
  360. describe('when the user is authenticated', function() {
  361. beforeEach(function() {
  362. this.cb = sinon.stub()
  363. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  364. this.AuthenticationManager.authenticate = sinon
  365. .stub()
  366. .callsArgWith(2, null, this.user)
  367. this.req.sessionID = Math.random()
  368. this.AuthenticationController.doPassportLogin(
  369. this.req,
  370. this.req.body.email,
  371. this.req.body.password,
  372. this.cb
  373. )
  374. })
  375. it('should attempt to authorise the user', function() {
  376. this.AuthenticationManager.authenticate
  377. .calledWith({ email: this.email.toLowerCase() }, this.password)
  378. .should.equal(true)
  379. })
  380. it("should establish the user's session", function() {
  381. this.cb.calledWith(null, this.user).should.equal(true)
  382. })
  383. })
  384. describe('when the user is not authenticated', function() {
  385. beforeEach(function() {
  386. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  387. this.AuthenticationManager.authenticate = sinon
  388. .stub()
  389. .callsArgWith(2, null, null)
  390. this.cb = sinon.stub()
  391. this.AuthenticationController.doPassportLogin(
  392. this.req,
  393. this.req.body.email,
  394. this.req.body.password,
  395. this.cb
  396. )
  397. })
  398. it('should not establish the login', function() {
  399. this.cb.callCount.should.equal(1)
  400. this.cb.calledWith(null, false)
  401. // @res.body.should.exist
  402. expect(this.cb.lastCall.args[2]).to.contain.all.keys(['text', 'type'])
  403. })
  404. // message:
  405. // text: 'Your email or password were incorrect. Please try again',
  406. // type: 'error'
  407. it('should not setup the user data in the background', function() {
  408. this.UserHandler.setupLoginData.called.should.equal(false)
  409. })
  410. it('should record a failed login', function() {
  411. this.AuthenticationController._recordFailedLogin.called.should.equal(
  412. true
  413. )
  414. })
  415. it('should log the failed login', function() {
  416. this.logger.log
  417. .calledWith({ email: this.email.toLowerCase() }, 'failed log in')
  418. .should.equal(true)
  419. })
  420. })
  421. })
  422. describe('getLoggedInUserId', function() {
  423. beforeEach(function() {
  424. this.req = { session: {} }
  425. })
  426. it('should return the user id from the session', function() {
  427. this.user_id = '2134'
  428. this.req.session.user = { _id: this.user_id }
  429. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  430. expect(result).to.equal(this.user_id)
  431. })
  432. it('should return user for passport session', function() {
  433. this.user_id = '2134'
  434. this.req.session = {
  435. passport: {
  436. user: {
  437. _id: this.user_id
  438. }
  439. }
  440. }
  441. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  442. expect(result).to.equal(this.user_id)
  443. })
  444. it('should return null if there is no user on the session', function() {
  445. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  446. expect(result).to.equal(null)
  447. })
  448. it('should return null if there is no session', function() {
  449. this.req = {}
  450. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  451. expect(result).to.equal(null)
  452. })
  453. it('should return null if there is no req', function() {
  454. this.req = {}
  455. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  456. expect(result).to.equal(null)
  457. })
  458. })
  459. describe('requireLogin', function() {
  460. beforeEach(function() {
  461. this.user = {
  462. _id: 'user-id-123',
  463. email: 'user@sharelatex.com'
  464. }
  465. this.middleware = this.AuthenticationController.requireLogin()
  466. })
  467. describe('when the user is logged in', function() {
  468. beforeEach(function() {
  469. this.req.session = {
  470. user: (this.user = {
  471. _id: 'user-id-123',
  472. email: 'user@sharelatex.com'
  473. })
  474. }
  475. this.middleware(this.req, this.res, this.next)
  476. })
  477. it('should call the next method in the chain', function() {
  478. this.next.called.should.equal(true)
  479. })
  480. })
  481. describe('when the user is not logged in', function() {
  482. beforeEach(function() {
  483. this.req.session = {}
  484. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  485. this.req.query = {}
  486. this.middleware(this.req, this.res, this.next)
  487. })
  488. it('should redirect to the register or login page', function() {
  489. this.AuthenticationController._redirectToLoginOrRegisterPage
  490. .calledWith(this.req, this.res)
  491. .should.equal(true)
  492. })
  493. })
  494. })
  495. describe('validateUserSession', function() {
  496. beforeEach(function() {
  497. this.user = {
  498. _id: 'user-id-123',
  499. email: 'user@sharelatex.com'
  500. }
  501. this.middleware = this.AuthenticationController.validateUserSession()
  502. })
  503. describe('when the user has a session token', function() {
  504. beforeEach(function() {
  505. this.req.user = this.user
  506. this.SessionStoreManager.hasValidationToken = sinon.stub().returns(true)
  507. this.middleware(this.req, this.res, this.next)
  508. })
  509. it('should call the next method in the chain', function() {
  510. this.next.called.should.equal(true)
  511. })
  512. })
  513. describe('when the user does not have a session token', function() {
  514. beforeEach(function() {
  515. this.req.session = {
  516. user: this.user,
  517. regenerate: sinon.stub().yields()
  518. }
  519. this.req.user = this.user
  520. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  521. this.req.query = {}
  522. this.SessionStoreManager.hasValidationToken = sinon
  523. .stub()
  524. .returns(false)
  525. this.middleware(this.req, this.res, this.next)
  526. })
  527. it('should destroy the current session', function() {
  528. this.req.session.regenerate.called.should.equal(true)
  529. })
  530. it('should redirect to the register or login page', function() {
  531. this.AuthenticationController._redirectToLoginOrRegisterPage
  532. .calledWith(this.req, this.res)
  533. .should.equal(true)
  534. })
  535. })
  536. })
  537. describe('requireOauth', function() {
  538. beforeEach(function() {
  539. this.res.send = sinon.stub()
  540. this.res.status = sinon.stub().returns(this.res)
  541. this.res.sendStatus = sinon.stub()
  542. this.middleware = this.AuthenticationController.requireOauth()
  543. })
  544. describe('when Oauth2Server authenticates', function() {
  545. beforeEach(function() {
  546. this.token = {
  547. accessToken: 'token',
  548. user: 'user'
  549. }
  550. this.Oauth2Server.server.authenticate.yields(null, this.token)
  551. this.middleware(this.req, this.res, this.next)
  552. })
  553. it('should set oauth_token on request', function() {
  554. this.req.oauth_token.should.equal(this.token)
  555. })
  556. it('should set oauth on request', function() {
  557. this.req.oauth.access_token.should.equal(this.token.accessToken)
  558. })
  559. it('should set oauth_user on request', function() {
  560. this.req.oauth_user.should.equal('user')
  561. })
  562. it('should call next', function() {
  563. this.next.should.have.been.calledOnce
  564. })
  565. })
  566. describe('when Oauth2Server returns 401 error', function() {
  567. beforeEach(function() {
  568. this.Oauth2Server.server.authenticate.yields({ code: 401 })
  569. this.middleware(this.req, this.res, this.next)
  570. })
  571. it('should return 401 error', function() {
  572. this.res.status.should.have.been.calledWith(401)
  573. })
  574. it('should not call next', function() {
  575. this.next.should.have.not.been.calledOnce
  576. })
  577. })
  578. })
  579. describe('requireGlobalLogin', function() {
  580. beforeEach(function() {
  581. this.req.headers = {}
  582. this.AuthenticationController.httpAuth = sinon.stub()
  583. this.setRedirect = sinon.spy(
  584. this.AuthenticationController,
  585. 'setRedirectInSession'
  586. )
  587. })
  588. afterEach(function() {
  589. this.setRedirect.restore()
  590. })
  591. describe('with white listed url', function() {
  592. beforeEach(function() {
  593. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  594. this.req._parsedUrl.pathname = '/login'
  595. this.AuthenticationController.requireGlobalLogin(
  596. this.req,
  597. this.res,
  598. this.next
  599. )
  600. })
  601. it('should call next() directly', function() {
  602. this.next.called.should.equal(true)
  603. })
  604. })
  605. describe('with white listed url and a query string', function() {
  606. beforeEach(function() {
  607. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  608. this.req._parsedUrl.pathname = '/login'
  609. this.req.url = '/login?query=something'
  610. this.AuthenticationController.requireGlobalLogin(
  611. this.req,
  612. this.res,
  613. this.next
  614. )
  615. })
  616. it('should call next() directly', function() {
  617. this.next.called.should.equal(true)
  618. })
  619. })
  620. describe('with http auth', function() {
  621. beforeEach(function() {
  622. this.req.headers['authorization'] = 'Mock Basic Auth'
  623. this.AuthenticationController.requireGlobalLogin(
  624. this.req,
  625. this.res,
  626. this.next
  627. )
  628. })
  629. it('should pass the request onto httpAuth', function() {
  630. this.AuthenticationController.httpAuth
  631. .calledWith(this.req, this.res, this.next)
  632. .should.equal(true)
  633. })
  634. })
  635. describe('with a user session', function() {
  636. beforeEach(function() {
  637. this.req.session = { user: { mock: 'user', _id: 'some_id' } }
  638. this.AuthenticationController.requireGlobalLogin(
  639. this.req,
  640. this.res,
  641. this.next
  642. )
  643. })
  644. it('should call next() directly', function() {
  645. this.next.called.should.equal(true)
  646. })
  647. })
  648. describe('with no login credentials', function() {
  649. beforeEach(function() {
  650. this.req.session = {}
  651. this.AuthenticationController.requireGlobalLogin(
  652. this.req,
  653. this.res,
  654. this.next
  655. )
  656. })
  657. it('should have called setRedirectInSession', function() {
  658. this.setRedirect.callCount.should.equal(1)
  659. })
  660. it('should redirect to the /login page', function() {
  661. this.res.redirectedTo.should.equal('/login')
  662. })
  663. })
  664. })
  665. describe('httpAuth', function() {
  666. describe('with http auth', function() {
  667. it('should error with incorrect user', function(done) {
  668. this.req.headers = {
  669. authorization: `Basic ${Buffer.from('user:nope').toString('base64')}`
  670. }
  671. this.req.end = status => {
  672. expect(status).to.equal('Unauthorized')
  673. done()
  674. }
  675. this.AuthenticationController.httpAuth(this.req, this.req)
  676. })
  677. it('should error with incorrect password', function(done) {
  678. this.req.headers = {
  679. authorization: `Basic ${Buffer.from('valid-test-user:nope').toString(
  680. 'base64'
  681. )}`
  682. }
  683. this.req.end = status => {
  684. expect(status).to.equal('Unauthorized')
  685. done()
  686. }
  687. this.AuthenticationController.httpAuth(this.req, this.req)
  688. })
  689. it('should fail with empty pass', function(done) {
  690. this.req.headers = {
  691. authorization: `Basic ${Buffer.from(`invalid-test-user:`).toString(
  692. 'base64'
  693. )}`
  694. }
  695. this.req.end = status => {
  696. expect(status).to.equal('Unauthorized')
  697. done()
  698. }
  699. this.AuthenticationController.httpAuth(this.req, this.req)
  700. })
  701. it('should succeed with correct user/pass', function(done) {
  702. this.req.headers = {
  703. authorization: `Basic ${Buffer.from(
  704. `valid-test-user:${this.httpAuthUsers['valid-test-user']}`
  705. ).toString('base64')}`
  706. }
  707. this.AuthenticationController.httpAuth(this.req, this.res, done)
  708. })
  709. })
  710. })
  711. describe('_redirectToLoginOrRegisterPage', function() {
  712. beforeEach(function() {
  713. this.middleware = this.AuthenticationController.requireLogin(
  714. (this.options = { load_from_db: false })
  715. )
  716. this.req.session = {}
  717. this.AuthenticationController._redirectToRegisterPage = sinon.stub()
  718. this.AuthenticationController._redirectToLoginPage = sinon.stub()
  719. this.req.query = {}
  720. })
  721. describe('they have come directly to the url', function() {
  722. beforeEach(function() {
  723. this.req.query = {}
  724. this.middleware(this.req, this.res, this.next)
  725. })
  726. it('should redirect to the login page', function() {
  727. this.AuthenticationController._redirectToRegisterPage
  728. .calledWith(this.req, this.res)
  729. .should.equal(false)
  730. this.AuthenticationController._redirectToLoginPage
  731. .calledWith(this.req, this.res)
  732. .should.equal(true)
  733. })
  734. })
  735. describe('they have come via a templates link', function() {
  736. beforeEach(function() {
  737. this.req.query.zipUrl = 'something'
  738. this.middleware(this.req, this.res, this.next)
  739. })
  740. it('should redirect to the register page', function() {
  741. this.AuthenticationController._redirectToRegisterPage
  742. .calledWith(this.req, this.res)
  743. .should.equal(true)
  744. this.AuthenticationController._redirectToLoginPage
  745. .calledWith(this.req, this.res)
  746. .should.equal(false)
  747. })
  748. })
  749. describe('they have been invited to a project', function() {
  750. beforeEach(function() {
  751. this.req.query.project_name = 'something'
  752. this.middleware(this.req, this.res, this.next)
  753. })
  754. it('should redirect to the register page', function() {
  755. this.AuthenticationController._redirectToRegisterPage
  756. .calledWith(this.req, this.res)
  757. .should.equal(true)
  758. this.AuthenticationController._redirectToLoginPage
  759. .calledWith(this.req, this.res)
  760. .should.equal(false)
  761. })
  762. })
  763. })
  764. describe('_redirectToRegisterPage', function() {
  765. beforeEach(function() {
  766. this.req.path = '/target/url'
  767. this.req.query = { extra_query: 'foo' }
  768. this.AuthenticationController._redirectToRegisterPage(this.req, this.res)
  769. })
  770. it('should redirect to the register page with a query string attached', function() {
  771. this.req.session.postLoginRedirect.should.equal(
  772. '/target/url?extra_query=foo'
  773. )
  774. this.res.redirectedTo.should.equal('/register?extra_query=foo')
  775. })
  776. it('should log out a message', function() {
  777. this.logger.log
  778. .calledWith(
  779. { url: this.url },
  780. 'user not logged in so redirecting to register page'
  781. )
  782. .should.equal(true)
  783. })
  784. })
  785. describe('_redirectToLoginPage', function() {
  786. beforeEach(function() {
  787. this.req.path = '/target/url'
  788. this.req.query = { extra_query: 'foo' }
  789. this.AuthenticationController._redirectToLoginPage(this.req, this.res)
  790. })
  791. it('should redirect to the register page with a query string attached', function() {
  792. this.req.session.postLoginRedirect.should.equal(
  793. '/target/url?extra_query=foo'
  794. )
  795. this.res.redirectedTo.should.equal('/login?extra_query=foo')
  796. })
  797. })
  798. describe('_recordSuccessfulLogin', function() {
  799. beforeEach(function() {
  800. this.UserUpdater.updateUser = sinon.stub().callsArg(2)
  801. this.AuthenticationController._recordSuccessfulLogin(
  802. this.user._id,
  803. this.callback
  804. )
  805. })
  806. it('should increment the user.login.success metric', function() {
  807. this.Metrics.inc.calledWith('user.login.success').should.equal(true)
  808. })
  809. it("should update the user's login count and last logged in date", function() {
  810. this.UserUpdater.updateUser.args[0][1]['$set'][
  811. 'lastLoggedIn'
  812. ].should.not.equal(undefined)
  813. this.UserUpdater.updateUser.args[0][1]['$inc']['loginCount'].should.equal(
  814. 1
  815. )
  816. })
  817. it('should call the callback', function() {
  818. this.callback.called.should.equal(true)
  819. })
  820. })
  821. describe('_recordFailedLogin', function() {
  822. beforeEach(function() {
  823. this.AuthenticationController._recordFailedLogin(this.callback)
  824. })
  825. it('should increment the user.login.failed metric', function() {
  826. this.Metrics.inc.calledWith('user.login.failed').should.equal(true)
  827. })
  828. it('should call the callback', function() {
  829. this.callback.called.should.equal(true)
  830. })
  831. })
  832. describe('setRedirectInSession', function() {
  833. beforeEach(function() {
  834. this.req = { session: {} }
  835. this.req.path = '/somewhere'
  836. this.req.query = { one: '1' }
  837. })
  838. it('should set redirect property on session', function() {
  839. this.AuthenticationController.setRedirectInSession(this.req)
  840. expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1')
  841. })
  842. it('should set the supplied value', function() {
  843. this.AuthenticationController.setRedirectInSession(
  844. this.req,
  845. '/somewhere/specific'
  846. )
  847. expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific')
  848. })
  849. it('should not allow open redirects', function() {
  850. this.AuthenticationController.setRedirectInSession(
  851. this.req,
  852. 'https://evil.com'
  853. )
  854. expect(this.req.session.postLoginRedirect).to.be.undefined
  855. })
  856. describe('with a png', function() {
  857. beforeEach(function() {
  858. this.req = { session: {} }
  859. })
  860. it('should not set the redirect', function() {
  861. this.AuthenticationController.setRedirectInSession(
  862. this.req,
  863. '/something.png'
  864. )
  865. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  866. })
  867. })
  868. describe('with a js path', function() {
  869. beforeEach(function() {
  870. this.req = { session: {} }
  871. })
  872. it('should not set the redirect', function() {
  873. this.AuthenticationController.setRedirectInSession(
  874. this.req,
  875. '/js/something.js'
  876. )
  877. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  878. })
  879. })
  880. })
  881. describe('_getRedirectFromSession', function() {
  882. it('should get redirect property from session', function() {
  883. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  884. expect(
  885. this.AuthenticationController._getRedirectFromSession(this.req)
  886. ).to.equal('/a?b=c')
  887. })
  888. it('should not allow open redirects', function() {
  889. this.req = { session: { postLoginRedirect: 'https://evil.com' } }
  890. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  891. .be.null
  892. })
  893. it('handle null values', function() {
  894. this.req = { session: {} }
  895. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  896. .be.null
  897. })
  898. })
  899. describe('_clearRedirectFromSession', function() {
  900. beforeEach(function() {
  901. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  902. })
  903. it('should remove the redirect property from session', function() {
  904. this.AuthenticationController._clearRedirectFromSession(this.req)
  905. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  906. })
  907. })
  908. describe('finishLogin', function() {
  909. // - get redirect
  910. // - async handlers
  911. // - afterLoginSessionSetup
  912. // - clear redirect
  913. // - issue redir, two ways
  914. beforeEach(function() {
  915. this.AuthenticationController._getRedirectFromSession = sinon
  916. .stub()
  917. .returns('/some/page')
  918. this.req.sessionID = 'thisisacryptographicallysecurerandomid'
  919. this.req.session = {
  920. passport: { user: { _id: 'one' } }
  921. }
  922. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  923. this.req.session.save = sinon.stub().callsArgWith(0, null)
  924. this.req.sessionStore = { generate: sinon.stub() }
  925. this.req.login = sinon.stub().yields(null)
  926. this.AuthenticationController._clearRedirectFromSession = sinon.stub()
  927. this.AuthenticationController._redirectToReconfirmPage = sinon.stub()
  928. this.UserSessionsManager.trackSession = sinon.stub()
  929. this.UserHandler.setupLoginData = sinon.stub()
  930. this.LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
  931. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  932. this.AnalyticsManager.recordEvent = sinon.stub()
  933. this.AnalyticsManager.identifyUser = sinon.stub()
  934. this.acceptsJson.returns(true)
  935. this.res.json = sinon.stub()
  936. this.res.redirect = sinon.stub()
  937. })
  938. it('should extract the redirect from the session', function() {
  939. this.AuthenticationController.finishLogin(
  940. this.user,
  941. this.req,
  942. this.res,
  943. this.next
  944. )
  945. expect(
  946. this.AuthenticationController._getRedirectFromSession.callCount
  947. ).to.equal(1)
  948. expect(
  949. this.AuthenticationController._getRedirectFromSession.calledWith(
  950. this.req
  951. )
  952. ).to.equal(true)
  953. })
  954. it('should clear redirect from session', function() {
  955. this.AuthenticationController.finishLogin(
  956. this.user,
  957. this.req,
  958. this.res,
  959. this.next
  960. )
  961. expect(
  962. this.AuthenticationController._clearRedirectFromSession.callCount
  963. ).to.equal(1)
  964. expect(
  965. this.AuthenticationController._clearRedirectFromSession.calledWith(
  966. this.req
  967. )
  968. ).to.equal(true)
  969. })
  970. it('should issue a json response with a redirect', function() {
  971. this.AuthenticationController.finishLogin(
  972. this.user,
  973. this.req,
  974. this.res,
  975. this.next
  976. )
  977. expect(
  978. this.AsyncFormHelper.redirect.calledWith(
  979. this.req,
  980. this.res,
  981. '/some/page'
  982. )
  983. ).to.equal(true)
  984. })
  985. describe('with a non-json request', function() {
  986. beforeEach(function() {
  987. this.acceptsJson.returns(false)
  988. this.res.json = sinon.stub()
  989. this.res.redirect = sinon.stub()
  990. })
  991. it('should issue a plain redirect', function() {
  992. this.AuthenticationController.finishLogin(
  993. this.user,
  994. this.req,
  995. this.res,
  996. this.next
  997. )
  998. expect(
  999. this.AsyncFormHelper.redirect.calledWith(
  1000. this.req,
  1001. this.res,
  1002. '/some/page'
  1003. )
  1004. ).to.equal(true)
  1005. })
  1006. })
  1007. describe('when user is flagged to reconfirm', function() {
  1008. beforeEach(function() {
  1009. this.req.session = {}
  1010. this.user.must_reconfirm = true
  1011. })
  1012. it('should redirect to reconfirm page', function() {
  1013. this.AuthenticationController.finishLogin(
  1014. this.user,
  1015. this.req,
  1016. this.res,
  1017. this.next
  1018. )
  1019. expect(
  1020. this.AuthenticationController._redirectToReconfirmPage.calledWith(
  1021. this.req
  1022. )
  1023. ).to.equal(true)
  1024. })
  1025. })
  1026. describe('preFinishLogin hook', function() {
  1027. it('call hook and proceed', function() {
  1028. this.Modules.hooks.fire = sinon.stub().yields(null, [])
  1029. this.AuthenticationController.finishLogin(
  1030. this.user,
  1031. this.req,
  1032. this.res,
  1033. this.next
  1034. )
  1035. sinon.assert.calledWith(
  1036. this.Modules.hooks.fire,
  1037. 'preFinishLogin',
  1038. this.req,
  1039. this.res,
  1040. this.user
  1041. )
  1042. expect(this.AsyncFormHelper.redirect.called).to.equal(true)
  1043. })
  1044. it('stop if hook has redirected', function(done) {
  1045. this.Modules.hooks.fire = sinon
  1046. .stub()
  1047. .yields(null, [{ doNotFinish: true }])
  1048. this.AuthenticationController.finishLogin(
  1049. this.user,
  1050. this.req,
  1051. this.res,
  1052. this.next
  1053. )
  1054. expect(this.next.callCount).to.equal(0)
  1055. expect(this.res.json.callCount).to.equal(0)
  1056. done()
  1057. })
  1058. it('call next with hook errors', function(done) {
  1059. this.Modules.hooks.fire = sinon.stub().yields(new Error())
  1060. this.AuthenticationController.finishLogin(
  1061. this.user,
  1062. this.req,
  1063. this.res,
  1064. error => {
  1065. expect(error).to.exist
  1066. expect(this.res.json.callCount).to.equal(0)
  1067. done()
  1068. }
  1069. )
  1070. })
  1071. })
  1072. describe('_afterLoginSessionSetup', function() {
  1073. beforeEach(function() {})
  1074. it('should call req.login', function() {
  1075. this.AuthenticationController.finishLogin(
  1076. this.user,
  1077. this.req,
  1078. this.res,
  1079. this.next
  1080. )
  1081. this.req.login.callCount.should.equal(1)
  1082. })
  1083. it('should call req.session.save', function() {
  1084. this.AuthenticationController.finishLogin(
  1085. this.user,
  1086. this.req,
  1087. this.res,
  1088. this.next
  1089. )
  1090. this.req.session.save.callCount.should.equal(1)
  1091. })
  1092. it('should call UserSessionsManager.trackSession', function() {
  1093. this.AuthenticationController.finishLogin(
  1094. this.user,
  1095. this.req,
  1096. this.res,
  1097. this.next
  1098. )
  1099. this.UserSessionsManager.trackSession.callCount.should.equal(1)
  1100. })
  1101. describe('when req.session.save produces an error', function() {
  1102. beforeEach(function() {
  1103. this.req.session.save = sinon
  1104. .stub()
  1105. .callsArgWith(0, new Error('woops'))
  1106. })
  1107. it('should produce an error', function(done) {
  1108. this.AuthenticationController.finishLogin(
  1109. this.user,
  1110. this.req,
  1111. this.res,
  1112. err => {
  1113. expect(err).to.not.be.oneOf([null, undefined])
  1114. expect(err).to.be.instanceof(Error)
  1115. done()
  1116. }
  1117. )
  1118. })
  1119. it('should not call UserSessionsManager.trackSession', function(done) {
  1120. this.AuthenticationController.finishLogin(
  1121. this.user,
  1122. this.req,
  1123. this.res,
  1124. err => {
  1125. expect(err).to.exist
  1126. this.UserSessionsManager.trackSession.callCount.should.equal(0)
  1127. done()
  1128. }
  1129. )
  1130. })
  1131. })
  1132. })
  1133. describe('_loginAsyncHandlers', function() {
  1134. beforeEach(function() {
  1135. this.AuthenticationController.finishLogin(
  1136. this.user,
  1137. this.req,
  1138. this.res,
  1139. this.next
  1140. )
  1141. })
  1142. it('should call identifyUser', function() {
  1143. this.AnalyticsManager.identifyUser
  1144. .calledWith(this.user._id, this.req.sessionID)
  1145. .should.equal(true)
  1146. })
  1147. it('should setup the user data in the background', function() {
  1148. this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true)
  1149. })
  1150. it('should set res.session.justLoggedIn', function() {
  1151. this.req.session.justLoggedIn.should.equal(true)
  1152. })
  1153. it('should record the successful login', function() {
  1154. this.AuthenticationController._recordSuccessfulLogin
  1155. .calledWith(this.user._id)
  1156. .should.equal(true)
  1157. })
  1158. it('should tell the rate limiter that there was a success for that email', function() {
  1159. this.LoginRateLimiter.recordSuccessfulLogin
  1160. .calledWith(this.user.email)
  1161. .should.equal(true)
  1162. })
  1163. it('should log the successful login', function() {
  1164. this.logger.log
  1165. .calledWith(
  1166. { email: this.user.email, user_id: this.user._id.toString() },
  1167. 'successful log in'
  1168. )
  1169. .should.equal(true)
  1170. })
  1171. it('should track the login event', function() {
  1172. this.AnalyticsManager.recordEvent
  1173. .calledWith(this.user._id, 'user-logged-in')
  1174. .should.equal(true)
  1175. })
  1176. })
  1177. })
  1178. })