clear_sessions_set_must_reconfirm.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const fs = require('fs')
  2. const { ObjectId, waitForDb } = require('../app/src/infrastructure/mongodb')
  3. const async = require('async')
  4. const UserUpdater = require('../app/src/Features/User/UserUpdater')
  5. const UserSessionsManager = require('../app/src/Features/User/UserSessionsManager')
  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. null,
  39. error => {
  40. if (error) {
  41. console.log(`Failed to clear sessions for ${userId}`, error)
  42. processLogger.failedClear.push(userId)
  43. } else {
  44. processLogger.success.push(userId)
  45. }
  46. return callback()
  47. }
  48. )
  49. }
  50. })
  51. }
  52. async function _loopUsers(userIds) {
  53. await new Promise((resolve, reject) => {
  54. async.eachLimit(userIds, ASYNC_LIMIT, _handleUser, error => {
  55. if (error) return reject(error)
  56. resolve()
  57. })
  58. })
  59. }
  60. const fileName = process.argv[2]
  61. if (!fileName) throw new Error('missing filename')
  62. const usersFile = fs.readFileSync(fileName, 'utf8')
  63. const userIds = usersFile
  64. .trim()
  65. .split('\n')
  66. .map(id => id.trim())
  67. async function processUsers(userIds) {
  68. console.log('---Starting set_must_reconfirm script---')
  69. await waitForDb()
  70. _validateUserIdList(userIds)
  71. console.log(`---Starting to process ${userIds.length} users---`)
  72. await _loopUsers(userIds)
  73. processLogger.printSummary()
  74. process.exit()
  75. }
  76. processUsers(userIds)