suspend_users.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Read a list of user IDs from a file and suspend their accounts.
  3. *
  4. * Usage: node scripts/suspend_users.mjs <filename>
  5. */
  6. import fs from 'node:fs'
  7. import { ObjectId } from '../app/src/infrastructure/mongodb.js'
  8. import UserUpdater from '../app/src/Features/User/UserUpdater.mjs'
  9. import { promiseMapWithLimit } from '@overleaf/promise-utils'
  10. const ASYNC_LIMIT = 10
  11. const processLogger = {
  12. failed: [],
  13. success: [],
  14. printSummary: () => {
  15. console.log(
  16. {
  17. success: processLogger.success,
  18. failed: processLogger.failed,
  19. },
  20. `\nDONE. ${processLogger.success.length} successful. ${processLogger.failed.length} failed to suspend.`
  21. )
  22. },
  23. }
  24. function _validateUserIdList(userIds) {
  25. if (!Array.isArray(userIds)) throw new Error('users is not an array')
  26. userIds.forEach(userId => {
  27. if (!ObjectId.isValid(userId)) throw new Error('user ID not valid')
  28. })
  29. }
  30. async function _handleUser(userId) {
  31. try {
  32. await UserUpdater.promises.suspendUser(userId, {
  33. ip: '0.0.0.0',
  34. info: { script: true },
  35. })
  36. } catch (error) {
  37. console.log(`Failed to suspend ${userId}`, error)
  38. processLogger.failed.push(userId)
  39. return
  40. }
  41. processLogger.success.push(userId)
  42. }
  43. async function _loopUsers(userIds) {
  44. return promiseMapWithLimit(ASYNC_LIMIT, userIds, _handleUser)
  45. }
  46. const fileName = process.argv[2]
  47. if (!fileName) throw new Error('missing filename')
  48. const usersFile = fs.readFileSync(fileName, 'utf8')
  49. const userIds = usersFile
  50. .trim()
  51. .split('\n')
  52. .map(id => id.trim())
  53. async function processUsers(userIds) {
  54. console.log('---Starting suspend_users script---')
  55. _validateUserIdList(userIds)
  56. console.log(`---Starting to process ${userIds.length} users---`)
  57. await _loopUsers(userIds)
  58. processLogger.printSummary()
  59. process.exit()
  60. }
  61. processUsers(userIds)