UserUpdater.js 11 KB

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