remove_email.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Run all the mongo queries on secondaries
  2. process.env.MONGO_CONNECTION_STRING =
  3. process.env.READ_ONLY_MONGO_CONNECTION_STRING
  4. const { ObjectId, waitForDb } = require('../app/src/infrastructure/mongodb')
  5. const UserUpdater = require('../app/src/Features/User/UserUpdater')
  6. const UserGetter = require('../app/src/Features/User/UserGetter')
  7. waitForDb()
  8. .then(removeEmail)
  9. .catch(error => {
  10. console.error(error)
  11. process.exit(1)
  12. })
  13. .then(() => {
  14. console.log('Done.')
  15. process.exit()
  16. })
  17. async function removeEmail() {
  18. const userId = process.argv[2]
  19. let email = process.argv[3]
  20. if (!ObjectId.isValid(userId)) {
  21. throw new Error(`user ID ${userId} is not valid`)
  22. }
  23. if (!email) {
  24. throw new Error('no email provided')
  25. }
  26. // email arg can be within double quotes for arg so that we can handle
  27. // malformed emails with spaces
  28. email = email.replace(/"/g, '')
  29. console.log(
  30. `\nBegin request to remove email "${email}" from user "${userId}"\n`
  31. )
  32. const userWithEmail = await UserGetter.promises.getUserByAnyEmail(email, {
  33. _id: 1,
  34. })
  35. if (!userWithEmail) {
  36. throw new Error(`no user found with email "${email}"`)
  37. }
  38. if (userWithEmail._id.toString() !== userId) {
  39. throw new Error(
  40. `email does not belong to user. Belongs to ${userWithEmail._id}`
  41. )
  42. }
  43. const skipParseEmail = true
  44. await UserUpdater.promises.removeEmailAddress(userId, email, skipParseEmail)
  45. }