| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235 |
- import { vi, expect } from 'vitest'
- import { setTimeout } from 'node:timers/promises'
- import path from 'node:path'
- import sinon from 'sinon'
- import mongodb from 'mongodb-legacy'
- import tk from 'timekeeper'
- import MongoHelpers from '../../../../app/src/Features/Helpers/Mongo.mjs'
- import Errors from '../../../../app/src/Features/Errors/Errors.js'
- const { normalizeQuery } = MongoHelpers
- const { ObjectId } = mongodb
- const MODULE_PATH = path.join(
- import.meta.dirname,
- '../../../../app/src/Features/User/UserUpdater'
- )
- vi.mock('../../../../app/src/Features/Errors/Errors.js', () =>
- vi.importActual('../../../../app/src/Features/Errors/Errors.js')
- )
- describe('UserUpdater', function () {
- beforeEach(async function (ctx) {
- tk.freeze(Date.now())
- ctx.user = {
- _id: new ObjectId(),
- name: 'bob',
- email: 'hello@world.com',
- emails: [{ email: 'hello@world.com' }],
- }
- ctx.db = {
- users: {
- updateOne: sinon.stub().resolves({ matchedCount: 1, modifiedCount: 1 }),
- },
- }
- ctx.mongodb = {
- db: ctx.db,
- ObjectId,
- }
- ctx.UserGetter = {
- promises: {
- ensureUniqueEmailAddress: sinon.stub().resolves(),
- getUser: sinon.stub(),
- getUserByMainEmail: sinon.stub(),
- getUserFullEmails: sinon.stub(),
- getUserEmail: sinon.stub(),
- },
- }
- ctx.UserGetter.promises.getUser.withArgs(ctx.user._id).resolves(ctx.user)
- ctx.UserGetter.promises.getUserByMainEmail
- .withArgs(ctx.user.email)
- .resolves(ctx.user)
- ctx.UserGetter.promises.getUserFullEmails
- .withArgs(ctx.user._id)
- .resolves(ctx.user.emails)
- ctx.UserGetter.promises.getUserEmail
- .withArgs(ctx.user._id)
- .resolves(ctx.user.email)
- ctx.AnalyticsManager = {
- recordEventForUserInBackground: sinon.stub(),
- }
- ctx.InstitutionsAPI = {
- promises: {
- addAffiliation: sinon.stub().resolves(),
- removeAffiliation: sinon.stub().resolves(),
- getUserAffiliations: sinon.stub().resolves(),
- },
- }
- ctx.EmailHandler = {
- promises: {
- sendEmail: sinon.stub().resolves(),
- },
- }
- ctx.Features = {
- hasFeature: sinon.stub().returns(false),
- }
- ctx.FeaturesUpdater = {
- promises: {
- refreshFeatures: sinon.stub().resolves(),
- },
- }
- ctx.UserAuditLogHandler = {
- promises: {
- addEntry: sinon.stub().resolves(),
- },
- }
- ctx.SubscriptionLocator = {
- promises: {
- getUserIndividualSubscription: sinon.stub().resolves(),
- },
- }
- ctx.NotificationsBuilder = {
- promises: {
- redundantPersonalSubscription: sinon
- .stub()
- .returns({ create: () => {} }),
- },
- }
- ctx.Modules = {
- promises: {
- hooks: {
- fire: sinon.stub().resolves([]),
- },
- },
- }
- ctx.UserSessionsManager = {
- promises: {
- removeSessionsFromRedis: sinon.stub().resolves(),
- },
- }
- ctx.AsyncLocalStorage = {
- removeItem: sinon.stub(),
- }
- vi.doMock('../../../../app/src/Features/Helpers/Mongo', () => ({
- default: { normalizeQuery },
- }))
- vi.doMock('../../../../app/src/infrastructure/mongodb', () => ctx.mongodb)
- vi.doMock('../../../../app/src/Features/User/UserGetter', () => ({
- default: ctx.UserGetter,
- }))
- vi.doMock(
- '../../../../app/src/Features/Institutions/InstitutionsAPI',
- () => ({
- default: ctx.InstitutionsAPI,
- })
- )
- vi.doMock('../../../../app/src/Features/Email/EmailHandler', () => ({
- default: ctx.EmailHandler,
- }))
- vi.doMock('../../../../app/src/infrastructure/Features', () => ({
- default: ctx.Features,
- }))
- vi.doMock(
- '../../../../app/src/Features/Subscription/FeaturesUpdater',
- () => ({
- default: ctx.FeaturesUpdater,
- })
- )
- vi.doMock('@overleaf/settings', () => ({
- default: (ctx.settings = {}),
- }))
- vi.doMock(
- '../../../../app/src/Features/Subscription/RecurlyWrapper',
- () => ({
- default: ctx.RecurlyWrapper,
- })
- )
- vi.doMock('../../../../app/src/Features/User/UserAuditLogHandler', () => ({
- default: ctx.UserAuditLogHandler,
- }))
- vi.doMock(
- '../../../../app/src/Features/Analytics/AnalyticsManager',
- () => ({
- default: ctx.AnalyticsManager,
- })
- )
- vi.doMock(
- '../../../../app/src/Features/Subscription/SubscriptionLocator',
- () => ({
- default: ctx.SubscriptionLocator,
- })
- )
- vi.doMock(
- '../../../../app/src/Features/Notifications/NotificationsBuilder',
- () => ({
- default: ctx.NotificationsBuilder,
- })
- )
- vi.doMock('../../../../app/src/infrastructure/Modules', () => ({
- default: ctx.Modules,
- }))
- vi.doMock('../../../../app/src/Features/User/UserSessionsManager', () => ({
- default: ctx.UserSessionsManager,
- }))
- vi.doMock(
- '../../../../app/src/Features/User/ThirdPartyIdentityManager',
- () => ({
- default: ctx.ThirdPartyIdentityManager,
- })
- )
- vi.doMock('../../../../app/src/infrastructure/AsyncLocalStorage', () => ({
- default: ctx.AsyncLocalStorage,
- }))
- ctx.UserUpdater = (await import(MODULE_PATH)).default
- ctx.newEmail = 'bob@bob.com'
- })
- afterEach(function () {
- return tk.reset()
- })
- describe('addAffiliationForNewUser', function () {
- it('should not remove affiliationUnchecked flag if v1 returns an error', async function (ctx) {
- ctx.InstitutionsAPI.promises.addAffiliation.rejects()
- await expect(
- ctx.UserUpdater.promises.addAffiliationForNewUser(
- ctx.user._id,
- ctx.newEmail
- )
- ).to.be.rejected
- sinon.assert.notCalled(ctx.db.users.updateOne)
- })
- it('should remove affiliationUnchecked flag if v1 does not return an error', async function (ctx) {
- await ctx.UserUpdater.promises.addAffiliationForNewUser(
- ctx.user._id,
- ctx.newEmail
- )
- sinon.assert.calledOnce(ctx.db.users.updateOne)
- sinon.assert.calledWithMatch(
- ctx.db.users.updateOne,
- { _id: ctx.user._id, 'emails.email': ctx.newEmail },
- { $unset: { 'emails.$.affiliationUnchecked': 1 } }
- )
- })
- it('should not throw if removing affiliationUnchecked flag errors', async function (ctx) {
- ctx.db.users.updateOne.rejects(new Error('nope'))
- await ctx.UserUpdater.promises.addAffiliationForNewUser(
- ctx.user._id,
- ctx.newEmail
- )
- })
- it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
- await ctx.UserUpdater.promises.addAffiliationForNewUser(
- ctx.user._id,
- ctx.newEmail
- )
- expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
- 'userFullEmails'
- )
- })
- })
- describe('changeEmailAddress', function () {
- beforeEach(async function (ctx) {
- ctx.auditLog = {
- initiatorId: 'abc123',
- ipAddress: '0:0:0:0',
- }
- // After the email changed, make sure that UserGetter.getUser() returns a
- // user with the new email.
- ctx.UserGetter.promises.getUser
- .withArgs(ctx.user._id)
- .onCall(1)
- .resolves({
- ...ctx.user,
- emails: [...ctx.user.emails, { email: ctx.newEmail }],
- })
- // The main email changes as a result of the email change
- ctx.UserGetter.promises.getUserByMainEmail
- .withArgs(ctx.user.email)
- .resolves(null)
- ctx.user.emails.push({ email: ctx.newEmail })
- await ctx.UserUpdater.promises.changeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- })
- it('adds the new email', function (ctx) {
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- { _id: ctx.user._id, 'emails.email': { $ne: ctx.newEmail } },
- {
- $push: {
- emails: sinon.match({ email: ctx.newEmail }),
- },
- }
- )
- })
- it('adds the new affiliation', function (ctx) {
- ctx.InstitutionsAPI.promises.addAffiliation.should.have.been.calledWith(
- ctx.user._id,
- ctx.newEmail
- )
- })
- it('removes the old email', function (ctx) {
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- { _id: ctx.user._id, email: { $ne: ctx.user.email } },
- { $pull: { emails: { email: ctx.user.email } } }
- )
- })
- it('removes the affiliation', function (ctx) {
- expect(
- ctx.InstitutionsAPI.promises.removeAffiliation
- ).to.have.been.calledWith(ctx.user._id, ctx.user.email)
- })
- it('refreshes features', function (ctx) {
- sinon.assert.calledWith(
- ctx.FeaturesUpdater.promises.refreshFeatures,
- ctx.user._id
- )
- })
- it('sets the default email', function (ctx) {
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- { _id: ctx.user._id, 'emails.email': ctx.newEmail },
- {
- $set: sinon.match({
- email: ctx.newEmail,
- }),
- }
- )
- })
- it('fires userEmailChanged hook', function (ctx) {
- expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
- 'userEmailChanged',
- ctx.user,
- ctx.newEmail
- )
- expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
- 'updateAccountEmailAddress',
- ctx.user._id,
- ctx.newEmail
- )
- })
- it('validates email', async function (ctx) {
- await expect(
- ctx.UserUpdater.promises.changeEmailAddress(
- ctx.user._id,
- 'foo',
- ctx.auditLog
- )
- ).to.be.rejected
- })
- })
- describe('addEmailAddress', function () {
- it('adds the email', async function (ctx) {
- await ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- {},
- { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- )
- ctx.UserGetter.promises.ensureUniqueEmailAddress.should.have.been.called
- const reversedHostname = ctx.newEmail
- .split('@')[1]
- .split('')
- .reverse()
- .join('')
- ctx.db.users.updateOne.should.have.been.calledWith(
- { _id: ctx.user._id, 'emails.email': { $ne: ctx.newEmail } },
- {
- $push: {
- emails: {
- email: ctx.newEmail,
- createdAt: sinon.match.date,
- reversedHostname,
- },
- },
- }
- )
- })
- it('adds the affiliation', async function (ctx) {
- const affiliationOptions = {
- university: { id: 1 },
- role: 'Prof',
- department: 'Math',
- }
- await ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- affiliationOptions,
- { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- )
- ctx.InstitutionsAPI.promises.addAffiliation.should.have.been.calledWith(
- ctx.user._id,
- ctx.newEmail,
- affiliationOptions
- )
- })
- it('handles affiliation errors', async function (ctx) {
- ctx.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
- await expect(
- ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- {},
- { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- )
- ).to.be.rejected
- ctx.db.users.updateOne.should.not.have.been.called
- })
- it('validates the email', async function (ctx) {
- expect(
- ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- 'bar',
- {},
- { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- )
- ).to.be.rejected
- })
- it('updates the audit log', async function (ctx) {
- ctx.ip = '127:0:0:0'
- await ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- {},
- { initiatorId: ctx.user._id, ipAddress: ctx.ip }
- )
- ctx.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(true)
- const { args } = ctx.UserAuditLogHandler.promises.addEntry.lastCall
- expect(args[0]).to.equal(ctx.user._id)
- expect(args[1]).to.equal('add-email')
- expect(args[2]).to.equal(ctx.user._id)
- expect(args[3]).to.equal(ctx.ip)
- expect(args[4]).to.deep.equal({ newSecondaryEmail: ctx.newEmail })
- })
- describe('errors', function () {
- describe('via UserAuditLogHandler', function () {
- const anError = new Error('oops')
- beforeEach(function (ctx) {
- ctx.UserAuditLogHandler.promises.addEntry.rejects(anError)
- })
- it('should not add email and should return error', async function (ctx) {
- await expect(
- ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- {},
- { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- )
- ).to.be.rejectedWith(anError)
- expect(ctx.db.users.updateOne).to.not.have.been.called
- })
- })
- })
- it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
- await ctx.UserUpdater.promises.addEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- {},
- { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- )
- expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
- 'userFullEmails'
- )
- })
- })
- describe('removeEmailAddress', function () {
- beforeEach(function (ctx) {
- ctx.auditLog = { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
- })
- it('removes the email', async function (ctx) {
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- { _id: ctx.user._id, email: { $ne: ctx.newEmail } },
- { $pull: { emails: { email: ctx.newEmail } } }
- )
- })
- it('removes the affiliation', async function (ctx) {
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- expect(ctx.InstitutionsAPI.promises.removeAffiliation).to.have.been
- .calledOnce
- const { args } = ctx.InstitutionsAPI.promises.removeAffiliation.lastCall
- args[0].should.equal(ctx.user._id)
- args[1].should.equal(ctx.newEmail)
- })
- it('refreshes features', async function (ctx) {
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- sinon.assert.calledWith(
- ctx.FeaturesUpdater.promises.refreshFeatures,
- ctx.user._id
- )
- })
- it('handles Mongo errors', async function (ctx) {
- const anError = new Error('nope')
- ctx.db.users.updateOne.rejects(anError)
- await expect(
- ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- ).to.be.rejected
- expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
- .called
- })
- it('handles missed update', async function (ctx) {
- ctx.db.users.updateOne.resolves({ matchedCount: 0 })
- await expect(
- ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- ).to.be.rejectedWith('Cannot remove email')
- expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
- .called
- })
- it('handles an affiliation error', async function (ctx) {
- const anError = new Error('nope')
- ctx.InstitutionsAPI.promises.removeAffiliation.rejects(anError)
- await expect(
- ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- ).to.be.rejected
- expect(ctx.db.users.updateOne).not.to.have.been.called
- expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
- .called
- })
- it('throws an error when removing the primary email', async function (ctx) {
- await expect(
- ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.user.email,
- ctx.auditLog
- )
- ).to.be.rejectedWith('cannot remove primary email')
- expect(ctx.db.users.updateOne).not.to.have.been.called
- expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
- .called
- })
- it('validates the email', function (ctx) {
- expect(
- ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- 'baz',
- ctx.auditLog
- )
- ).to.be.rejectedWith('invalid email')
- })
- it('skips email validation when skipParseEmail included', async function (ctx) {
- const skipParseEmail = true
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- 'baz',
- ctx.auditLog,
- skipParseEmail
- )
- })
- it('throws an error when skipParseEmail included but email is not a string', async function (ctx) {
- const skipParseEmail = true
- await expect(
- ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- 1,
- ctx.auditLog,
- skipParseEmail
- )
- ).to.be.rejectedWith('email must be a string')
- })
- it('logs the removal to the audit log', async function (ctx) {
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
- ctx.user._id,
- 'remove-email',
- ctx.auditLog.initiatorId,
- ctx.auditLog.ipAddress,
- {
- removedEmail: ctx.newEmail,
- }
- )
- })
- it('logs the removal from script to the audit log', async function (ctx) {
- ctx.auditLog = {
- initiatorId: undefined,
- ipAddress: '0.0.0.0',
- extraInfo: {
- script: true,
- },
- }
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
- ctx.user._id,
- 'remove-email',
- ctx.auditLog.initiatorId,
- ctx.auditLog.ipAddress,
- {
- removedEmail: ctx.newEmail,
- script: true,
- }
- )
- })
- it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
- await ctx.UserUpdater.promises.removeEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- ctx.auditLog
- )
- expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
- 'userFullEmails'
- )
- })
- })
- describe('setDefaultEmailAddress', function () {
- function setUserEmails(test, emails) {
- test.user.emails = emails
- test.UserGetter.promises.getUserFullEmails
- .withArgs(test.user._id)
- .resolves(emails)
- }
- beforeEach(function (ctx) {
- ctx.auditLog = {
- initiatorId: ctx.user,
- ipAddress: '0:0:0:0',
- }
- setUserEmails(ctx, [
- {
- email: ctx.newEmail,
- confirmedAt: new Date(),
- },
- ])
- })
- it('set default', async function (ctx) {
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- { _id: ctx.user._id, 'emails.email': ctx.newEmail },
- {
- $set: {
- email: ctx.newEmail,
- lastPrimaryEmailCheck: sinon.match.date,
- },
- }
- )
- })
- it('fires userEmailChanged hook', async function (ctx) {
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
- 'userEmailChanged',
- ctx.user,
- ctx.newEmail
- )
- expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
- 'updateAccountEmailAddress',
- ctx.user._id,
- ctx.newEmail
- )
- })
- it('handles Mongo errors', async function (ctx) {
- ctx.db.users.updateOne = sinon.stub().rejects(Error('nope'))
- await expect(
- ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- ).to.be.rejected
- })
- it('handles missed updates', async function (ctx) {
- ctx.db.users.updateOne.resolves({ matchedCount: 0 })
- await expect(
- ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- ).to.be.rejected
- })
- it('validates the email', async function (ctx) {
- await expect(
- ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- '.edu',
- false,
- ctx.auditLog
- )
- ).to.be.rejected
- })
- it('updates the audit log', async function (ctx) {
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
- ctx.user._id,
- 'change-primary-email',
- ctx.auditLog.initiatorId,
- ctx.auditLog.ipAddress,
- {
- newPrimaryEmail: ctx.newEmail,
- oldPrimaryEmail: ctx.user.email,
- }
- )
- })
- it('blocks email update if audit log returns an error', async function (ctx) {
- ctx.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
- await expect(
- ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- ).to.be.rejected
- expect(ctx.db.users.updateOne).to.not.have.been.called
- })
- it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
- 'userFullEmails'
- )
- })
- describe('when email not confirmed', function () {
- beforeEach(function (ctx) {
- setUserEmails(ctx, [
- {
- email: ctx.newEmail,
- confirmedAt: null,
- },
- ])
- })
- it('should throw an error', async function (ctx) {
- await expect(
- ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog
- )
- ).to.be.rejectedWith(Errors.UnconfirmedEmailError)
- expect(ctx.db.users.updateOne).to.not.have.been.called
- })
- })
- describe('when email does not belong to user', function () {
- beforeEach(function (ctx) {
- setUserEmails(ctx, [])
- ctx.UserUpdater.promises.updateUser = sinon.stub()
- })
- it('should callback with error', function (ctx) {
- ctx.UserUpdater.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog,
- error => {
- expect(error).to.exist
- expect(error.name).to.equal('Error')
- ctx.UserUpdater.promises.updateUser.callCount.should.equal(0)
- }
- )
- })
- })
- describe('security alert', function () {
- it('should be sent to old and new email when sendSecurityAlert=true', async function (ctx) {
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog,
- true
- )
- // Emails are sent asynchronously. Wait a bit.
- await setTimeout(100)
- ctx.EmailHandler.promises.sendEmail.callCount.should.equal(2)
- for (const recipient of [ctx.user.email, ctx.newEmail]) {
- expect(ctx.EmailHandler.promises.sendEmail).to.have.been.calledWith(
- 'securityAlert',
- sinon.match({ to: recipient })
- )
- }
- })
- it('should send to the most recently (re-)confirmed emails grouped by institution and by domain for unaffiliated emails', async function (ctx) {
- setUserEmails(ctx, [
- {
- email: '1@a1.uni',
- confirmedAt: new Date(2020, 0, 1),
- reConfirmedAt: new Date(2021, 2, 11),
- lastConfirmedAt: new Date(2021, 2, 11),
- default: false,
- affiliation: {
- institution: {
- id: 123,
- name: 'A1 University',
- },
- cachedConfirmedAt: '2020-01-01T18:25:01.639Z',
- cachedReconfirmedAt: '2021-03-11T18:25:01.639Z',
- },
- },
- {
- email: '2@a1.uni',
- confirmedAt: new Date(2019, 0, 1),
- reConfirmedAt: new Date(2022, 2, 11),
- lastConfirmedAt: new Date(2022, 2, 11),
- default: false,
- affiliation: {
- institution: {
- id: 123,
- name: 'A1 University',
- },
- cachedConfirmedAt: '2019-01-01T18:25:01.639Z',
- cachedReconfirmedAt: '2022-03-11T18:25:01.639Z',
- },
- },
- {
- email: '2020@foo.bar',
- confirmedAt: new Date(2020, 6, 1),
- lastConfirmedAt: new Date(2020, 6, 1),
- },
- {
- email: '2021@foo.bar',
- confirmedAt: new Date(2021, 6, 1),
- lastConfirmedAt: new Date(2021, 6, 1),
- },
- {
- email: ctx.user.email,
- confirmedAt: new Date(2021, 6, 1),
- lastConfirmedAt: new Date(2021, 6, 1),
- },
- {
- email: ctx.newEmail,
- confirmedAt: new Date(2021, 6, 1),
- lastConfirmedAt: new Date(2021, 6, 1),
- },
- ])
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog,
- true
- )
- // Emails are sent asynchronously. Wait a bit.
- await setTimeout(100)
- ctx.EmailHandler.promises.sendEmail.callCount.should.equal(4)
- for (const recipient of [
- ctx.user.email,
- ctx.newEmail,
- '2@a1.uni',
- '2021@foo.bar',
- ]) {
- expect(ctx.EmailHandler.promises.sendEmail).to.have.been.calledWith(
- 'securityAlert',
- sinon.match({ to: recipient })
- )
- }
- })
- 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 (ctx) {
- setUserEmails(ctx, [
- {
- email: '1@a1.uni',
- confirmedAt: new Date(2020, 0, 1),
- reConfirmedAt: new Date(2021, 2, 11),
- lastConfirmedAt: new Date(2021, 2, 11),
- default: false,
- affiliation: {
- institution: {
- id: 123,
- name: 'A1 University',
- },
- cachedConfirmedAt: '2020-01-01T18:25:01.639Z',
- cachedReconfirmedAt: '2021-03-11T18:25:01.639Z',
- },
- },
- {
- email: '1@b2.uni',
- confirmedAt: new Date(2019, 0, 1),
- reConfirmedAt: new Date(2022, 2, 11),
- lastConfirmedAt: new Date(2022, 2, 11),
- default: false,
- affiliation: {
- institution: {
- id: 234,
- name: 'B2 University',
- },
- cachedConfirmedAt: '2019-01-01T18:25:01.639Z',
- cachedReconfirmedAt: '2022-03-11T18:25:01.639Z',
- },
- },
- {
- email: '2020@foo.bar',
- confirmedAt: new Date(2020, 6, 1),
- lastConfirmedAt: new Date(2020, 6, 1),
- },
- {
- email: '2021@bar.foo',
- confirmedAt: new Date(2021, 6, 1),
- lastConfirmedAt: new Date(2021, 6, 1),
- },
- {
- email: ctx.user.email,
- confirmedAt: new Date(2021, 6, 1),
- lastConfirmedAt: new Date(2021, 6, 1),
- },
- {
- email: ctx.newEmail,
- confirmedAt: new Date(2021, 6, 1),
- lastConfirmedAt: new Date(2021, 6, 1),
- },
- ])
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog,
- true
- )
- // Emails are sent asynchronously. Wait a bit.
- await setTimeout(100)
- ctx.EmailHandler.promises.sendEmail.callCount.should.equal(6)
- for (const recipient of [
- ctx.user.email,
- ctx.newEmail,
- '1@a1.uni',
- '1@b2.uni',
- '2020@foo.bar',
- '2021@bar.foo',
- ]) {
- expect(ctx.EmailHandler.promises.sendEmail).to.have.been.calledWith(
- 'securityAlert',
- sinon.match({ to: recipient })
- )
- }
- })
- describe('errors', function () {
- const anError = new Error('oops')
- describe('EmailHandler', function () {
- beforeEach(function (ctx) {
- ctx.EmailHandler.promises.sendEmail.rejects(anError)
- })
- it('should log but not pass back the error', async function (ctx) {
- await ctx.UserUpdater.promises.setDefaultEmailAddress(
- ctx.user._id,
- ctx.newEmail,
- false,
- ctx.auditLog,
- true
- )
- const loggerCall = ctx.logger.error.mock.calls[0]
- expect(loggerCall[0]).to.deep.equal({
- error: anError,
- userId: ctx.user._id,
- })
- expect(loggerCall[1]).to.contain(
- 'could not send security alert email when primary email changed'
- )
- })
- })
- })
- })
- })
- describe('confirmEmail', function () {
- it('should update the email record', async function (ctx) {
- await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.user.email)
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- {
- _id: ctx.user._id,
- 'emails.email': ctx.user.email,
- },
- {
- $set: {
- 'emails.$.reconfirmedAt': new Date(),
- },
- $min: {
- 'emails.$.confirmedAt': new Date(),
- },
- }
- )
- })
- it('adds affiliation', async function (ctx) {
- await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- ctx.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(true)
- sinon.assert.calledWith(
- ctx.InstitutionsAPI.promises.addAffiliation,
- ctx.user._id,
- ctx.newEmail,
- { confirmedAt: new Date() }
- )
- })
- it('handles errors', async function (ctx) {
- ctx.db.users.updateOne.rejects(new Error('nope'))
- await expect(
- ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- ).to.be.rejected
- })
- it('handle missed update', async function (ctx) {
- ctx.db.users.updateOne.resolves({ matchedCount: 0 })
- await expect(
- ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- ).to.be.rejected
- })
- it('validates email', async function (ctx) {
- expect(ctx.UserUpdater.promises.confirmEmail(ctx.user._id, '@')).to.be
- .rejected
- })
- it('handles affiliation errors', async function (ctx) {
- ctx.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
- await expect(
- ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- ).to.be.rejected
- expect(ctx.db.users.updateOne).to.not.have.been.called
- })
- it('refreshes features', async function (ctx) {
- await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- sinon.assert.calledWith(
- ctx.FeaturesUpdater.promises.refreshFeatures,
- ctx.user._id
- )
- })
- it('should not call redundantPersonalSubscription when user is not on a commons license', async function (ctx) {
- ctx.InstitutionsAPI.promises.getUserAffiliations.resolves([])
- ctx.SubscriptionLocator.promises.getUserIndividualSubscription.resolves({
- planCode: 'personal',
- groupPlan: false,
- })
- await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- sinon.assert.notCalled(
- ctx.NotificationsBuilder.promises.redundantPersonalSubscription
- )
- })
- it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
- await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- expect(ctx.AsyncLocalStorage.removeItem).to.have.been.called
- expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
- 'userFullEmails'
- )
- })
- describe('with institution licence and subscription', function () {
- beforeEach(async function (ctx) {
- ctx.affiliation = {
- email: ctx.newEmail,
- licence: 'pro_plus',
- institution: {
- id: 123,
- name: 'Institution',
- },
- }
- ctx.InstitutionsAPI.promises.getUserAffiliations.resolves([
- ctx.affiliation,
- { email: 'other@email.edu' },
- ])
- ctx.SubscriptionLocator.promises.getUserIndividualSubscription.resolves(
- {
- planCode: 'personal',
- groupPlan: false,
- }
- )
- })
- it('creates redundant subscription notification', async function (ctx) {
- await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
- sinon.assert.calledWith(
- ctx.InstitutionsAPI.promises.getUserAffiliations,
- ctx.user._id
- )
- sinon.assert.calledWith(
- ctx.SubscriptionLocator.promises.getUserIndividualSubscription,
- ctx.user._id
- )
- sinon.assert.calledWith(
- ctx.NotificationsBuilder.promises.redundantPersonalSubscription,
- {
- institutionId: 123,
- institutionName: 'Institution',
- },
- { _id: ctx.user._id }
- )
- })
- })
- })
- describe('suspendUser', function () {
- beforeEach(function (ctx) {
- ctx.auditLog = {
- initiatorId: 'abc123',
- ip: '0.0.0.0',
- }
- })
- it('should suspend the user', async function (ctx) {
- await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
- expect(ctx.db.users.updateOne).to.have.been.calledWith(
- { _id: ctx.user._id, suspended: { $ne: true } },
- { $set: { suspended: true } }
- )
- })
- it('should remove sessions from redis', async function (ctx) {
- await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
- expect(
- ctx.UserSessionsManager.promises.removeSessionsFromRedis
- ).to.have.been.calledWith({ _id: ctx.user._id })
- })
- it('should log the suspension to the audit log', async function (ctx) {
- await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
- expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
- ctx.user._id,
- 'account-suspension',
- ctx.auditLog.initiatorId,
- ctx.auditLog.ip,
- {}
- )
- })
- it('should fire the removeDropbox hook', async function (ctx) {
- await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
- expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
- 'removeDropbox',
- ctx.user._id,
- 'account-suspension'
- )
- })
- it('should handle not finding a record to update', async function (ctx) {
- ctx.db.users.updateOne.resolves({ matchedCount: 0 })
- await expect(
- ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
- ).to.be.rejectedWith(Errors.NotFoundError)
- })
- })
- })
|