clear_sessions_set_must_reconfirm.mjs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import fs from 'fs'
  2. import { ObjectId, waitForDb } from '../app/src/infrastructure/mongodb.js'
  3. import async from 'async'
  4. import UserUpdater from '../app/src/Features/User/UserUpdater.js'
  5. import UserSessionsManager from '../app/src/Features/User/UserSessionsManager.js'
  6. const ASYNC_LIMIT = 10
  7. const processLogger = {
  8. failedClear: [],
  9. failedSet: [],
  10. success: [],
  11. printSummary: () => {
  12. console.log(
  13. {
  14. success: processLogger.success,
  15. failedClear: processLogger.failedClear,
  16. failedSet: processLogger.failedSet,
  17. },
  18. `\nDONE. ${processLogger.success.length} successful. ${processLogger.failedClear.length} failed to clear sessions. ${processLogger.failedSet.length} failed to set must_reconfirm.`
  19. )
  20. },
  21. }
  22. function _validateUserIdList(userIds) {
  23. if (!Array.isArray(userIds)) throw new Error('users is not an array')
  24. userIds.forEach(userId => {
  25. if (!ObjectId.isValid(userId)) throw new Error('user ID not valid')
  26. })
  27. }
  28. function _handleUser(userId, callback) {
  29. UserUpdater.updateUser(userId, { $set: { must_reconfirm: true } }, error => {
  30. if (error) {
  31. console.log(`Failed to set must_reconfirm ${userId}`, error)
  32. processLogger.failedSet.push(userId)
  33. return callback()
  34. } else {
  35. UserSessionsManager.removeSessionsFromRedis(
  36. { _id: userId },
  37. null,
  38. error => {
  39. if (error) {
  40. console.log(`Failed to clear sessions for ${userId}`, error)
  41. processLogger.failedClear.push(userId)
  42. } else {
  43. processLogger.success.push(userId)
  44. }
  45. return callback()
  46. }
  47. )
  48. }
  49. })
  50. }
  51. async function _loopUsers(userIds) {
  52. await new Promise((resolve, reject) => {
  53. async.eachLimit(userIds, ASYNC_LIMIT, _handleUser, error => {
  54. if (error) return reject(error)
  55. resolve()
  56. })
  57. })
  58. }
  59. const fileName = process.argv[2]
  60. if (!fileName) throw new Error('missing filename')
  61. const usersFile = fs.readFileSync(fileName, 'utf8')
  62. const userIds = usersFile
  63. .trim()
  64. .split('\n')
  65. .map(id => id.trim())
  66. async function processUsers(userIds) {
  67. console.log('---Starting set_must_reconfirm script---')
  68. await waitForDb()
  69. _validateUserIdList(userIds)
  70. console.log(`---Starting to process ${userIds.length} users---`)
  71. await _loopUsers(userIds)
  72. processLogger.printSummary()
  73. process.exit()
  74. }
  75. processUsers(userIds)