backfill_sso_affiliations.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const { User } = require('../app/src/models/User')
  2. const UserUpdater = require('../app/src/Features/User/UserUpdater')
  3. require('logger-sharelatex').logger.level('error')
  4. const pLimit = require('p-limit')
  5. const CONCURRENCY = 10
  6. const unexpectedUserStates = []
  7. console.log('Starting SSO affiliation backfill')
  8. const query = {
  9. emails: {
  10. $elemMatch: {
  11. samlProviderId: { $exists: true },
  12. confirmedAt: { $exists: false }
  13. }
  14. }
  15. }
  16. async function backfillAffiliation(user) {
  17. const ssoEmail = user.emails.filter(
  18. emailData => !emailData.confirmedAt && emailData.samlProviderId
  19. )
  20. if (ssoEmail.length > 1 || ssoEmail.length === 0) {
  21. unexpectedUserStates.push(user._id)
  22. }
  23. const { email } = ssoEmail[0]
  24. await UserUpdater.promises.confirmEmail(user._id, email)
  25. }
  26. async function getUsers() {
  27. return User.find(query, { emails: 1 }).exec()
  28. }
  29. async function run() {
  30. const limit = pLimit(CONCURRENCY)
  31. const users = await getUsers()
  32. console.log(`Found ${users.length} users`)
  33. await Promise.all(users.map(user => limit(() => backfillAffiliation(user))))
  34. console.log('Finished')
  35. console.log(
  36. `Found ${unexpectedUserStates.length} in unexpected states`,
  37. unexpectedUserStates
  38. )
  39. }
  40. run()
  41. .then(() => {
  42. process.exit()
  43. })
  44. .catch(error => {
  45. console.log(error)
  46. process.exit(1)
  47. })