clear_sessions_set_must_reconfirm.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.revokeAllUserSessions({ _id: userId }, [], error => {
  36. if (error) {
  37. console.log(`Failed to clear sessions for ${userId}`, error)
  38. processLogger.failedClear.push(userId)
  39. } else {
  40. processLogger.success.push(userId)
  41. }
  42. return callback()
  43. })
  44. }
  45. })
  46. }
  47. async function _loopUsers(userIds) {
  48. await new Promise((resolve, reject) => {
  49. async.eachLimit(userIds, ASYNC_LIMIT, _handleUser, error => {
  50. if (error) return reject(error)
  51. resolve()
  52. })
  53. })
  54. }
  55. const fileName = process.argv[2]
  56. if (!fileName) throw new Error('missing filename')
  57. const usersFile = fs.readFileSync(fileName, 'utf8')
  58. const userIds = usersFile
  59. .trim()
  60. .split('\n')
  61. .map(id => id.trim())
  62. async function processUsers(userIds) {
  63. console.log('---Starting set_must_reconfirm script---')
  64. await waitForDb()
  65. _validateUserIdList(userIds)
  66. console.log(`---Starting to process ${userIds.length} users---`)
  67. await _loopUsers(userIds)
  68. processLogger.printSummary()
  69. process.exit()
  70. }
  71. processUsers(userIds)