back_fill_staff_access.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 KEEP_SESSIONS = process.argv.includes('--keep-sessions')
  8. const FULL_STAFF_ACCESS = {
  9. publisherMetrics: true,
  10. publisherManagement: true,
  11. institutionMetrics: true,
  12. institutionManagement: true,
  13. groupMetrics: true,
  14. groupManagement: true,
  15. adminMetrics: true,
  16. splitTestMetrics: true,
  17. splitTestManagement: true,
  18. }
  19. function doesNotHaveFullStaffAccess(user) {
  20. if (!user.staffAccess) {
  21. return true
  22. }
  23. for (const field of Object.keys(FULL_STAFF_ACCESS)) {
  24. if (!user.staffAccess[field]) {
  25. return true
  26. }
  27. }
  28. return false
  29. }
  30. function formatUser(user) {
  31. user = Object.assign({}, user, user.staffAccess)
  32. delete user.staffAccess
  33. return user
  34. }
  35. async function main() {
  36. const adminUsers = await db.users
  37. .find(
  38. { isAdmin: true },
  39. {
  40. projection: {
  41. _id: 1,
  42. email: 1,
  43. staffAccess: 1,
  44. },
  45. readPreference: READ_PREFERENCE_SECONDARY,
  46. }
  47. )
  48. .toArray()
  49. console.log('All Admin users:')
  50. console.table(adminUsers.map(formatUser))
  51. const incompleteUsers = adminUsers.filter(doesNotHaveFullStaffAccess)
  52. if (incompleteUsers.length === 0) {
  53. console.warn('All Admin users have full staff access.')
  54. return
  55. }
  56. console.log()
  57. console.log('Incomplete staff access:')
  58. console.table(incompleteUsers.map(formatUser))
  59. if (COMMIT) {
  60. for (const user of incompleteUsers) {
  61. console.error(
  62. `Granting ${user.email} (${user._id.toString()}) full staff access`
  63. )
  64. await db.users.updateOne(
  65. { _id: user._id, isAdmin: true },
  66. { $set: { staffAccess: FULL_STAFF_ACCESS } }
  67. )
  68. if (!KEEP_SESSIONS) {
  69. await UserSessionsManager.promises.removeSessionsFromRedis(user)
  70. }
  71. }
  72. } else {
  73. console.warn('Use --commit to grant missing staff access.')
  74. }
  75. }
  76. try {
  77. await main()
  78. console.error('Done.')
  79. process.exit(0)
  80. } catch (error) {
  81. console.error({ error })
  82. process.exit(1)
  83. }