clear_admin_sessions.mjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import {
  2. db,
  3. READ_PREFERENCE_SECONDARY,
  4. } from '../app/src/infrastructure/mongodb.js'
  5. import UserSessionsManager from '../app/src/Features/User/UserSessionsManager.js'
  6. import { scriptRunner } from './lib/ScriptRunner.mjs'
  7. const COMMIT = process.argv.includes('--commit')
  8. const LOG_SESSIONS = !process.argv.includes('--log-sessions=false')
  9. async function main() {
  10. const adminUsers = await db.users
  11. .find(
  12. { isAdmin: true },
  13. {
  14. projection: {
  15. _id: 1,
  16. email: 1,
  17. },
  18. readPreference: READ_PREFERENCE_SECONDARY,
  19. }
  20. )
  21. .toArray()
  22. if (LOG_SESSIONS) {
  23. for (const user of adminUsers) {
  24. user.sessions = JSON.stringify(
  25. await UserSessionsManager.promises.getAllUserSessions(user, [])
  26. )
  27. }
  28. }
  29. console.log('All Admin users before clearing:')
  30. console.table(adminUsers)
  31. if (COMMIT) {
  32. let anyFailed = false
  33. for (const user of adminUsers) {
  34. console.error(
  35. `Clearing sessions for ${user.email} (${user._id.toString()})`
  36. )
  37. user.clearedSessions = 0
  38. try {
  39. user.clearedSessions =
  40. await UserSessionsManager.promises.removeSessionsFromRedis(user)
  41. } catch (err) {
  42. anyFailed = true
  43. console.error(err)
  44. }
  45. }
  46. console.log('All Admin users after clearing:')
  47. console.table(adminUsers)
  48. if (anyFailed) {
  49. throw new Error('failed to clear some sessions, see above for details')
  50. }
  51. } else {
  52. console.warn('Use --commit to clear sessions.')
  53. }
  54. }
  55. try {
  56. await scriptRunner(main)
  57. console.error('Done.')
  58. process.exit(0)
  59. } catch (error) {
  60. console.error({ error })
  61. process.exit(1)
  62. }