AuthenticationControllerTests.js 45 KB

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