UserUpdaterTests.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. const { setTimeout } = require('timers/promises')
  2. const SandboxedModule = require('sandboxed-module')
  3. const path = require('path')
  4. const sinon = require('sinon')
  5. const { ObjectId } = require('mongodb-legacy')
  6. const tk = require('timekeeper')
  7. const { expect } = require('chai')
  8. const { normalizeQuery } = require('../../../../app/src/Features/Helpers/Mongo')
  9. const Errors = require('../../../../app/src/Features/Errors/Errors')
  10. const MODULE_PATH = path.join(
  11. __dirname,
  12. '../../../../app/src/Features/User/UserUpdater'
  13. )
  14. describe('UserUpdater', function () {
  15. beforeEach(function () {
  16. tk.freeze(Date.now())
  17. this.user = {
  18. _id: new ObjectId(),
  19. name: 'bob',
  20. email: 'hello@world.com',
  21. emails: [{ email: 'hello@world.com' }],
  22. }
  23. this.db = {
  24. users: {
  25. updateOne: sinon.stub().resolves({ matchedCount: 1, modifiedCount: 1 }),
  26. },
  27. }
  28. this.mongodb = {
  29. db: this.db,
  30. ObjectId,
  31. }
  32. this.UserGetter = {
  33. promises: {
  34. ensureUniqueEmailAddress: sinon.stub().resolves(),
  35. getUser: sinon.stub(),
  36. getUserByMainEmail: sinon.stub(),
  37. getUserFullEmails: sinon.stub(),
  38. getUserEmail: sinon.stub(),
  39. },
  40. }
  41. this.UserGetter.promises.getUser.withArgs(this.user._id).resolves(this.user)
  42. this.UserGetter.promises.getUserByMainEmail
  43. .withArgs(this.user.email)
  44. .resolves(this.user)
  45. this.UserGetter.promises.getUserFullEmails
  46. .withArgs(this.user._id)
  47. .resolves(this.user.emails)
  48. this.UserGetter.promises.getUserEmail
  49. .withArgs(this.user._id)
  50. .resolves(this.user.email)
  51. this.NewsletterManager = {
  52. promises: {
  53. changeEmail: sinon.stub().resolves(),
  54. },
  55. }
  56. this.AnalyticsManager = {
  57. recordEventForUserInBackground: sinon.stub(),
  58. }
  59. this.InstitutionsAPI = {
  60. promises: {
  61. addAffiliation: sinon.stub().resolves(),
  62. removeAffiliation: sinon.stub().resolves(),
  63. getUserAffiliations: sinon.stub().resolves(),
  64. },
  65. }
  66. this.EmailHandler = {
  67. promises: {
  68. sendEmail: sinon.stub().resolves(),
  69. },
  70. }
  71. this.Features = {
  72. hasFeature: sinon.stub().returns(false),
  73. }
  74. this.FeaturesUpdater = {
  75. promises: {
  76. refreshFeatures: sinon.stub().resolves(),
  77. },
  78. }
  79. this.UserAuditLogHandler = {
  80. promises: {
  81. addEntry: sinon.stub().resolves(),
  82. },
  83. }
  84. this.SubscriptionLocator = {
  85. promises: {
  86. getUserIndividualSubscription: sinon.stub().resolves(),
  87. },
  88. }
  89. this.NotificationsBuilder = {
  90. promises: {
  91. redundantPersonalSubscription: sinon
  92. .stub()
  93. .returns({ create: () => {} }),
  94. },
  95. }
  96. this.Modules = {
  97. promises: {
  98. hooks: {
  99. fire: sinon.stub().resolves([]),
  100. },
  101. },
  102. }
  103. this.UserSessionsManager = {
  104. promises: {
  105. removeSessionsFromRedis: sinon.stub().resolves(),
  106. },
  107. }
  108. this.AsyncLocalStorage = {
  109. removeItem: sinon.stub(),
  110. }
  111. this.UserUpdater = SandboxedModule.require(MODULE_PATH, {
  112. requires: {
  113. '../Helpers/Mongo': { normalizeQuery },
  114. '../../infrastructure/mongodb': this.mongodb,
  115. './UserGetter': this.UserGetter,
  116. '../Institutions/InstitutionsAPI': this.InstitutionsAPI,
  117. '../Email/EmailHandler': this.EmailHandler,
  118. '../../infrastructure/Features': this.Features,
  119. '../Subscription/FeaturesUpdater': this.FeaturesUpdater,
  120. '@overleaf/settings': (this.settings = {}),
  121. '../Newsletter/NewsletterManager': this.NewsletterManager,
  122. '../Subscription/RecurlyWrapper': this.RecurlyWrapper,
  123. './UserAuditLogHandler': this.UserAuditLogHandler,
  124. '../Analytics/AnalyticsManager': this.AnalyticsManager,
  125. '../../Errors/Errors': Errors,
  126. '../Subscription/SubscriptionLocator': this.SubscriptionLocator,
  127. '../Notifications/NotificationsBuilder': this.NotificationsBuilder,
  128. '../../infrastructure/Modules': this.Modules,
  129. './UserSessionsManager': this.UserSessionsManager,
  130. './ThirdPartyIdentityManager': this.ThirdPartyIdentityManager,
  131. '../../infrastructure/AsyncLocalStorage': this.AsyncLocalStorage,
  132. },
  133. })
  134. this.newEmail = 'bob@bob.com'
  135. })
  136. afterEach(function () {
  137. return tk.reset()
  138. })
  139. describe('addAffiliationForNewUser', function () {
  140. it('should not remove affiliationUnchecked flag if v1 returns an error', async function () {
  141. this.InstitutionsAPI.promises.addAffiliation.rejects()
  142. await expect(
  143. this.UserUpdater.promises.addAffiliationForNewUser(
  144. this.user._id,
  145. this.newEmail
  146. )
  147. ).to.be.rejected
  148. sinon.assert.notCalled(this.db.users.updateOne)
  149. })
  150. it('should remove affiliationUnchecked flag if v1 does not return an error', async function () {
  151. await this.UserUpdater.promises.addAffiliationForNewUser(
  152. this.user._id,
  153. this.newEmail
  154. )
  155. sinon.assert.calledOnce(this.db.users.updateOne)
  156. sinon.assert.calledWithMatch(
  157. this.db.users.updateOne,
  158. { _id: this.user._id, 'emails.email': this.newEmail },
  159. { $unset: { 'emails.$.affiliationUnchecked': 1 } }
  160. )
  161. })
  162. it('should not throw if removing affiliationUnchecked flag errors', async function () {
  163. this.db.users.updateOne.rejects(new Error('nope'))
  164. await this.UserUpdater.promises.addAffiliationForNewUser(
  165. this.user._id,
  166. this.newEmail
  167. )
  168. })
  169. it('calls to remove userFullEmails from AsyncLocalStorage', async function () {
  170. await this.UserUpdater.promises.addAffiliationForNewUser(
  171. this.user._id,
  172. this.newEmail
  173. )
  174. expect(this.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  175. 'userFullEmails'
  176. )
  177. })
  178. })
  179. describe('changeEmailAddress', function () {
  180. beforeEach(async function () {
  181. this.auditLog = {
  182. initiatorId: 'abc123',
  183. ipAddress: '0:0:0:0',
  184. }
  185. // After the email changed, make sure that UserGetter.getUser() returns a
  186. // user with the new email.
  187. this.UserGetter.promises.getUser
  188. .withArgs(this.user._id)
  189. .onCall(1)
  190. .resolves({
  191. ...this.user,
  192. emails: [...this.user.emails, { email: this.newEmail }],
  193. })
  194. // The main email changes as a result of the email change
  195. this.UserGetter.promises.getUserByMainEmail
  196. .withArgs(this.user.email)
  197. .resolves(null)
  198. this.user.emails.push({ email: this.newEmail })
  199. await this.UserUpdater.promises.changeEmailAddress(
  200. this.user._id,
  201. this.newEmail,
  202. this.auditLog
  203. )
  204. })
  205. it('adds the new email', function () {
  206. expect(this.db.users.updateOne).to.have.been.calledWith(
  207. { _id: this.user._id, 'emails.email': { $ne: this.newEmail } },
  208. {
  209. $push: {
  210. emails: sinon.match({ email: this.newEmail }),
  211. },
  212. }
  213. )
  214. })
  215. it('adds the new affiliation', function () {
  216. this.InstitutionsAPI.promises.addAffiliation.should.have.been.calledWith(
  217. this.user._id,
  218. this.newEmail
  219. )
  220. })
  221. it('removes the old email', function () {
  222. expect(this.db.users.updateOne).to.have.been.calledWith(
  223. { _id: this.user._id, email: { $ne: this.user.email } },
  224. { $pull: { emails: { email: this.user.email } } }
  225. )
  226. })
  227. it('removes the affiliation', function () {
  228. expect(
  229. this.InstitutionsAPI.promises.removeAffiliation
  230. ).to.have.been.calledWith(this.user._id, this.user.email)
  231. })
  232. it('refreshes features', function () {
  233. sinon.assert.calledWith(
  234. this.FeaturesUpdater.promises.refreshFeatures,
  235. this.user._id
  236. )
  237. })
  238. it('sets the default email', function () {
  239. expect(this.db.users.updateOne).to.have.been.calledWith(
  240. { _id: this.user._id, 'emails.email': this.newEmail },
  241. {
  242. $set: sinon.match({
  243. email: this.newEmail,
  244. }),
  245. }
  246. )
  247. })
  248. it('sets the new email in the newsletter', function () {
  249. expect(
  250. this.NewsletterManager.promises.changeEmail
  251. ).to.have.been.calledWith(this.user, this.newEmail)
  252. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  253. 'updateAccountEmailAddress',
  254. this.user._id,
  255. this.newEmail
  256. )
  257. })
  258. it('validates email', async function () {
  259. await expect(
  260. this.UserUpdater.promises.changeEmailAddress(
  261. this.user._id,
  262. 'foo',
  263. this.auditLog
  264. )
  265. ).to.be.rejected
  266. })
  267. })
  268. describe('addEmailAddress', function () {
  269. it('adds the email', async function () {
  270. await this.UserUpdater.promises.addEmailAddress(
  271. this.user._id,
  272. this.newEmail,
  273. {},
  274. { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  275. )
  276. this.UserGetter.promises.ensureUniqueEmailAddress.should.have.been.called
  277. const reversedHostname = this.newEmail
  278. .split('@')[1]
  279. .split('')
  280. .reverse()
  281. .join('')
  282. this.db.users.updateOne.should.have.been.calledWith(
  283. { _id: this.user._id, 'emails.email': { $ne: this.newEmail } },
  284. {
  285. $push: {
  286. emails: {
  287. email: this.newEmail,
  288. createdAt: sinon.match.date,
  289. reversedHostname,
  290. },
  291. },
  292. }
  293. )
  294. })
  295. it('adds the affiliation', async function () {
  296. const affiliationOptions = {
  297. university: { id: 1 },
  298. role: 'Prof',
  299. department: 'Math',
  300. }
  301. await this.UserUpdater.promises.addEmailAddress(
  302. this.user._id,
  303. this.newEmail,
  304. affiliationOptions,
  305. { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  306. )
  307. this.InstitutionsAPI.promises.addAffiliation.should.have.been.calledWith(
  308. this.user._id,
  309. this.newEmail,
  310. affiliationOptions
  311. )
  312. })
  313. it('handles affiliation errors', async function () {
  314. this.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
  315. await expect(
  316. this.UserUpdater.promises.addEmailAddress(
  317. this.user._id,
  318. this.newEmail,
  319. {},
  320. { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  321. )
  322. ).to.be.rejected
  323. this.db.users.updateOne.should.not.have.been.called
  324. })
  325. it('validates the email', async function () {
  326. expect(
  327. this.UserUpdater.promises.addEmailAddress(
  328. this.user._id,
  329. 'bar',
  330. {},
  331. { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  332. )
  333. ).to.be.rejected
  334. })
  335. it('updates the audit log', async function () {
  336. this.ip = '127:0:0:0'
  337. await this.UserUpdater.promises.addEmailAddress(
  338. this.user._id,
  339. this.newEmail,
  340. {},
  341. { initiatorId: this.user._id, ipAddress: this.ip }
  342. )
  343. this.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(true)
  344. const { args } = this.UserAuditLogHandler.promises.addEntry.lastCall
  345. expect(args[0]).to.equal(this.user._id)
  346. expect(args[1]).to.equal('add-email')
  347. expect(args[2]).to.equal(this.user._id)
  348. expect(args[3]).to.equal(this.ip)
  349. expect(args[4]).to.deep.equal({ newSecondaryEmail: this.newEmail })
  350. })
  351. describe('errors', function () {
  352. describe('via UserAuditLogHandler', function () {
  353. const anError = new Error('oops')
  354. beforeEach(function () {
  355. this.UserAuditLogHandler.promises.addEntry.rejects(anError)
  356. })
  357. it('should not add email and should return error', async function () {
  358. await expect(
  359. this.UserUpdater.promises.addEmailAddress(
  360. this.user._id,
  361. this.newEmail,
  362. {},
  363. { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  364. )
  365. ).to.be.rejectedWith(anError)
  366. expect(this.db.users.updateOne).to.not.have.been.called
  367. })
  368. })
  369. })
  370. it('calls to remove userFullEmails from AsyncLocalStorage', async function () {
  371. await this.UserUpdater.promises.addEmailAddress(
  372. this.user._id,
  373. this.newEmail,
  374. {},
  375. { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  376. )
  377. expect(this.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  378. 'userFullEmails'
  379. )
  380. })
  381. })
  382. describe('removeEmailAddress', function () {
  383. this.beforeEach(function () {
  384. this.auditLog = { initiatorId: this.user._id, ipAddress: '127:0:0:0' }
  385. })
  386. it('removes the email', async function () {
  387. await this.UserUpdater.promises.removeEmailAddress(
  388. this.user._id,
  389. this.newEmail,
  390. this.auditLog
  391. )
  392. expect(this.db.users.updateOne).to.have.been.calledWith(
  393. { _id: this.user._id, email: { $ne: this.newEmail } },
  394. { $pull: { emails: { email: this.newEmail } } }
  395. )
  396. })
  397. it('removes the affiliation', async function () {
  398. await this.UserUpdater.promises.removeEmailAddress(
  399. this.user._id,
  400. this.newEmail,
  401. this.auditLog
  402. )
  403. expect(this.InstitutionsAPI.promises.removeAffiliation).to.have.been
  404. .calledOnce
  405. const { args } = this.InstitutionsAPI.promises.removeAffiliation.lastCall
  406. args[0].should.equal(this.user._id)
  407. args[1].should.equal(this.newEmail)
  408. })
  409. it('refreshes features', async function () {
  410. await this.UserUpdater.promises.removeEmailAddress(
  411. this.user._id,
  412. this.newEmail,
  413. this.auditLog
  414. )
  415. sinon.assert.calledWith(
  416. this.FeaturesUpdater.promises.refreshFeatures,
  417. this.user._id
  418. )
  419. })
  420. it('handles Mongo errors', async function () {
  421. const anError = new Error('nope')
  422. this.db.users.updateOne.rejects(anError)
  423. await expect(
  424. this.UserUpdater.promises.removeEmailAddress(
  425. this.user._id,
  426. this.newEmail,
  427. this.auditLog
  428. )
  429. ).to.be.rejected
  430. expect(this.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  431. .called
  432. })
  433. it('handles missed update', async function () {
  434. this.db.users.updateOne.resolves({ matchedCount: 0 })
  435. await expect(
  436. this.UserUpdater.promises.removeEmailAddress(
  437. this.user._id,
  438. this.newEmail,
  439. this.auditLog
  440. )
  441. ).to.be.rejectedWith('Cannot remove email')
  442. expect(this.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  443. .called
  444. })
  445. it('handles an affiliation error', async function () {
  446. const anError = new Error('nope')
  447. this.InstitutionsAPI.promises.removeAffiliation.rejects(anError)
  448. await expect(
  449. this.UserUpdater.promises.removeEmailAddress(
  450. this.user._id,
  451. this.newEmail,
  452. this.auditLog
  453. )
  454. ).to.be.rejected
  455. expect(this.db.users.updateOne).not.to.have.been.called
  456. expect(this.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  457. .called
  458. })
  459. it('throws an error when removing the primary email', async function () {
  460. await expect(
  461. this.UserUpdater.promises.removeEmailAddress(
  462. this.user._id,
  463. this.user.email,
  464. this.auditLog
  465. )
  466. ).to.be.rejectedWith('cannot remove primary email')
  467. expect(this.db.users.updateOne).not.to.have.been.called
  468. expect(this.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  469. .called
  470. })
  471. it('validates the email', function () {
  472. expect(
  473. this.UserUpdater.promises.removeEmailAddress(
  474. this.user._id,
  475. 'baz',
  476. this.auditLog
  477. )
  478. ).to.be.rejectedWith('invalid email')
  479. })
  480. it('skips email validation when skipParseEmail included', async function () {
  481. const skipParseEmail = true
  482. await this.UserUpdater.promises.removeEmailAddress(
  483. this.user._id,
  484. 'baz',
  485. this.auditLog,
  486. skipParseEmail
  487. )
  488. })
  489. it('throws an error when skipParseEmail included but email is not a string', async function () {
  490. const skipParseEmail = true
  491. await expect(
  492. this.UserUpdater.promises.removeEmailAddress(
  493. this.user._id,
  494. 1,
  495. this.auditLog,
  496. skipParseEmail
  497. )
  498. ).to.be.rejectedWith('email must be a string')
  499. })
  500. it('logs the removal to the audit log', async function () {
  501. await this.UserUpdater.promises.removeEmailAddress(
  502. this.user._id,
  503. this.newEmail,
  504. this.auditLog
  505. )
  506. expect(
  507. this.UserAuditLogHandler.promises.addEntry
  508. ).to.have.been.calledWith(
  509. this.user._id,
  510. 'remove-email',
  511. this.auditLog.initiatorId,
  512. this.auditLog.ipAddress,
  513. {
  514. removedEmail: this.newEmail,
  515. }
  516. )
  517. })
  518. it('logs the removal from script to the audit log', async function () {
  519. this.auditLog = {
  520. initiatorId: undefined,
  521. ipAddress: '0.0.0.0',
  522. extraInfo: {
  523. script: true,
  524. },
  525. }
  526. await this.UserUpdater.promises.removeEmailAddress(
  527. this.user._id,
  528. this.newEmail,
  529. this.auditLog
  530. )
  531. expect(
  532. this.UserAuditLogHandler.promises.addEntry
  533. ).to.have.been.calledWith(
  534. this.user._id,
  535. 'remove-email',
  536. this.auditLog.initiatorId,
  537. this.auditLog.ipAddress,
  538. {
  539. removedEmail: this.newEmail,
  540. script: true,
  541. }
  542. )
  543. })
  544. it('calls to remove userFullEmails from AsyncLocalStorage', async function () {
  545. await this.UserUpdater.promises.removeEmailAddress(
  546. this.user._id,
  547. this.newEmail,
  548. this.auditLog
  549. )
  550. expect(this.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  551. 'userFullEmails'
  552. )
  553. })
  554. })
  555. describe('setDefaultEmailAddress', function () {
  556. function setUserEmails(test, emails) {
  557. test.user.emails = emails
  558. test.UserGetter.promises.getUserFullEmails
  559. .withArgs(test.user._id)
  560. .resolves(emails)
  561. }
  562. beforeEach(function () {
  563. this.auditLog = {
  564. initiatorId: this.user,
  565. ipAddress: '0:0:0:0',
  566. }
  567. setUserEmails(this, [
  568. {
  569. email: this.newEmail,
  570. confirmedAt: new Date(),
  571. },
  572. ])
  573. })
  574. it('set default', async function () {
  575. await this.UserUpdater.promises.setDefaultEmailAddress(
  576. this.user._id,
  577. this.newEmail,
  578. false,
  579. this.auditLog
  580. )
  581. expect(this.db.users.updateOne).to.have.been.calledWith(
  582. { _id: this.user._id, 'emails.email': this.newEmail },
  583. {
  584. $set: {
  585. email: this.newEmail,
  586. lastPrimaryEmailCheck: sinon.match.date,
  587. },
  588. }
  589. )
  590. })
  591. it('sets the changed email in the newsletter', async function () {
  592. await this.UserUpdater.promises.setDefaultEmailAddress(
  593. this.user._id,
  594. this.newEmail,
  595. false,
  596. this.auditLog
  597. )
  598. expect(
  599. this.NewsletterManager.promises.changeEmail
  600. ).to.have.been.calledWith(this.user, this.newEmail)
  601. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  602. 'updateAccountEmailAddress',
  603. this.user._id,
  604. this.newEmail
  605. )
  606. })
  607. it('handles Mongo errors', async function () {
  608. this.db.users.updateOne = sinon.stub().rejects(Error('nope'))
  609. await expect(
  610. this.UserUpdater.promises.setDefaultEmailAddress(
  611. this.user._id,
  612. this.newEmail,
  613. false,
  614. this.auditLog
  615. )
  616. ).to.be.rejected
  617. })
  618. it('handles missed updates', async function () {
  619. this.db.users.updateOne.resolves({ matchedCount: 0 })
  620. await expect(
  621. this.UserUpdater.promises.setDefaultEmailAddress(
  622. this.user._id,
  623. this.newEmail,
  624. false,
  625. this.auditLog
  626. )
  627. ).to.be.rejected
  628. })
  629. it('validates the email', async function () {
  630. await expect(
  631. this.UserUpdater.promises.setDefaultEmailAddress(
  632. this.user._id,
  633. '.edu',
  634. false,
  635. this.auditLog
  636. )
  637. ).to.be.rejected
  638. })
  639. it('updates the audit log', async function () {
  640. await this.UserUpdater.promises.setDefaultEmailAddress(
  641. this.user._id,
  642. this.newEmail,
  643. false,
  644. this.auditLog
  645. )
  646. expect(
  647. this.UserAuditLogHandler.promises.addEntry
  648. ).to.have.been.calledWith(
  649. this.user._id,
  650. 'change-primary-email',
  651. this.auditLog.initiatorId,
  652. this.auditLog.ipAddress,
  653. {
  654. newPrimaryEmail: this.newEmail,
  655. oldPrimaryEmail: this.user.email,
  656. }
  657. )
  658. })
  659. it('blocks email update if audit log returns an error', async function () {
  660. this.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
  661. await expect(
  662. this.UserUpdater.promises.setDefaultEmailAddress(
  663. this.user._id,
  664. this.newEmail,
  665. false,
  666. this.auditLog
  667. )
  668. ).to.be.rejected
  669. expect(this.db.users.updateOne).to.not.have.been.called
  670. })
  671. it('calls to remove userFullEmails from AsyncLocalStorage', async function () {
  672. await this.UserUpdater.promises.setDefaultEmailAddress(
  673. this.user._id,
  674. this.newEmail,
  675. false,
  676. this.auditLog
  677. )
  678. expect(this.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  679. 'userFullEmails'
  680. )
  681. })
  682. describe('when email not confirmed', function () {
  683. beforeEach(function () {
  684. setUserEmails(this, [
  685. {
  686. email: this.newEmail,
  687. confirmedAt: null,
  688. },
  689. ])
  690. })
  691. it('should throw an error', async function () {
  692. await expect(
  693. this.UserUpdater.promises.setDefaultEmailAddress(
  694. this.user._id,
  695. this.newEmail,
  696. false,
  697. this.auditLog
  698. )
  699. ).to.be.rejectedWith(Errors.UnconfirmedEmailError)
  700. expect(this.db.users.updateOne).to.not.have.been.called
  701. expect(this.NewsletterManager.promises.changeEmail).to.not.have.been
  702. .called
  703. })
  704. })
  705. describe('when email does not belong to user', function () {
  706. beforeEach(function () {
  707. setUserEmails(this, [])
  708. this.UserUpdater.promises.updateUser = sinon.stub()
  709. })
  710. it('should callback with error', function () {
  711. this.UserUpdater.setDefaultEmailAddress(
  712. this.user._id,
  713. this.newEmail,
  714. false,
  715. this.auditLog,
  716. error => {
  717. expect(error).to.exist
  718. expect(error.name).to.equal('Error')
  719. this.UserUpdater.promises.updateUser.callCount.should.equal(0)
  720. this.NewsletterManager.promises.changeEmail.callCount.should.equal(
  721. 0
  722. )
  723. }
  724. )
  725. })
  726. })
  727. describe('security alert', function () {
  728. it('should be sent to old and new email when sendSecurityAlert=true', async function () {
  729. await this.UserUpdater.promises.setDefaultEmailAddress(
  730. this.user._id,
  731. this.newEmail,
  732. false,
  733. this.auditLog,
  734. true
  735. )
  736. // Emails are sent asynchronously. Wait a bit.
  737. await setTimeout(100)
  738. this.EmailHandler.promises.sendEmail.callCount.should.equal(2)
  739. for (const recipient of [this.user.email, this.newEmail]) {
  740. expect(this.EmailHandler.promises.sendEmail).to.have.been.calledWith(
  741. 'securityAlert',
  742. sinon.match({ to: recipient })
  743. )
  744. }
  745. })
  746. it('should send to the most recently (re-)confirmed emails grouped by institution and by domain for unaffiliated emails', async function () {
  747. setUserEmails(this, [
  748. {
  749. email: '1@a1.uni',
  750. confirmedAt: new Date(2020, 0, 1),
  751. reConfirmedAt: new Date(2021, 2, 11),
  752. lastConfirmedAt: new Date(2021, 2, 11),
  753. default: false,
  754. affiliation: {
  755. institution: {
  756. id: 123,
  757. name: 'A1 University',
  758. },
  759. cachedConfirmedAt: '2020-01-01T18:25:01.639Z',
  760. cachedReconfirmedAt: '2021-03-11T18:25:01.639Z',
  761. },
  762. },
  763. {
  764. email: '2@a1.uni',
  765. confirmedAt: new Date(2019, 0, 1),
  766. reConfirmedAt: new Date(2022, 2, 11),
  767. lastConfirmedAt: new Date(2022, 2, 11),
  768. default: false,
  769. affiliation: {
  770. institution: {
  771. id: 123,
  772. name: 'A1 University',
  773. },
  774. cachedConfirmedAt: '2019-01-01T18:25:01.639Z',
  775. cachedReconfirmedAt: '2022-03-11T18:25:01.639Z',
  776. },
  777. },
  778. {
  779. email: '2020@foo.bar',
  780. confirmedAt: new Date(2020, 6, 1),
  781. lastConfirmedAt: new Date(2020, 6, 1),
  782. },
  783. {
  784. email: '2021@foo.bar',
  785. confirmedAt: new Date(2021, 6, 1),
  786. lastConfirmedAt: new Date(2021, 6, 1),
  787. },
  788. {
  789. email: this.user.email,
  790. confirmedAt: new Date(2021, 6, 1),
  791. lastConfirmedAt: new Date(2021, 6, 1),
  792. },
  793. {
  794. email: this.newEmail,
  795. confirmedAt: new Date(2021, 6, 1),
  796. lastConfirmedAt: new Date(2021, 6, 1),
  797. },
  798. ])
  799. await this.UserUpdater.promises.setDefaultEmailAddress(
  800. this.user._id,
  801. this.newEmail,
  802. false,
  803. this.auditLog,
  804. true
  805. )
  806. // Emails are sent asynchronously. Wait a bit.
  807. await setTimeout(100)
  808. this.EmailHandler.promises.sendEmail.callCount.should.equal(4)
  809. for (const recipient of [
  810. this.user.email,
  811. this.newEmail,
  812. '2@a1.uni',
  813. '2021@foo.bar',
  814. ]) {
  815. expect(this.EmailHandler.promises.sendEmail).to.have.been.calledWith(
  816. 'securityAlert',
  817. sinon.match({ to: recipient })
  818. )
  819. }
  820. })
  821. it('should send to the most recently (re-)confirmed emails grouped by institution and by domain for unaffiliated emails (multiple institutions and unaffiliated email domains)', async function () {
  822. setUserEmails(this, [
  823. {
  824. email: '1@a1.uni',
  825. confirmedAt: new Date(2020, 0, 1),
  826. reConfirmedAt: new Date(2021, 2, 11),
  827. lastConfirmedAt: new Date(2021, 2, 11),
  828. default: false,
  829. affiliation: {
  830. institution: {
  831. id: 123,
  832. name: 'A1 University',
  833. },
  834. cachedConfirmedAt: '2020-01-01T18:25:01.639Z',
  835. cachedReconfirmedAt: '2021-03-11T18:25:01.639Z',
  836. },
  837. },
  838. {
  839. email: '1@b2.uni',
  840. confirmedAt: new Date(2019, 0, 1),
  841. reConfirmedAt: new Date(2022, 2, 11),
  842. lastConfirmedAt: new Date(2022, 2, 11),
  843. default: false,
  844. affiliation: {
  845. institution: {
  846. id: 234,
  847. name: 'B2 University',
  848. },
  849. cachedConfirmedAt: '2019-01-01T18:25:01.639Z',
  850. cachedReconfirmedAt: '2022-03-11T18:25:01.639Z',
  851. },
  852. },
  853. {
  854. email: '2020@foo.bar',
  855. confirmedAt: new Date(2020, 6, 1),
  856. lastConfirmedAt: new Date(2020, 6, 1),
  857. },
  858. {
  859. email: '2021@bar.foo',
  860. confirmedAt: new Date(2021, 6, 1),
  861. lastConfirmedAt: new Date(2021, 6, 1),
  862. },
  863. {
  864. email: this.user.email,
  865. confirmedAt: new Date(2021, 6, 1),
  866. lastConfirmedAt: new Date(2021, 6, 1),
  867. },
  868. {
  869. email: this.newEmail,
  870. confirmedAt: new Date(2021, 6, 1),
  871. lastConfirmedAt: new Date(2021, 6, 1),
  872. },
  873. ])
  874. await this.UserUpdater.promises.setDefaultEmailAddress(
  875. this.user._id,
  876. this.newEmail,
  877. false,
  878. this.auditLog,
  879. true
  880. )
  881. // Emails are sent asynchronously. Wait a bit.
  882. await setTimeout(100)
  883. this.EmailHandler.promises.sendEmail.callCount.should.equal(6)
  884. for (const recipient of [
  885. this.user.email,
  886. this.newEmail,
  887. '1@a1.uni',
  888. '1@b2.uni',
  889. '2020@foo.bar',
  890. '2021@bar.foo',
  891. ]) {
  892. expect(this.EmailHandler.promises.sendEmail).to.have.been.calledWith(
  893. 'securityAlert',
  894. sinon.match({ to: recipient })
  895. )
  896. }
  897. })
  898. describe('errors', function () {
  899. const anError = new Error('oops')
  900. describe('EmailHandler', function () {
  901. beforeEach(function () {
  902. this.EmailHandler.promises.sendEmail.rejects(anError)
  903. })
  904. it('should log but not pass back the error', async function () {
  905. await this.UserUpdater.promises.setDefaultEmailAddress(
  906. this.user._id,
  907. this.newEmail,
  908. false,
  909. this.auditLog,
  910. true
  911. )
  912. const loggerCall = this.logger.error.firstCall
  913. expect(loggerCall.args[0]).to.deep.equal({
  914. error: anError,
  915. userId: this.user._id,
  916. })
  917. expect(loggerCall.args[1]).to.contain(
  918. 'could not send security alert email when primary email changed'
  919. )
  920. })
  921. })
  922. })
  923. })
  924. })
  925. describe('confirmEmail', function () {
  926. it('should update the email record', async function () {
  927. await this.UserUpdater.promises.confirmEmail(
  928. this.user._id,
  929. this.user.email
  930. )
  931. expect(this.db.users.updateOne).to.have.been.calledWith(
  932. {
  933. _id: this.user._id,
  934. 'emails.email': this.user.email,
  935. },
  936. {
  937. $set: {
  938. 'emails.$.reconfirmedAt': new Date(),
  939. },
  940. $min: {
  941. 'emails.$.confirmedAt': new Date(),
  942. },
  943. }
  944. )
  945. })
  946. it('adds affiliation', async function () {
  947. await this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  948. this.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(true)
  949. sinon.assert.calledWith(
  950. this.InstitutionsAPI.promises.addAffiliation,
  951. this.user._id,
  952. this.newEmail,
  953. { confirmedAt: new Date() }
  954. )
  955. })
  956. it('handles errors', async function () {
  957. this.db.users.updateOne.rejects(new Error('nope'))
  958. await expect(
  959. this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  960. ).to.be.rejected
  961. })
  962. it('handle missed update', async function () {
  963. this.db.users.updateOne.resolves({ matchedCount: 0 })
  964. await expect(
  965. this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  966. ).to.be.rejected
  967. })
  968. it('validates email', async function () {
  969. expect(this.UserUpdater.promises.confirmEmail(this.user._id, '@')).to.be
  970. .rejected
  971. })
  972. it('handles affiliation errors', async function () {
  973. this.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
  974. await expect(
  975. this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  976. ).to.be.rejected
  977. expect(this.db.users.updateOne).to.not.have.been.called
  978. })
  979. it('refreshes features', async function () {
  980. await this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  981. sinon.assert.calledWith(
  982. this.FeaturesUpdater.promises.refreshFeatures,
  983. this.user._id
  984. )
  985. })
  986. it('should not call redundantPersonalSubscription when user is not on a commons license', async function () {
  987. this.InstitutionsAPI.promises.getUserAffiliations.resolves([])
  988. this.SubscriptionLocator.promises.getUserIndividualSubscription.resolves({
  989. planCode: 'personal',
  990. groupPlan: false,
  991. })
  992. await this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  993. sinon.assert.notCalled(
  994. this.NotificationsBuilder.promises.redundantPersonalSubscription
  995. )
  996. })
  997. it('calls to remove userFullEmails from AsyncLocalStorage', async function () {
  998. await this.UserUpdater.promises.confirmEmail(this.user._id, this.newEmail)
  999. expect(this.AsyncLocalStorage.removeItem).to.have.been.called
  1000. expect(this.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  1001. 'userFullEmails'
  1002. )
  1003. })
  1004. describe('with institution licence and subscription', function () {
  1005. beforeEach(async function () {
  1006. this.affiliation = {
  1007. email: this.newEmail,
  1008. licence: 'pro_plus',
  1009. institution: {
  1010. id: 123,
  1011. name: 'Institution',
  1012. },
  1013. }
  1014. this.InstitutionsAPI.promises.getUserAffiliations.resolves([
  1015. this.affiliation,
  1016. { email: 'other@email.edu' },
  1017. ])
  1018. this.SubscriptionLocator.promises.getUserIndividualSubscription.resolves(
  1019. {
  1020. planCode: 'personal',
  1021. groupPlan: false,
  1022. }
  1023. )
  1024. })
  1025. it('creates redundant subscription notification', async function () {
  1026. await this.UserUpdater.promises.confirmEmail(
  1027. this.user._id,
  1028. this.newEmail
  1029. )
  1030. sinon.assert.calledWith(
  1031. this.InstitutionsAPI.promises.getUserAffiliations,
  1032. this.user._id
  1033. )
  1034. sinon.assert.calledWith(
  1035. this.SubscriptionLocator.promises.getUserIndividualSubscription,
  1036. this.user._id
  1037. )
  1038. sinon.assert.calledWith(
  1039. this.NotificationsBuilder.promises.redundantPersonalSubscription,
  1040. {
  1041. institutionId: 123,
  1042. institutionName: 'Institution',
  1043. },
  1044. { _id: this.user._id }
  1045. )
  1046. })
  1047. })
  1048. })
  1049. describe('suspendUser', function () {
  1050. beforeEach(function () {
  1051. this.auditLog = {
  1052. initiatorId: 'abc123',
  1053. ip: '0.0.0.0',
  1054. }
  1055. })
  1056. it('should suspend the user', async function () {
  1057. await this.UserUpdater.promises.suspendUser(this.user._id, this.auditLog)
  1058. expect(this.db.users.updateOne).to.have.been.calledWith(
  1059. { _id: this.user._id, suspended: { $ne: true } },
  1060. { $set: { suspended: true } }
  1061. )
  1062. })
  1063. it('should remove sessions from redis', async function () {
  1064. await this.UserUpdater.promises.suspendUser(this.user._id, this.auditLog)
  1065. expect(
  1066. this.UserSessionsManager.promises.removeSessionsFromRedis
  1067. ).to.have.been.calledWith({ _id: this.user._id })
  1068. })
  1069. it('should log the suspension to the audit log', async function () {
  1070. await this.UserUpdater.promises.suspendUser(this.user._id, this.auditLog)
  1071. expect(
  1072. this.UserAuditLogHandler.promises.addEntry
  1073. ).to.have.been.calledWith(
  1074. this.user._id,
  1075. 'account-suspension',
  1076. this.auditLog.initiatorId,
  1077. this.auditLog.ip,
  1078. {}
  1079. )
  1080. })
  1081. it('should fire the removeDropbox hook', async function () {
  1082. await this.UserUpdater.promises.suspendUser(this.user._id, this.auditLog)
  1083. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  1084. 'removeDropbox',
  1085. this.user._id,
  1086. 'account-suspension'
  1087. )
  1088. })
  1089. it('should handle not finding a record to update', async function () {
  1090. this.db.users.updateOne.resolves({ matchedCount: 0 })
  1091. await expect(
  1092. this.UserUpdater.promises.suspendUser(this.user._id, this.auditLog)
  1093. ).to.be.rejectedWith(Errors.NotFoundError)
  1094. })
  1095. })
  1096. })