UserDeleterTests.js 17 KB

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