UserEmailsControllerTests.js 17 KB

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