UserDeleterTests.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. const { expect } = require('chai')
  2. const sinon = require('sinon')
  3. const tk = require('timekeeper')
  4. const moment = require('moment')
  5. const SandboxedModule = require('sandboxed-module')
  6. const Errors = require('../../../../app/src/Features/Errors/Errors')
  7. const ObjectId = require('mongoose').Types.ObjectId
  8. const { User } = require('../helpers/models/User')
  9. const { DeletedUser } = require('../helpers/models/DeletedUser')
  10. const modulePath = '../../../../app/src/Features/User/UserDeleter.js'
  11. describe('UserDeleter', function () {
  12. beforeEach(function () {
  13. tk.freeze(Date.now())
  14. this.userId = new ObjectId()
  15. this.UserMock = sinon.mock(User)
  16. this.DeletedUserMock = sinon.mock(DeletedUser)
  17. this.mockedUser = sinon.mock(
  18. new User({
  19. _id: this.userId,
  20. email: 'bob@bob.com',
  21. lastLoggedIn: Date.now() + 1000,
  22. signUpDate: Date.now() + 2000,
  23. loginCount: 10,
  24. overleaf: {
  25. id: 1234,
  26. },
  27. refered_users: ['wombat', 'potato'],
  28. refered_user_count: 2,
  29. referal_id: ['giraffe'],
  30. })
  31. )
  32. this.user = this.mockedUser.object
  33. this.NewsletterManager = {
  34. promises: {
  35. unsubscribe: sinon.stub().resolves(),
  36. },
  37. }
  38. this.ProjectDeleter = {
  39. promises: {
  40. deleteUsersProjects: sinon.stub().resolves(),
  41. },
  42. }
  43. this.SubscriptionHandler = {
  44. promises: {
  45. cancelSubscription: sinon.stub().resolves(),
  46. },
  47. }
  48. this.SubscriptionUpdater = {
  49. promises: {
  50. removeUserFromAllGroups: sinon.stub().resolves(),
  51. },
  52. }
  53. this.SubscriptionLocator = {
  54. promises: {
  55. getUsersSubscription: sinon.stub().resolves(),
  56. },
  57. }
  58. this.UserMembershipsHandler = {
  59. promises: {
  60. removeUserFromAllEntities: sinon.stub().resolves(),
  61. },
  62. }
  63. this.UserSessionsManager = {
  64. promises: {
  65. revokeAllUserSessions: sinon.stub().resolves(),
  66. },
  67. }
  68. this.InstitutionsApi = {
  69. promises: {
  70. deleteAffiliations: sinon.stub().resolves(),
  71. },
  72. }
  73. this.UserAuditLogEntry = {
  74. deleteMany: sinon.stub().returns({ exec: sinon.stub().resolves() }),
  75. }
  76. this.Modules = {
  77. promises: { hooks: { fire: sinon.stub().resolves() } },
  78. }
  79. this.Feedback = {
  80. deleteMany: sinon.stub().returns({ exec: sinon.stub().resolves() }),
  81. }
  82. this.OnboardingDataCollectionManager = {
  83. deleteOnboardingDataCollection: sinon.stub().resolves(),
  84. }
  85. this.EmailHandler = {
  86. promises: {
  87. sendEmail: sinon.stub().resolves(),
  88. },
  89. }
  90. this.UserDeleter = SandboxedModule.require(modulePath, {
  91. requires: {
  92. '../../models/User': { User },
  93. '../../models/DeletedUser': { DeletedUser },
  94. '../../models/Feedback': { Feedback: this.Feedback },
  95. '../Newsletter/NewsletterManager': this.NewsletterManager,
  96. './UserSessionsManager': this.UserSessionsManager,
  97. '../Subscription/SubscriptionHandler': this.SubscriptionHandler,
  98. '../Subscription/SubscriptionUpdater': this.SubscriptionUpdater,
  99. '../Subscription/SubscriptionLocator': this.SubscriptionLocator,
  100. '../UserMembership/UserMembershipsHandler': this.UserMembershipsHandler,
  101. '../Project/ProjectDeleter': this.ProjectDeleter,
  102. '../Institutions/InstitutionsAPI': this.InstitutionsApi,
  103. '../../models/UserAuditLogEntry': {
  104. UserAuditLogEntry: this.UserAuditLogEntry,
  105. },
  106. '../../infrastructure/Modules': this.Modules,
  107. '../OnboardingDataCollection/OnboardingDataCollectionManager':
  108. this.OnboardingDataCollectionManager,
  109. '../Email/EmailHandler': this.EmailHandler,
  110. },
  111. })
  112. })
  113. afterEach(function () {
  114. this.DeletedUserMock.restore()
  115. this.UserMock.restore()
  116. this.mockedUser.restore()
  117. })
  118. describe('deleteUser', function () {
  119. beforeEach(function () {
  120. this.UserMock.expects('findById')
  121. .withArgs(this.userId)
  122. .chain('exec')
  123. .resolves(this.user)
  124. })
  125. describe('when the user can be deleted', function () {
  126. beforeEach(function () {
  127. this.deletedUser = {
  128. user: this.user,
  129. deleterData: {
  130. deletedAt: new Date(),
  131. deletedUserId: this.userId,
  132. deleterIpAddress: undefined,
  133. deleterId: undefined,
  134. deletedUserLastLoggedIn: this.user.lastLoggedIn,
  135. deletedUserSignUpDate: this.user.signUpDate,
  136. deletedUserLoginCount: this.user.loginCount,
  137. deletedUserReferralId: this.user.referal_id,
  138. deletedUserReferredUsers: this.user.refered_users,
  139. deletedUserReferredUserCount: this.user.refered_user_count,
  140. deletedUserOverleafId: this.user.overleaf.id,
  141. },
  142. }
  143. })
  144. describe('when no options are passed', function () {
  145. beforeEach(function () {
  146. this.DeletedUserMock.expects('updateOne')
  147. .withArgs(
  148. { 'deleterData.deletedUserId': this.userId },
  149. this.deletedUser,
  150. { upsert: true }
  151. )
  152. .chain('exec')
  153. .resolves()
  154. })
  155. describe('when unsubscribing in Mailchimp succeeds', function () {
  156. beforeEach(function () {
  157. this.UserMock.expects('deleteOne')
  158. .withArgs({ _id: this.userId })
  159. .chain('exec')
  160. .resolves()
  161. })
  162. it('should find and the user in mongo by its id', async function () {
  163. await this.UserDeleter.promises.deleteUser(this.userId, {})
  164. this.UserMock.verify()
  165. })
  166. it('should delete the user from mailchimp', async function () {
  167. await this.UserDeleter.promises.deleteUser(this.userId, {})
  168. expect(
  169. this.NewsletterManager.promises.unsubscribe
  170. ).to.have.been.calledWith(this.user, { delete: true })
  171. })
  172. it('should delete all the projects of a user', async function () {
  173. await this.UserDeleter.promises.deleteUser(this.userId, {})
  174. expect(
  175. this.ProjectDeleter.promises.deleteUsersProjects
  176. ).to.have.been.calledWith(this.userId)
  177. })
  178. it("should cancel the user's subscription", async function () {
  179. await this.UserDeleter.promises.deleteUser(this.userId, {})
  180. expect(
  181. this.SubscriptionHandler.promises.cancelSubscription
  182. ).to.have.been.calledWith(this.user)
  183. })
  184. it('should delete user affiliations', async function () {
  185. await this.UserDeleter.promises.deleteUser(this.userId, {})
  186. expect(
  187. this.InstitutionsApi.promises.deleteAffiliations
  188. ).to.have.been.calledWith(this.userId)
  189. })
  190. it('should fire the deleteUser hook for modules', async function () {
  191. await this.UserDeleter.promises.deleteUser(this.userId, {})
  192. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  193. 'deleteUser',
  194. this.userId
  195. )
  196. })
  197. it('should stop the user sessions', async function () {
  198. await this.UserDeleter.promises.deleteUser(this.userId, {})
  199. expect(
  200. this.UserSessionsManager.promises.revokeAllUserSessions
  201. ).to.have.been.calledWith(this.userId, [])
  202. })
  203. it('should remove user from group subscriptions', async function () {
  204. await this.UserDeleter.promises.deleteUser(this.userId, {})
  205. expect(
  206. this.SubscriptionUpdater.promises.removeUserFromAllGroups
  207. ).to.have.been.calledWith(this.userId)
  208. })
  209. it('should remove user memberships', async function () {
  210. await this.UserDeleter.promises.deleteUser(this.userId, {})
  211. expect(
  212. this.UserMembershipsHandler.promises.removeUserFromAllEntities
  213. ).to.have.been.calledWith(this.userId)
  214. })
  215. it('rejects if the user is a subscription admin', async function () {
  216. this.SubscriptionLocator.promises.getUsersSubscription.rejects({
  217. _id: 'some-subscription',
  218. })
  219. await expect(this.UserDeleter.promises.deleteUser(this.userId, {}))
  220. .to.be.rejected
  221. })
  222. it('should create a deletedUser', async function () {
  223. await this.UserDeleter.promises.deleteUser(this.userId, {})
  224. this.DeletedUserMock.verify()
  225. })
  226. it('should email the user', async function () {
  227. await this.UserDeleter.promises.deleteUser(this.userId, {})
  228. const emailOptions = {
  229. to: 'bob@bob.com',
  230. action: 'account deleted',
  231. actionDescribed: 'your Overleaf account was deleted',
  232. }
  233. expect(
  234. this.EmailHandler.promises.sendEmail
  235. ).to.have.been.calledWith('securityAlert', emailOptions)
  236. })
  237. })
  238. describe('when unsubscribing from mailchimp fails', function () {
  239. beforeEach(function () {
  240. this.NewsletterManager.promises.unsubscribe.rejects(
  241. new Error('something went wrong')
  242. )
  243. })
  244. it('should return an error and not delete the user', async function () {
  245. await expect(this.UserDeleter.promises.deleteUser(this.userId, {}))
  246. .to.be.rejected
  247. this.UserMock.verify()
  248. })
  249. })
  250. describe('when called as a callback', function () {
  251. beforeEach(function () {
  252. this.UserMock.expects('deleteOne')
  253. .withArgs({ _id: this.userId })
  254. .chain('exec')
  255. .resolves()
  256. })
  257. it('should delete the user', function (done) {
  258. this.UserDeleter.deleteUser(this.userId, {}, err => {
  259. expect(err).not.to.exist
  260. this.UserMock.verify()
  261. this.DeletedUserMock.verify()
  262. done()
  263. })
  264. })
  265. })
  266. })
  267. describe('when a user and IP address are specified', function () {
  268. beforeEach(function () {
  269. this.ipAddress = '1.2.3.4'
  270. this.deleterId = new ObjectId()
  271. this.deletedUser.deleterData.deleterIpAddress = this.ipAddress
  272. this.deletedUser.deleterData.deleterId = this.deleterId
  273. this.DeletedUserMock.expects('updateOne')
  274. .withArgs(
  275. { 'deleterData.deletedUserId': this.userId },
  276. this.deletedUser,
  277. { upsert: true }
  278. )
  279. .chain('exec')
  280. .resolves()
  281. this.UserMock.expects('deleteOne')
  282. .withArgs({ _id: this.userId })
  283. .chain('exec')
  284. .resolves()
  285. })
  286. it('should add the deleted user id and ip address to the deletedUser', async function () {
  287. await this.UserDeleter.promises.deleteUser(this.userId, {
  288. deleterUser: { _id: this.deleterId },
  289. ipAddress: this.ipAddress,
  290. })
  291. this.DeletedUserMock.verify()
  292. })
  293. describe('when called as a callback', function () {
  294. it('should delete the user', function (done) {
  295. this.UserDeleter.deleteUser(
  296. this.userId,
  297. {
  298. deleterUser: { _id: this.deleterId },
  299. ipAddress: this.ipAddress,
  300. },
  301. err => {
  302. expect(err).not.to.exist
  303. this.UserMock.verify()
  304. this.DeletedUserMock.verify()
  305. done()
  306. }
  307. )
  308. })
  309. })
  310. })
  311. })
  312. describe('when the user cannot be deleted because they are a subscription admin', function () {
  313. beforeEach(function () {
  314. this.SubscriptionLocator.promises.getUsersSubscription.resolves({
  315. _id: 'some-subscription',
  316. })
  317. })
  318. it('fails with a SubscriptionAdminDeletionError', async function () {
  319. await expect(
  320. this.UserDeleter.promises.deleteUser(this.userId)
  321. ).to.be.rejectedWith(Errors.SubscriptionAdminDeletionError)
  322. })
  323. it('should not create a deletedUser', async function () {
  324. await expect(this.UserDeleter.promises.deleteUser(this.userId)).to.be
  325. .rejected
  326. this.DeletedUserMock.verify()
  327. })
  328. it('should not remove the user from mongo', async function () {
  329. await expect(this.UserDeleter.promises.deleteUser(this.userId)).to.be
  330. .rejected
  331. this.UserMock.verify()
  332. })
  333. })
  334. })
  335. describe('ensureCanDeleteUser', function () {
  336. it('should not return error when user can be deleted', async function () {
  337. this.SubscriptionLocator.promises.getUsersSubscription.resolves(null)
  338. let error
  339. try {
  340. await this.UserDeleter.promises.ensureCanDeleteUser(this.user)
  341. } catch (e) {
  342. error = e
  343. } finally {
  344. expect(error).not.to.exist
  345. }
  346. })
  347. it('should return custom error when user is group admin', async function () {
  348. this.SubscriptionLocator.promises.getUsersSubscription.resolves({
  349. _id: '123abc',
  350. })
  351. let error
  352. try {
  353. await this.UserDeleter.promises.ensureCanDeleteUser(this.user)
  354. } catch (e) {
  355. error = e
  356. } finally {
  357. expect(error).to.be.instanceof(Errors.SubscriptionAdminDeletionError)
  358. }
  359. })
  360. it('propagates errors', async function () {
  361. this.SubscriptionLocator.promises.getUsersSubscription.rejects(
  362. new Error('Some error')
  363. )
  364. let error
  365. try {
  366. await this.UserDeleter.promises.ensureCanDeleteUser(this.user)
  367. } catch (e) {
  368. error = e
  369. } finally {
  370. expect(error).to.be.instanceof(Error)
  371. }
  372. })
  373. })
  374. describe('expireDeletedUsersAfterDuration', function () {
  375. const userId1 = new ObjectId()
  376. const userId2 = new ObjectId()
  377. beforeEach(function () {
  378. this.deletedUsers = [
  379. {
  380. user: { _id: userId1 },
  381. deleterData: { deletedUserId: userId1 },
  382. save: sinon.stub().resolves(),
  383. },
  384. {
  385. user: { _id: userId2 },
  386. deleterData: { deletedUserId: userId2 },
  387. save: sinon.stub().resolves(),
  388. },
  389. ]
  390. this.DeletedUserMock.expects('find')
  391. .withArgs({
  392. 'deleterData.deletedAt': {
  393. $lt: new Date(moment().subtract(90, 'days')),
  394. },
  395. user: {
  396. $ne: null,
  397. },
  398. })
  399. .chain('exec')
  400. .resolves(this.deletedUsers)
  401. for (const deletedUser of this.deletedUsers) {
  402. this.DeletedUserMock.expects('findOne')
  403. .withArgs({
  404. 'deleterData.deletedUserId': deletedUser.deleterData.deletedUserId,
  405. })
  406. .chain('exec')
  407. .resolves(deletedUser)
  408. }
  409. })
  410. it('clears data from all deleted users', async function () {
  411. await this.UserDeleter.promises.expireDeletedUsersAfterDuration()
  412. for (const deletedUser of this.deletedUsers) {
  413. expect(deletedUser.user).to.be.undefined
  414. expect(deletedUser.save.called).to.be.true
  415. }
  416. })
  417. it('deletes audit logs for all deleted users', async function () {
  418. await this.UserDeleter.promises.expireDeletedUsersAfterDuration()
  419. for (const deletedUser of this.deletedUsers) {
  420. expect(this.UserAuditLogEntry.deleteMany).to.have.been.calledWith({
  421. userId: deletedUser.deleterData.deletedUserId,
  422. })
  423. }
  424. })
  425. })
  426. describe('expireDeletedUser', function () {
  427. beforeEach(function () {
  428. this.mockedDeletedUser = sinon.mock(
  429. new DeletedUser({
  430. user: this.user,
  431. deleterData: {
  432. deleterIpAddress: '1.1.1.1',
  433. deletedUserId: this.userId,
  434. },
  435. })
  436. )
  437. this.deletedUser = this.mockedDeletedUser.object
  438. this.mockedDeletedUser.expects('save').resolves()
  439. this.DeletedUserMock.expects('findOne')
  440. .withArgs({ 'deleterData.deletedUserId': this.userId })
  441. .chain('exec')
  442. .resolves(this.deletedUser)
  443. })
  444. afterEach(function () {
  445. this.mockedDeletedUser.restore()
  446. })
  447. it('should find the user by user ID', async function () {
  448. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  449. this.DeletedUserMock.verify()
  450. })
  451. it('should remove the user data from mongo', async function () {
  452. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  453. expect(this.deletedUser.user).not.to.exist
  454. })
  455. it('should remove the IP address from mongo', async function () {
  456. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  457. expect(this.deletedUser.deleterData.ipAddress).not.to.exist
  458. })
  459. it('should not delete other deleterData fields', async function () {
  460. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  461. expect(this.deletedUser.deleterData.deletedUserId).to.equal(this.userId)
  462. })
  463. it('should save the record to mongo', async function () {
  464. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  465. this.mockedDeletedUser.verify()
  466. })
  467. it('should fire the expireDeletedUser hook for modules', async function () {
  468. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  469. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  470. 'expireDeletedUser',
  471. this.userId
  472. )
  473. })
  474. it('should delete Feeback', async function () {
  475. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  476. expect(this.Feedback.deleteMany).to.have.been.calledWith({
  477. userId: this.userId,
  478. })
  479. })
  480. describe('when called as a callback', function () {
  481. it('should expire the user', function (done) {
  482. this.UserDeleter.expireDeletedUser(this.userId, err => {
  483. expect(err).not.to.exist
  484. this.DeletedUserMock.verify()
  485. this.mockedDeletedUser.verify()
  486. expect(this.deletedUser.user).not.to.exist
  487. expect(this.deletedUser.deleterData.ipAddress).not.to.exist
  488. done()
  489. })
  490. })
  491. })
  492. })
  493. })