UserDeleterTests.js 15 KB

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