UserUpdater.coffee 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. logger = require("logger-sharelatex")
  2. mongojs = require("../../infrastructure/mongojs")
  3. metrics = require("metrics-sharelatex")
  4. db = mongojs.db
  5. async = require("async")
  6. ObjectId = mongojs.ObjectId
  7. UserGetter = require("./UserGetter")
  8. { addAffiliation, removeAffiliation } = require("./UserAffiliationsManager")
  9. EmailHelper = require "../Helpers/EmailHelper"
  10. Errors = require "../Errors/Errors"
  11. Settings = require "settings-sharelatex"
  12. request = require 'request'
  13. module.exports = UserUpdater =
  14. updateUser: (query, update, callback = (error) ->) ->
  15. if typeof query == "string"
  16. query = _id: ObjectId(query)
  17. else if query instanceof ObjectId
  18. query = _id: query
  19. else if typeof query._id == "string"
  20. query._id = ObjectId(query._id)
  21. db.users.update query, update, callback
  22. #
  23. # DEPRECATED
  24. #
  25. # Change the user's main email address by adding a new email, switching the
  26. # default email and removing the old email. Prefer manipulating multiple
  27. # emails and the default rather than calling this method directly
  28. #
  29. changeEmailAddress: (userId, newEmail, callback)->
  30. newEmail = EmailHelper.parseEmail(newEmail)
  31. return callback(new Error('invalid email')) if !newEmail?
  32. logger.log userId: userId, newEmail: newEmail, "updaing email address of user"
  33. oldEmail = null
  34. async.series [
  35. (cb) ->
  36. UserGetter.getUserEmail userId, (error, email) ->
  37. oldEmail = email
  38. cb(error)
  39. (cb) -> UserUpdater.addEmailAddress userId, newEmail, cb
  40. (cb) -> UserUpdater.setDefaultEmailAddress userId, newEmail, cb
  41. (cb) -> UserUpdater.removeEmailAddress userId, oldEmail, cb
  42. ], callback
  43. # Add a new email address for the user. Email cannot be already used by this
  44. # or any other user
  45. addEmailAddress: (userId, newEmail, affiliationOptions, callback) ->
  46. unless callback? # affiliationOptions is optional
  47. callback = affiliationOptions
  48. affiliationOptions = {}
  49. newEmail = EmailHelper.parseEmail(newEmail)
  50. return callback(new Error('invalid email')) if !newEmail?
  51. UserGetter.ensureUniqueEmailAddress newEmail, (error) =>
  52. return callback(error) if error?
  53. addAffiliation userId, newEmail, affiliationOptions, (error) =>
  54. if error?
  55. logger.err error: error, 'problem adding affiliation while adding email'
  56. return callback(error)
  57. update = $push: emails: email: newEmail, createdAt: new Date()
  58. @updateUser userId, update, (error) ->
  59. if error?
  60. logger.err error: error, 'problem updating users emails'
  61. return callback(error)
  62. callback()
  63. # remove one of the user's email addresses. The email cannot be the user's
  64. # default email address
  65. removeEmailAddress: (userId, email, callback) ->
  66. email = EmailHelper.parseEmail(email)
  67. return callback(new Error('invalid email')) if !email?
  68. removeAffiliation userId, email, (error) =>
  69. if error?
  70. logger.err error: error, 'problem removing affiliation'
  71. return callback(error)
  72. query = _id: userId, email: $ne: email
  73. update = $pull: emails: email: email
  74. @updateUser query, update, (error, res) ->
  75. if error?
  76. logger.err error:error, 'problem removing users email'
  77. return callback(error)
  78. if res.n == 0
  79. return callback(new Error('Cannot remove email'))
  80. callback()
  81. # set the default email address by setting the `email` attribute. The email
  82. # must be one of the user's multiple emails (`emails` attribute)
  83. setDefaultEmailAddress: (userId, email, callback) ->
  84. email = EmailHelper.parseEmail(email)
  85. return callback(new Error('invalid email')) if !email?
  86. query = _id: userId, 'emails.email': email
  87. update = $set: email: email
  88. @updateUser query, update, (error, res) ->
  89. if error?
  90. logger.err error:error, 'problem setting default emails'
  91. return callback(error)
  92. if res.n == 0 # TODO: Check n or nMatched?
  93. return callback(new Error('Default email does not belong to user'))
  94. callback()
  95. updateV1AndSetDefaultEmailAddress: (userId, email, callback) ->
  96. @updateEmailAddressInV1 userId, email, (error) =>
  97. return callback(error) if error?
  98. @setDefaultEmailAddress userId, email, callback
  99. updateEmailAddressInV1: (userId, newEmail, callback) ->
  100. if !Settings.apis?.v1?.url?
  101. return callback()
  102. UserGetter.getUser userId, { 'overleaf.id': 1, emails: 1 }, (error, user) ->
  103. return callback(error) if error?
  104. return callback(new Errors.NotFoundError('no user found')) if !user?
  105. if !user.overleaf?.id?
  106. return callback()
  107. newEmailIsConfirmed = false
  108. for email in user.emails
  109. if email.email == newEmail and email.confirmedAt?
  110. newEmailIsConfirmed = true
  111. break
  112. if !newEmailIsConfirmed
  113. return callback(new Errors.UnconfirmedEmailError("can't update v1 with unconfirmed email"))
  114. request {
  115. baseUrl: Settings.apis.v1.url
  116. url: "/api/v1/sharelatex/users/#{user.overleaf.id}/email"
  117. method: 'PUT'
  118. auth:
  119. user: Settings.apis.v1.user
  120. pass: Settings.apis.v1.pass
  121. sendImmediately: true
  122. json: { email: newEmail },
  123. timeout: 5 * 1000
  124. }, (error, response, body) ->
  125. if error?
  126. error = new Errors.V1ConnectionError('No V1 connection') if error.code == 'ECONNREFUSED'
  127. return callback(error)
  128. if response.statusCode == 409 # Conflict
  129. return callback(new Errors.EmailExistsError('email exists in v1'))
  130. else if 200 <= response.statusCode < 300
  131. return callback()
  132. else
  133. return callback new Error("non-success code from v1: #{response.statusCode}")
  134. confirmEmail: (userId, email, callback) ->
  135. email = EmailHelper.parseEmail(email)
  136. return callback(new Error('invalid email')) if !email?
  137. logger.log {userId, email}, 'confirming user email'
  138. addAffiliation userId, email, (error) =>
  139. if error?
  140. logger.err error: error, 'problem adding affiliation while confirming email'
  141. return callback(error)
  142. query =
  143. _id: userId
  144. 'emails.email': email
  145. update =
  146. $set:
  147. 'emails.$.confirmedAt': new Date()
  148. @updateUser query, update, (error, res) ->
  149. return callback(error) if error?
  150. logger.log {res, userId, email}, "tried to confirm email"
  151. if res.n == 0
  152. return callback(new Errors.NotFoundError('user id and email do no match'))
  153. callback()
  154. [
  155. 'updateUser'
  156. 'changeEmailAddress'
  157. 'setDefaultEmailAddress'
  158. 'addEmailAddress'
  159. 'removeEmailAddress'
  160. ].map (method) ->
  161. metrics.timeAsyncMethod(UserUpdater, method, 'mongo.UserUpdater', logger)