UserUpdater.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. const logger = require('@overleaf/logger')
  2. const OError = require('@overleaf/o-error')
  3. const { db } = require('../../infrastructure/mongodb')
  4. const { normalizeQuery } = require('../Helpers/Mongo')
  5. const metrics = require('@overleaf/metrics')
  6. const async = require('async')
  7. const { callbackify, promisify } = require('util')
  8. const UserGetter = require('./UserGetter')
  9. const {
  10. addAffiliation,
  11. promises: InstitutionsAPIPromises,
  12. } = require('../Institutions/InstitutionsAPI')
  13. const Features = require('../../infrastructure/Features')
  14. const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
  15. const EmailHandler = require('../Email/EmailHandler')
  16. const EmailHelper = require('../Helpers/EmailHelper')
  17. const Errors = require('../Errors/Errors')
  18. const NewsletterManager = require('../Newsletter/NewsletterManager')
  19. const RecurlyWrapper = require('../Subscription/RecurlyWrapper')
  20. const UserAuditLogHandler = require('./UserAuditLogHandler')
  21. async function _sendSecurityAlertPrimaryEmailChanged(userId, oldEmail, email) {
  22. // send email to both old and new primary email
  23. const emailOptions = {
  24. actionDescribed: `the primary email address on your account was changed to ${email}`,
  25. action: 'change of primary email address',
  26. }
  27. const toOld = Object.assign({}, emailOptions, { to: oldEmail })
  28. const toNew = Object.assign({}, emailOptions, { to: email })
  29. try {
  30. await EmailHandler.promises.sendEmail('securityAlert', toOld)
  31. await EmailHandler.promises.sendEmail('securityAlert', toNew)
  32. } catch (error) {
  33. logger.error(
  34. { error, userId },
  35. 'could not send security alert email when primary email changed'
  36. )
  37. }
  38. }
  39. async function addEmailAddress(userId, newEmail, affiliationOptions, auditLog) {
  40. newEmail = EmailHelper.parseEmail(newEmail)
  41. if (!newEmail) {
  42. throw new Error('invalid email')
  43. }
  44. await UserGetter.promises.ensureUniqueEmailAddress(newEmail)
  45. await UserAuditLogHandler.promises.addEntry(
  46. userId,
  47. 'add-email',
  48. auditLog.initiatorId,
  49. auditLog.ipAddress,
  50. {
  51. newSecondaryEmail: newEmail,
  52. }
  53. )
  54. try {
  55. await InstitutionsAPIPromises.addAffiliation(
  56. userId,
  57. newEmail,
  58. affiliationOptions
  59. )
  60. } catch (error) {
  61. throw OError.tag(error, 'problem adding affiliation while adding email')
  62. }
  63. try {
  64. const reversedHostname = newEmail.split('@')[1].split('').reverse().join('')
  65. const update = {
  66. $push: {
  67. emails: { email: newEmail, createdAt: new Date(), reversedHostname },
  68. },
  69. }
  70. await UserUpdater.promises.updateUser(userId, update)
  71. } catch (error) {
  72. throw OError.tag(error, 'problem updating users emails')
  73. }
  74. }
  75. async function clearSAMLData(userId, auditLog, sendEmail) {
  76. const user = await UserGetter.promises.getUser(userId, {
  77. email: 1,
  78. emails: 1,
  79. })
  80. await UserAuditLogHandler.promises.addEntry(
  81. userId,
  82. 'clear-institution-sso-data',
  83. auditLog.initiatorId,
  84. auditLog.ipAddress,
  85. {}
  86. )
  87. const update = {
  88. $unset: {
  89. samlIdentifiers: 1,
  90. 'emails.$[].samlProviderId': 1,
  91. },
  92. }
  93. await UserUpdater.promises.updateUser(userId, update)
  94. for (const emailData of user.emails) {
  95. await InstitutionsAPIPromises.removeEntitlement(userId, emailData.email)
  96. }
  97. await FeaturesUpdater.promises.refreshFeatures(
  98. userId,
  99. 'clear-institution-sso-data'
  100. )
  101. if (sendEmail) {
  102. await EmailHandler.promises.sendEmail('SAMLDataCleared', { to: user.email })
  103. }
  104. }
  105. async function setDefaultEmailAddress(
  106. userId,
  107. email,
  108. allowUnconfirmed,
  109. auditLog,
  110. sendSecurityAlert
  111. ) {
  112. email = EmailHelper.parseEmail(email)
  113. if (email == null) {
  114. throw new Error('invalid email')
  115. }
  116. const user = await UserGetter.promises.getUser(userId, {
  117. email: 1,
  118. emails: 1,
  119. })
  120. if (!user) {
  121. throw new Error('invalid userId')
  122. }
  123. const oldEmail = user.email
  124. const userEmail = user.emails.find(e => e.email === email)
  125. if (!userEmail) {
  126. throw new Error('Default email does not belong to user')
  127. }
  128. if (!userEmail.confirmedAt && !allowUnconfirmed) {
  129. throw new Errors.UnconfirmedEmailError()
  130. }
  131. await UserAuditLogHandler.promises.addEntry(
  132. userId,
  133. 'change-primary-email',
  134. auditLog.initiatorId,
  135. auditLog.ipAddress,
  136. {
  137. newPrimaryEmail: email,
  138. oldPrimaryEmail: oldEmail,
  139. }
  140. )
  141. const query = { _id: userId, 'emails.email': email }
  142. const update = { $set: { email } }
  143. const res = await UserUpdater.promises.updateUser(query, update)
  144. // this should not happen
  145. if (res.matchedCount !== 1) {
  146. throw new Error('email update error')
  147. }
  148. if (sendSecurityAlert) {
  149. // no need to wait, errors are logged and not passed back
  150. _sendSecurityAlertPrimaryEmailChanged(userId, oldEmail, email)
  151. }
  152. try {
  153. await NewsletterManager.promises.changeEmail(user, email)
  154. } catch (error) {
  155. logger.warn(
  156. { err: error, oldEmail, newEmail: email },
  157. 'Failed to change email in newsletter subscription'
  158. )
  159. }
  160. try {
  161. await RecurlyWrapper.promises.updateAccountEmailAddress(user._id, email)
  162. } catch (error) {
  163. // errors are ignored
  164. }
  165. }
  166. async function confirmEmail(userId, email) {
  167. // used for initial email confirmation (non-SSO and SSO)
  168. // also used for reconfirmation of non-SSO emails
  169. const confirmedAt = new Date()
  170. email = EmailHelper.parseEmail(email)
  171. if (email == null) {
  172. throw new Error('invalid email')
  173. }
  174. logger.log({ userId, email }, 'confirming user email')
  175. try {
  176. await InstitutionsAPIPromises.addAffiliation(userId, email, { confirmedAt })
  177. } catch (error) {
  178. throw OError.tag(error, 'problem adding affiliation while confirming email')
  179. }
  180. const query = {
  181. _id: userId,
  182. 'emails.email': email,
  183. }
  184. // only update confirmedAt if it was not previously set
  185. const update = {
  186. $set: {
  187. 'emails.$.reconfirmedAt': confirmedAt,
  188. },
  189. $min: {
  190. 'emails.$.confirmedAt': confirmedAt,
  191. },
  192. }
  193. if (Features.hasFeature('affiliations')) {
  194. update.$unset = {
  195. 'emails.$.affiliationUnchecked': 1,
  196. }
  197. }
  198. const res = await UserUpdater.promises.updateUser(query, update)
  199. if (res.matchedCount !== 1) {
  200. throw new Errors.NotFoundError('user id and email do no match')
  201. }
  202. await FeaturesUpdater.promises.refreshFeatures(userId, 'confirm-email')
  203. }
  204. async function removeEmailAddress(userId, email, skipParseEmail = false) {
  205. // remove one of the user's email addresses. The email cannot be the user's
  206. // default email address
  207. if (!skipParseEmail) {
  208. email = EmailHelper.parseEmail(email)
  209. } else if (skipParseEmail && typeof email !== 'string') {
  210. throw new Error('email must be a string')
  211. }
  212. if (!email) {
  213. throw new Error('invalid email')
  214. }
  215. const isMainEmail = await UserGetter.promises.getUserByMainEmail(email, {
  216. _id: 1,
  217. })
  218. if (isMainEmail) {
  219. throw new Error('cannot remove primary email')
  220. }
  221. try {
  222. await InstitutionsAPIPromises.removeAffiliation(userId, email)
  223. } catch (error) {
  224. OError.tag(error, 'problem removing affiliation')
  225. throw error
  226. }
  227. const query = { _id: userId, email: { $ne: email } }
  228. const update = { $pull: { emails: { email } } }
  229. let res
  230. try {
  231. res = await UserUpdater.promises.updateUser(query, update)
  232. } catch (error) {
  233. OError.tag(error, 'problem removing users email')
  234. throw error
  235. }
  236. if (res.matchedCount !== 1) {
  237. throw new Error('Cannot remove email')
  238. }
  239. await FeaturesUpdater.promises.refreshFeatures(userId, 'remove-email')
  240. }
  241. const UserUpdater = {
  242. addAffiliationForNewUser(userId, email, affiliationOptions, callback) {
  243. if (callback == null) {
  244. // affiliationOptions is optional
  245. callback = affiliationOptions
  246. affiliationOptions = {}
  247. }
  248. addAffiliation(userId, email, affiliationOptions, error => {
  249. if (error) {
  250. return callback(error)
  251. }
  252. UserUpdater.updateUser(
  253. { _id: userId, 'emails.email': email },
  254. { $unset: { 'emails.$.affiliationUnchecked': 1 } },
  255. error => {
  256. if (error) {
  257. callback(
  258. OError.tag(
  259. error,
  260. 'could not remove affiliationUnchecked flag for user on create',
  261. {
  262. userId,
  263. email,
  264. }
  265. )
  266. )
  267. } else {
  268. callback()
  269. }
  270. }
  271. )
  272. })
  273. },
  274. updateUser(query, update, callback) {
  275. if (callback == null) {
  276. callback = () => {}
  277. }
  278. try {
  279. query = normalizeQuery(query)
  280. } catch (err) {
  281. return callback(err)
  282. }
  283. db.users.updateOne(query, update, callback)
  284. },
  285. //
  286. // DEPRECATED
  287. //
  288. // Change the user's main email address by adding a new email, switching the
  289. // default email and removing the old email. Prefer manipulating multiple
  290. // emails and the default rather than calling this method directly
  291. //
  292. changeEmailAddress(userId, newEmail, auditLog, callback) {
  293. newEmail = EmailHelper.parseEmail(newEmail)
  294. if (newEmail == null) {
  295. return callback(new Error('invalid email'))
  296. }
  297. let oldEmail = null
  298. async.series(
  299. [
  300. cb =>
  301. UserGetter.getUserEmail(userId, (error, email) => {
  302. oldEmail = email
  303. cb(error)
  304. }),
  305. cb => UserUpdater.addEmailAddress(userId, newEmail, {}, auditLog, cb),
  306. cb =>
  307. UserUpdater.setDefaultEmailAddress(
  308. userId,
  309. newEmail,
  310. true,
  311. auditLog,
  312. true,
  313. cb
  314. ),
  315. cb => UserUpdater.removeEmailAddress(userId, oldEmail, cb),
  316. ],
  317. callback
  318. )
  319. },
  320. // Add a new email address for the user. Email cannot be already used by this
  321. // or any other user
  322. addEmailAddress: callbackify(addEmailAddress),
  323. removeEmailAddress: callbackify(removeEmailAddress),
  324. clearSAMLData: callbackify(clearSAMLData),
  325. // set the default email address by setting the `email` attribute. The email
  326. // must be one of the user's multiple emails (`emails` attribute)
  327. setDefaultEmailAddress: callbackify(setDefaultEmailAddress),
  328. confirmEmail: callbackify(confirmEmail),
  329. removeReconfirmFlag(userId, callback) {
  330. UserUpdater.updateUser(
  331. userId.toString(),
  332. {
  333. $set: { must_reconfirm: false },
  334. },
  335. error => callback(error)
  336. )
  337. },
  338. }
  339. ;[
  340. 'updateUser',
  341. 'changeEmailAddress',
  342. 'setDefaultEmailAddress',
  343. 'addEmailAddress',
  344. 'removeEmailAddress',
  345. 'removeReconfirmFlag',
  346. ].map(method =>
  347. metrics.timeAsyncMethod(UserUpdater, method, 'mongo.UserUpdater', logger)
  348. )
  349. const promises = {
  350. addAffiliationForNewUser: promisify(UserUpdater.addAffiliationForNewUser),
  351. addEmailAddress,
  352. confirmEmail,
  353. setDefaultEmailAddress,
  354. updateUser: promisify(UserUpdater.updateUser),
  355. removeEmailAddress,
  356. removeReconfirmFlag: promisify(UserUpdater.removeReconfirmFlag),
  357. }
  358. UserUpdater.promises = promises
  359. module.exports = UserUpdater