clear_admin_sessions.mjs 1.6 KB

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