UserEmailsControllerTests.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. const sinon = require('sinon')
  2. const assertCalledWith = sinon.assert.calledWith
  3. const assertNotCalled = sinon.assert.notCalled
  4. const { assert, expect } = require('chai')
  5. const modulePath = '../../../../app/src/Features/User/UserEmailsController.js'
  6. const SandboxedModule = require('sandboxed-module')
  7. const MockRequest = require('../helpers/MockRequest')
  8. const MockResponse = require('../helpers/MockResponse')
  9. const Errors = require('../../../../app/src/Features/Errors/Errors')
  10. describe('UserEmailsController', function () {
  11. beforeEach(function () {
  12. this.req = new MockRequest()
  13. this.req.sessionID = Math.random().toString()
  14. this.res = new MockResponse()
  15. this.next = sinon.stub()
  16. this.user = {
  17. _id: 'mock-user-id',
  18. email: 'example@overleaf.com',
  19. emails: {},
  20. }
  21. this.UserGetter = {
  22. getUserFullEmails: sinon.stub(),
  23. getUserByAnyEmail: sinon.stub(),
  24. promises: {
  25. getUser: sinon.stub().resolves(this.user),
  26. },
  27. }
  28. this.SessionManager = {
  29. getSessionUser: sinon.stub().returns(this.user),
  30. getLoggedInUserId: sinon.stub().returns(this.user._id),
  31. setInSessionUser: sinon.stub(),
  32. }
  33. this.Features = {
  34. hasFeature: sinon.stub(),
  35. }
  36. this.UserSessionsManager = {
  37. revokeAllUserSessions: sinon.stub().yields(),
  38. }
  39. this.UserUpdater = {
  40. addEmailAddress: sinon.stub(),
  41. removeEmailAddress: sinon.stub(),
  42. setDefaultEmailAddress: sinon.stub(),
  43. updateV1AndSetDefaultEmailAddress: sinon.stub(),
  44. promises: {
  45. addEmailAddress: sinon.stub().resolves(),
  46. },
  47. }
  48. this.EmailHelper = { parseEmail: sinon.stub() }
  49. this.endorseAffiliation = sinon.stub().yields()
  50. this.InstitutionsAPI = {
  51. endorseAffiliation: this.endorseAffiliation,
  52. }
  53. this.HttpErrorHandler = { conflict: sinon.stub() }
  54. this.AnalyticsManager = {
  55. recordEventForUser: sinon.stub(),
  56. }
  57. this.UserEmailsController = SandboxedModule.require(modulePath, {
  58. requires: {
  59. '../Authentication/SessionManager': this.SessionManager,
  60. '../../infrastructure/Features': this.Features,
  61. './UserSessionsManager': this.UserSessionsManager,
  62. './UserGetter': this.UserGetter,
  63. './UserUpdater': this.UserUpdater,
  64. '../Email/EmailHandler': (this.EmailHandler = {
  65. promises: {
  66. sendEmail: sinon.stub().resolves(),
  67. },
  68. }),
  69. '../Helpers/EmailHelper': this.EmailHelper,
  70. './UserEmailsConfirmationHandler': (this.UserEmailsConfirmationHandler =
  71. {
  72. sendReconfirmationEmail: sinon.stub(),
  73. promises: {
  74. sendConfirmationEmail: sinon.stub().resolves(),
  75. },
  76. }),
  77. '../Institutions/InstitutionsAPI': this.InstitutionsAPI,
  78. '../Errors/HttpErrorHandler': this.HttpErrorHandler,
  79. '../Analytics/AnalyticsManager': this.AnalyticsManager,
  80. },
  81. })
  82. })
  83. describe('List', function () {
  84. beforeEach(function () {})
  85. it('lists emails', function (done) {
  86. const fullEmails = [{ some: 'data' }]
  87. this.UserGetter.getUserFullEmails.callsArgWith(1, null, fullEmails)
  88. this.UserEmailsController.list(this.req, {
  89. json: response => {
  90. assert.deepEqual(response, fullEmails)
  91. assertCalledWith(this.UserGetter.getUserFullEmails, this.user._id)
  92. done()
  93. },
  94. })
  95. })
  96. })
  97. describe('Add', function () {
  98. beforeEach(function () {
  99. this.newEmail = 'new_email@baz.com'
  100. this.req.body = {
  101. email: this.newEmail,
  102. university: { name: 'University Name' },
  103. department: 'Department',
  104. role: 'Role',
  105. }
  106. this.EmailHelper.parseEmail.returns(this.newEmail)
  107. this.UserEmailsConfirmationHandler.sendConfirmationEmail = sinon
  108. .stub()
  109. .yields()
  110. })
  111. it('passed audit log to addEmailAddress', function (done) {
  112. this.res.sendStatus = sinon.stub()
  113. this.res.sendStatus.callsFake(() => {
  114. const addCall = this.UserUpdater.promises.addEmailAddress.lastCall
  115. expect(addCall.args[3]).to.deep.equal({
  116. initiatorId: this.user._id,
  117. ipAddress: this.req.ip,
  118. })
  119. done()
  120. })
  121. this.UserEmailsController.add(this.req, this.res)
  122. })
  123. it('adds new email', function (done) {
  124. this.UserEmailsController.add(
  125. this.req,
  126. {
  127. sendStatus: code => {
  128. code.should.equal(204)
  129. assertCalledWith(this.EmailHelper.parseEmail, this.newEmail)
  130. assertCalledWith(
  131. this.UserUpdater.promises.addEmailAddress,
  132. this.user._id,
  133. this.newEmail
  134. )
  135. const affiliationOptions =
  136. this.UserUpdater.promises.addEmailAddress.lastCall.args[2]
  137. Object.keys(affiliationOptions).length.should.equal(3)
  138. affiliationOptions.university.should.equal(this.req.body.university)
  139. affiliationOptions.department.should.equal(this.req.body.department)
  140. affiliationOptions.role.should.equal(this.req.body.role)
  141. done()
  142. },
  143. },
  144. this.next
  145. )
  146. })
  147. it('sends a security alert email', function (done) {
  148. this.res.sendStatus = sinon.stub()
  149. this.res.sendStatus.callsFake(() => {
  150. const emailCall = this.EmailHandler.promises.sendEmail.getCall(0)
  151. emailCall.args[0].should.to.equal('securityAlert')
  152. emailCall.args[1].to.should.equal(this.user.email)
  153. emailCall.args[1].actionDescribed.should.contain(
  154. 'a secondary email address'
  155. )
  156. emailCall.args[1].to.should.equal(this.user.email)
  157. emailCall.args[1].message[0].should.contain(this.newEmail)
  158. done()
  159. })
  160. this.UserEmailsController.add(this.req, this.res)
  161. })
  162. it('sends an email confirmation', function (done) {
  163. this.UserEmailsController.add(
  164. this.req,
  165. {
  166. sendStatus: code => {
  167. code.should.equal(204)
  168. assertCalledWith(
  169. this.UserEmailsConfirmationHandler.promises.sendConfirmationEmail,
  170. this.user._id,
  171. this.newEmail
  172. )
  173. done()
  174. },
  175. },
  176. this.next
  177. )
  178. })
  179. it('handles email parse error', function (done) {
  180. this.EmailHelper.parseEmail.returns(null)
  181. this.UserEmailsController.add(
  182. this.req,
  183. {
  184. sendStatus: code => {
  185. code.should.equal(422)
  186. assertNotCalled(this.UserUpdater.promises.addEmailAddress)
  187. done()
  188. },
  189. },
  190. this.next
  191. )
  192. })
  193. it('should pass the error to the next handler when adding the email fails', function (done) {
  194. this.UserUpdater.promises.addEmailAddress.rejects(new Error())
  195. this.UserEmailsController.add(this.req, this.res, error => {
  196. expect(error).to.be.instanceof(Error)
  197. done()
  198. })
  199. })
  200. it('should call the HTTP conflict handler when the email already exists', function (done) {
  201. this.UserUpdater.promises.addEmailAddress.rejects(
  202. new Errors.EmailExistsError()
  203. )
  204. this.HttpErrorHandler.conflict = sinon.spy((req, res, message) => {
  205. req.should.exist
  206. res.should.exist
  207. message.should.equal('email_already_registered')
  208. done()
  209. })
  210. this.UserEmailsController.add(this.req, this.res, this.next)
  211. })
  212. it("should call the HTTP conflict handler when there's a domain matching error", function (done) {
  213. this.UserUpdater.promises.addEmailAddress.rejects(
  214. new Error('422: Email does not belong to university')
  215. )
  216. this.HttpErrorHandler.conflict = sinon.spy((req, res, message) => {
  217. req.should.exist
  218. res.should.exist
  219. message.should.equal('email_does_not_belong_to_university')
  220. done()
  221. })
  222. this.UserEmailsController.add(this.req, this.res, this.next)
  223. })
  224. it('should fail to add new emails when the limit has been reached', function (done) {
  225. this.user.emails = []
  226. for (let i = 0; i < 10; i++) {
  227. this.user.emails.push({ email: `example${i}@overleaf.com` })
  228. }
  229. this.UserEmailsController.add(
  230. this.req,
  231. {
  232. status: code => {
  233. expect(code).to.equal(422)
  234. return {
  235. json: error => {
  236. expect(error.message).to.equal('secondary email limit exceeded')
  237. done()
  238. },
  239. }
  240. },
  241. },
  242. this.next
  243. )
  244. })
  245. })
  246. describe('remove', function () {
  247. beforeEach(function () {
  248. this.email = 'email_to_remove@bar.com'
  249. this.req.body.email = this.email
  250. this.EmailHelper.parseEmail.returns(this.email)
  251. })
  252. it('removes email', function (done) {
  253. const auditLog = {
  254. initiatorId: this.user._id,
  255. ipAddress: this.req.ip,
  256. }
  257. this.UserUpdater.removeEmailAddress.callsArgWith(3, null)
  258. this.UserEmailsController.remove(this.req, {
  259. sendStatus: code => {
  260. code.should.equal(200)
  261. assertCalledWith(this.EmailHelper.parseEmail, this.email)
  262. assertCalledWith(
  263. this.UserUpdater.removeEmailAddress,
  264. this.user._id,
  265. this.email,
  266. auditLog
  267. )
  268. done()
  269. },
  270. })
  271. })
  272. it('handles email parse error', function (done) {
  273. this.EmailHelper.parseEmail.returns(null)
  274. this.UserEmailsController.remove(this.req, {
  275. sendStatus: code => {
  276. code.should.equal(422)
  277. assertNotCalled(this.UserUpdater.removeEmailAddress)
  278. done()
  279. },
  280. })
  281. })
  282. })
  283. describe('setDefault', function () {
  284. beforeEach(function () {
  285. this.email = 'email_to_set_default@bar.com'
  286. this.req.body.email = this.email
  287. this.EmailHelper.parseEmail.returns(this.email)
  288. this.SessionManager.setInSessionUser.returns(null)
  289. })
  290. it('sets default email', function (done) {
  291. this.UserUpdater.setDefaultEmailAddress.yields()
  292. this.UserEmailsController.setDefault(this.req, {
  293. sendStatus: code => {
  294. code.should.equal(200)
  295. assertCalledWith(this.EmailHelper.parseEmail, this.email)
  296. assertCalledWith(
  297. this.SessionManager.setInSessionUser,
  298. this.req.session,
  299. {
  300. email: this.email,
  301. }
  302. )
  303. assertCalledWith(
  304. this.UserUpdater.setDefaultEmailAddress,
  305. this.user._id,
  306. this.email
  307. )
  308. done()
  309. },
  310. })
  311. })
  312. it('handles email parse error', function (done) {
  313. this.EmailHelper.parseEmail.returns(null)
  314. this.UserEmailsController.setDefault(this.req, {
  315. sendStatus: code => {
  316. code.should.equal(422)
  317. assertNotCalled(this.UserUpdater.setDefaultEmailAddress)
  318. done()
  319. },
  320. })
  321. })
  322. it('should reset the users other sessions', function (done) {
  323. this.UserUpdater.setDefaultEmailAddress.yields()
  324. this.res.callback = () => {
  325. expect(
  326. this.UserSessionsManager.revokeAllUserSessions
  327. ).to.have.been.calledWith(this.user, [this.req.sessionID])
  328. done()
  329. }
  330. this.UserEmailsController.setDefault(this.req, this.res, done)
  331. })
  332. it('handles error from revoking sessions and returns 200', function (done) {
  333. this.UserUpdater.setDefaultEmailAddress.yields()
  334. const redisError = new Error('redis error')
  335. this.UserSessionsManager.revokeAllUserSessions = sinon
  336. .stub()
  337. .yields(redisError)
  338. this.res.callback = () => {
  339. expect(this.res.statusCode).to.equal(200)
  340. // give revoke process time to run
  341. setTimeout(() => {
  342. expect(this.logger.warn).to.have.been.calledWith(
  343. sinon.match({ err: redisError }),
  344. 'failed revoking secondary sessions after changing default email'
  345. )
  346. done()
  347. })
  348. }
  349. this.UserEmailsController.setDefault(this.req, this.res, done)
  350. })
  351. })
  352. describe('endorse', function () {
  353. beforeEach(function () {
  354. this.email = 'email_to_endorse@bar.com'
  355. this.req.body.email = this.email
  356. this.EmailHelper.parseEmail.returns(this.email)
  357. })
  358. it('endorses affiliation', function (done) {
  359. this.req.body.role = 'Role'
  360. this.req.body.department = 'Department'
  361. this.UserEmailsController.endorse(this.req, {
  362. sendStatus: code => {
  363. code.should.equal(204)
  364. assertCalledWith(
  365. this.endorseAffiliation,
  366. this.user._id,
  367. this.email,
  368. 'Role',
  369. 'Department'
  370. )
  371. done()
  372. },
  373. })
  374. })
  375. })
  376. describe('confirm', function () {
  377. beforeEach(function () {
  378. this.UserEmailsConfirmationHandler.confirmEmailFromToken = sinon
  379. .stub()
  380. .yields()
  381. this.res = {
  382. sendStatus: sinon.stub(),
  383. json: sinon.stub(),
  384. }
  385. this.res.status = sinon.stub().returns(this.res)
  386. this.next = sinon.stub()
  387. this.token = 'mock-token'
  388. this.req.body = { token: this.token }
  389. })
  390. describe('successfully', function () {
  391. beforeEach(function () {
  392. this.UserEmailsController.confirm(this.req, this.res, this.next)
  393. })
  394. it('should confirm the email from the token', function () {
  395. this.UserEmailsConfirmationHandler.confirmEmailFromToken
  396. .calledWith(this.token)
  397. .should.equal(true)
  398. })
  399. it('should return a 200 status', function () {
  400. this.res.sendStatus.calledWith(200).should.equal(true)
  401. })
  402. })
  403. describe('without a token', function () {
  404. beforeEach(function () {
  405. this.req.body.token = null
  406. this.UserEmailsController.confirm(this.req, this.res, this.next)
  407. })
  408. it('should return a 422 status', function () {
  409. this.res.status.calledWith(422).should.equal(true)
  410. })
  411. })
  412. describe('when confirming fails', function () {
  413. beforeEach(function () {
  414. this.UserEmailsConfirmationHandler.confirmEmailFromToken = sinon
  415. .stub()
  416. .yields(new Errors.NotFoundError('not found'))
  417. this.UserEmailsController.confirm(this.req, this.res, this.next)
  418. })
  419. it('should return a 404 error code with a message', function () {
  420. this.res.status.calledWith(404).should.equal(true)
  421. this.res.json
  422. .calledWith({
  423. message: this.req.i18n.translate('confirmation_token_invalid'),
  424. })
  425. .should.equal(true)
  426. })
  427. })
  428. })
  429. describe('resendConfirmation', function () {
  430. beforeEach(function () {
  431. this.EmailHelper.parseEmail.returnsArg(0)
  432. this.UserGetter.getUserByAnyEmail.yields(undefined, {
  433. _id: this.user._id,
  434. })
  435. this.req = {
  436. body: {},
  437. }
  438. this.res = {
  439. sendStatus: sinon.stub(),
  440. }
  441. this.next = sinon.stub()
  442. this.UserEmailsConfirmationHandler.sendConfirmationEmail = sinon
  443. .stub()
  444. .yields()
  445. })
  446. it('should send the email', function (done) {
  447. this.req = {
  448. body: {
  449. email: 'test@example.com',
  450. },
  451. }
  452. this.UserEmailsController.sendReconfirmation(
  453. this.req,
  454. this.res,
  455. this.next
  456. )
  457. expect(this.UserEmailsConfirmationHandler.sendReconfirmationEmail).to.have
  458. .been.calledOnce
  459. done()
  460. })
  461. it('should return 422 if email not valid', function (done) {
  462. this.req = {
  463. body: {},
  464. }
  465. this.UserEmailsController.resendConfirmation(
  466. this.req,
  467. this.res,
  468. this.next
  469. )
  470. expect(this.UserEmailsConfirmationHandler.sendConfirmationEmail).to.not
  471. .have.been.called
  472. expect(this.res.sendStatus.lastCall.args[0]).to.equal(422)
  473. done()
  474. })
  475. describe('email on another user account', function () {
  476. beforeEach(function () {
  477. this.UserGetter.getUserByAnyEmail.yields(undefined, {
  478. _id: 'another-user-id',
  479. })
  480. })
  481. it('should return 422', function (done) {
  482. this.req = {
  483. body: {
  484. email: 'test@example.com',
  485. },
  486. }
  487. this.UserEmailsController.resendConfirmation(
  488. this.req,
  489. this.res,
  490. this.next
  491. )
  492. expect(this.UserEmailsConfirmationHandler.sendConfirmationEmail).to.not
  493. .have.been.called
  494. expect(this.res.sendStatus.lastCall.args[0]).to.equal(422)
  495. done()
  496. })
  497. })
  498. })
  499. describe('sendReconfirmation', function () {
  500. beforeEach(function () {
  501. this.res.sendStatus = sinon.stub()
  502. this.UserGetter.getUserByAnyEmail.yields(undefined, {
  503. _id: this.user._id,
  504. })
  505. this.EmailHelper.parseEmail.returnsArg(0)
  506. })
  507. it('should send the email', function (done) {
  508. this.req = {
  509. body: {
  510. email: 'test@example.com',
  511. },
  512. }
  513. this.UserEmailsController.sendReconfirmation(
  514. this.req,
  515. this.res,
  516. this.next
  517. )
  518. expect(this.UserEmailsConfirmationHandler.sendReconfirmationEmail).to.have
  519. .been.calledOnce
  520. done()
  521. })
  522. it('should return 400 if email not valid', function (done) {
  523. this.req = {
  524. body: {},
  525. }
  526. this.UserEmailsController.sendReconfirmation(
  527. this.req,
  528. this.res,
  529. this.next
  530. )
  531. expect(this.UserEmailsConfirmationHandler.sendReconfirmationEmail).to.not
  532. .have.been.called
  533. expect(this.res.sendStatus.lastCall.args[0]).to.equal(400)
  534. done()
  535. })
  536. describe('email on another user account', function () {
  537. beforeEach(function () {
  538. this.UserGetter.getUserByAnyEmail.yields(undefined, {
  539. _id: 'another-user-id',
  540. })
  541. })
  542. it('should return 422', function (done) {
  543. this.req = {
  544. body: {
  545. email: 'test@example.com',
  546. },
  547. }
  548. this.UserEmailsController.sendReconfirmation(
  549. this.req,
  550. this.res,
  551. this.next
  552. )
  553. expect(this.UserEmailsConfirmationHandler.sendReconfirmationEmail).to
  554. .not.have.been.called
  555. expect(this.res.sendStatus.lastCall.args[0]).to.equal(422)
  556. done()
  557. })
  558. })
  559. })
  560. })