remove_email.mjs 1.4 KB

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