UserEmailsController.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. const AuthenticationController = require('../Authentication/AuthenticationController')
  2. const Settings = require('@overleaf/settings')
  3. const logger = require('@overleaf/logger')
  4. const SessionManager = require('../Authentication/SessionManager')
  5. const UserGetter = require('./UserGetter')
  6. const UserUpdater = require('./UserUpdater')
  7. const UserSessionsManager = require('./UserSessionsManager')
  8. const EmailHandler = require('../Email/EmailHandler')
  9. const EmailHelper = require('../Helpers/EmailHelper')
  10. const UserEmailsConfirmationHandler = require('./UserEmailsConfirmationHandler')
  11. const { endorseAffiliation } = require('../Institutions/InstitutionsAPI')
  12. const Errors = require('../Errors/Errors')
  13. const HttpErrorHandler = require('../Errors/HttpErrorHandler')
  14. const { expressify } = require('@overleaf/promise-utils')
  15. const AsyncFormHelper = require('../Helpers/AsyncFormHelper')
  16. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  17. const UserPrimaryEmailCheckHandler = require('../User/UserPrimaryEmailCheckHandler')
  18. const UserAuditLogHandler = require('./UserAuditLogHandler')
  19. const { RateLimiter } = require('../../infrastructure/RateLimiter')
  20. const Features = require('../../infrastructure/Features')
  21. const tsscmp = require('tsscmp')
  22. const Modules = require('../../infrastructure/Modules')
  23. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  24. const AUDIT_LOG_TOKEN_PREFIX_LENGTH = 10
  25. const sendSecondaryConfirmCodeRateLimiter = new RateLimiter(
  26. 'send-secondary-confirmation-code',
  27. {
  28. points: 1,
  29. duration: 60,
  30. }
  31. )
  32. const checkSecondaryConfirmCodeRateLimiter = new RateLimiter(
  33. 'check-secondary-confirmation-code-per-email',
  34. {
  35. points: 10,
  36. duration: 60,
  37. }
  38. )
  39. const resendSecondaryConfirmCodeRateLimiter = new RateLimiter(
  40. 'resend-secondary-confirmation-code',
  41. {
  42. points: 1,
  43. duration: 60,
  44. }
  45. )
  46. async function _sendSecurityAlertEmail(user, email) {
  47. const emailOptions = {
  48. to: user.email,
  49. actionDescribed: `a secondary email address has been added to your account ${user.email}`,
  50. message: [
  51. `<span style="display:inline-block;padding: 0 20px;width:100%;">Added: <br/><b>${email}</b></span>`,
  52. ],
  53. action: 'secondary email address added',
  54. }
  55. await EmailHandler.promises.sendEmail('securityAlert', emailOptions)
  56. }
  57. /**
  58. * This method is for adding a secondary email to be confirmed via an emailed link.
  59. * For code confirmation, see the `addWithConfirmationCode` method in this file.
  60. */
  61. async function add(req, res, next) {
  62. const userId = SessionManager.getLoggedInUserId(req.session)
  63. const email = EmailHelper.parseEmail(req.body.email)
  64. if (!email) {
  65. return res.sendStatus(422)
  66. }
  67. const user = await UserGetter.promises.getUser(userId, {
  68. email: 1,
  69. 'emails.email': 1,
  70. })
  71. if (user.emails.length >= Settings.emailAddressLimit) {
  72. return res.status(422).json({ message: 'secondary email limit exceeded' })
  73. }
  74. const affiliationOptions = {
  75. university: req.body.university,
  76. role: req.body.role,
  77. department: req.body.department,
  78. }
  79. try {
  80. await UserUpdater.promises.addEmailAddress(
  81. userId,
  82. email,
  83. affiliationOptions,
  84. {
  85. initiatorId: user._id,
  86. ipAddress: req.ip,
  87. }
  88. )
  89. } catch (error) {
  90. return UserEmailsController._handleEmailError(error, req, res, next)
  91. }
  92. await _sendSecurityAlertEmail(user, email)
  93. await UserEmailsConfirmationHandler.promises.sendConfirmationEmail(
  94. userId,
  95. email
  96. )
  97. res.sendStatus(204)
  98. }
  99. async function resendConfirmation(req, res) {
  100. const userId = SessionManager.getLoggedInUserId(req.session)
  101. const email = EmailHelper.parseEmail(req.body.email)
  102. if (!email) {
  103. return res.sendStatus(422)
  104. }
  105. const user = await UserGetter.promises.getUserByAnyEmail(email, { _id: 1 })
  106. if (!user || user._id.toString() !== userId) {
  107. return res.sendStatus(422)
  108. }
  109. await UserEmailsConfirmationHandler.promises.sendConfirmationEmail(
  110. userId,
  111. email
  112. )
  113. res.sendStatus(200)
  114. }
  115. async function sendReconfirmation(req, res) {
  116. const userId = SessionManager.getLoggedInUserId(req.session)
  117. const email = EmailHelper.parseEmail(req.body.email)
  118. if (!email) {
  119. return res.sendStatus(400)
  120. }
  121. const user = await UserGetter.promises.getUserByAnyEmail(email, { _id: 1 })
  122. if (!user || user._id.toString() !== userId) {
  123. return res.sendStatus(422)
  124. }
  125. await UserEmailsConfirmationHandler.promises.sendReconfirmationEmail(
  126. userId,
  127. email
  128. )
  129. res.sendStatus(204)
  130. }
  131. /**
  132. * This method is for adding a secondary email to be confirmed via a code.
  133. * For email link confirmation see the `add` method in this file.
  134. */
  135. async function addWithConfirmationCode(req, res) {
  136. delete req.session.pendingSecondaryEmail
  137. const userId = SessionManager.getLoggedInUserId(req.session)
  138. const email = EmailHelper.parseEmail(req.body.email)
  139. const affiliationOptions = {
  140. university: req.body.university,
  141. role: req.body.role,
  142. department: req.body.department,
  143. }
  144. if (!email) {
  145. return res.sendStatus(422)
  146. }
  147. const user = await UserGetter.promises.getUser(userId, {
  148. email: 1,
  149. 'emails.email': 1,
  150. })
  151. if (user.emails.length >= Settings.emailAddressLimit) {
  152. return res.status(422).json({ message: 'secondary email limit exceeded' })
  153. }
  154. try {
  155. await UserGetter.promises.ensureUniqueEmailAddress(email)
  156. await sendSecondaryConfirmCodeRateLimiter.consume(email, 1, {
  157. method: 'email',
  158. })
  159. await UserAuditLogHandler.promises.addEntry(
  160. userId,
  161. 'request-add-email-code',
  162. userId,
  163. req.ip,
  164. {
  165. newSecondaryEmail: email,
  166. }
  167. )
  168. const { confirmCode, confirmCodeExpiresTimestamp } =
  169. await UserEmailsConfirmationHandler.promises.sendConfirmationCode(
  170. email,
  171. true
  172. )
  173. req.session.pendingSecondaryEmail = {
  174. email,
  175. confirmCode,
  176. confirmCodeExpiresTimestamp,
  177. affiliationOptions,
  178. }
  179. return res.sendStatus(200)
  180. } catch (err) {
  181. if (err.name === 'EmailExistsError') {
  182. return res.status(409).json({
  183. message: {
  184. type: 'error',
  185. text: req.i18n.translate('email_already_registered'),
  186. },
  187. })
  188. }
  189. if (err?.remainingPoints === 0) {
  190. return res.status(429).json({})
  191. }
  192. logger.err({ err }, 'failed to send confirmation code')
  193. delete req.session.pendingSecondaryEmail
  194. return res.status(500).json({
  195. message: {
  196. key: 'error_performing_request',
  197. },
  198. })
  199. }
  200. }
  201. async function checkSecondaryEmailConfirmationCode(req, res) {
  202. const userId = SessionManager.getLoggedInUserId(req.session)
  203. const code = req.body.code
  204. const user = await UserGetter.promises.getUser(userId, {
  205. email: 1,
  206. 'emails.email': 1,
  207. })
  208. if (!req.session.pendingSecondaryEmail) {
  209. logger.err(
  210. {},
  211. 'error checking confirmation code. missing pendingSecondaryEmail'
  212. )
  213. return res.status(500).json({
  214. message: {
  215. key: 'error_performing_request',
  216. },
  217. })
  218. }
  219. const newSecondaryEmail = req.session.pendingSecondaryEmail.email
  220. try {
  221. await checkSecondaryConfirmCodeRateLimiter.consume(newSecondaryEmail, 1, {
  222. method: 'email',
  223. })
  224. } catch (err) {
  225. if (err?.remainingPoints === 0) {
  226. return res.sendStatus(429)
  227. } else {
  228. return res.status(500).json({
  229. message: {
  230. key: 'error_performing_request',
  231. },
  232. })
  233. }
  234. }
  235. if (
  236. req.session.pendingSecondaryEmail.confirmCodeExpiresTimestamp < Date.now()
  237. ) {
  238. return res.status(403).json({
  239. message: { key: 'expired_confirmation_code' },
  240. })
  241. }
  242. if (!tsscmp(req.session.pendingSecondaryEmail.confirmCode, code)) {
  243. return res.status(403).json({
  244. message: { key: 'invalid_confirmation_code' },
  245. })
  246. }
  247. try {
  248. await UserAuditLogHandler.promises.addEntry(
  249. userId,
  250. 'add-email-via-code',
  251. userId,
  252. req.ip,
  253. { newSecondaryEmail }
  254. )
  255. await _sendSecurityAlertEmail(user, newSecondaryEmail)
  256. await UserUpdater.promises.addEmailAddress(
  257. userId,
  258. newSecondaryEmail,
  259. req.session.pendingSecondaryEmail.affiliationOptions,
  260. {
  261. initiatorId: user._id,
  262. ipAddress: req.ip,
  263. }
  264. )
  265. await UserUpdater.promises.confirmEmail(
  266. userId,
  267. newSecondaryEmail,
  268. req.session.pendingSecondaryEmail.affiliationOptions
  269. )
  270. delete req.session.pendingSecondaryEmail
  271. AnalyticsManager.recordEventForUserInBackground(
  272. user._id,
  273. 'email-verified',
  274. {
  275. provider: 'email',
  276. verification_type: 'token',
  277. isPrimary: false,
  278. }
  279. )
  280. const redirectUrl =
  281. AuthenticationController.getRedirectFromSession(req) || '/project'
  282. return res.json({
  283. redir: redirectUrl,
  284. })
  285. } catch (error) {
  286. if (error.name === 'EmailExistsError') {
  287. return res.status(409).json({
  288. message: {
  289. type: 'error',
  290. text: req.i18n.translate('email_already_registered'),
  291. },
  292. })
  293. }
  294. logger.err({ error }, 'failed to check confirmation code')
  295. return res.status(500).json({
  296. message: {
  297. key: 'error_performing_request',
  298. },
  299. })
  300. }
  301. }
  302. async function resendSecondaryEmailConfirmationCode(req, res) {
  303. if (!req.session.pendingSecondaryEmail) {
  304. logger.err(
  305. {},
  306. 'error resending confirmation code. missing pendingSecondaryEmail'
  307. )
  308. return res.status(500).json({
  309. message: {
  310. key: 'error_performing_request',
  311. },
  312. })
  313. }
  314. const email = req.session.pendingSecondaryEmail.email
  315. try {
  316. await resendSecondaryConfirmCodeRateLimiter.consume(email, 1, {
  317. method: 'email',
  318. })
  319. } catch (err) {
  320. if (err?.remainingPoints === 0) {
  321. return res.status(429).json({})
  322. } else {
  323. throw err
  324. }
  325. }
  326. try {
  327. const userId = SessionManager.getLoggedInUserId(req.session)
  328. await UserAuditLogHandler.promises.addEntry(
  329. userId,
  330. 'resend-add-email-code',
  331. userId,
  332. req.ip,
  333. {
  334. newSecondaryEmail: email,
  335. }
  336. )
  337. const { confirmCode, confirmCodeExpiresTimestamp } =
  338. await UserEmailsConfirmationHandler.promises.sendConfirmationCode(
  339. email,
  340. true
  341. )
  342. req.session.pendingSecondaryEmail.confirmCode = confirmCode
  343. req.session.pendingSecondaryEmail.confirmCodeExpiresTimestamp =
  344. confirmCodeExpiresTimestamp
  345. return res.status(200).json({
  346. message: { key: 'we_sent_new_code' },
  347. })
  348. } catch (err) {
  349. logger.err({ err, email }, 'failed to send confirmation code')
  350. return res.status(500).json({
  351. key: 'error_performing_request',
  352. })
  353. }
  354. }
  355. async function confirmSecondaryEmailPage(req, res) {
  356. const userId = SessionManager.getLoggedInUserId(req.session)
  357. if (!req.session.pendingSecondaryEmail) {
  358. const redirectURL =
  359. AuthenticationController.getRedirectFromSession(req) || '/project'
  360. return res.redirect(redirectURL)
  361. }
  362. // Populates splitTestVariants with a value for the split test name and allows
  363. // Pug to read it
  364. await SplitTestHandler.promises.getAssignment(req, res, 'misc-b2c-pages-bs5')
  365. AnalyticsManager.recordEventForUserInBackground(
  366. userId,
  367. 'confirm-secondary-email-page-displayed'
  368. )
  369. res.render('user/confirmSecondaryEmail', {
  370. email: req.session.pendingSecondaryEmail.email,
  371. })
  372. }
  373. async function addSecondaryEmailPage(req, res) {
  374. const userId = SessionManager.getLoggedInUserId(req.session)
  375. const confirmedEmails =
  376. await UserGetter.promises.getUserConfirmedEmails(userId)
  377. if (confirmedEmails.length >= 2) {
  378. const redirectURL =
  379. AuthenticationController.getRedirectFromSession(req) || '/project'
  380. return res.redirect(redirectURL)
  381. }
  382. AnalyticsManager.recordEventForUserInBackground(
  383. userId,
  384. 'add-secondary-email-page-displayed'
  385. )
  386. res.render('user/addSecondaryEmail')
  387. }
  388. async function primaryEmailCheckPage(req, res) {
  389. const userId = SessionManager.getLoggedInUserId(req.session)
  390. const user = await UserGetter.promises.getUser(userId, {
  391. lastPrimaryEmailCheck: 1,
  392. signUpDate: 1,
  393. email: 1,
  394. emails: 1,
  395. })
  396. if (!UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)) {
  397. return res.redirect('/project')
  398. }
  399. AnalyticsManager.recordEventForUserInBackground(
  400. userId,
  401. 'primary-email-check-page-displayed'
  402. )
  403. const { variant } = await SplitTestHandler.promises.getAssignment(
  404. req,
  405. res,
  406. 'auth-pages-bs5'
  407. )
  408. const template =
  409. variant === 'enabled'
  410. ? 'user/primaryEmailCheck-bs5'
  411. : 'user/primaryEmailCheck'
  412. res.render(template)
  413. }
  414. async function primaryEmailCheck(req, res) {
  415. const userId = SessionManager.getLoggedInUserId(req.session)
  416. await UserUpdater.promises.updateUser(userId, {
  417. $set: { lastPrimaryEmailCheck: new Date() },
  418. })
  419. AnalyticsManager.recordEventForUserInBackground(
  420. userId,
  421. 'primary-email-check-done'
  422. )
  423. // We want to redirect to prompt a user to add a secondary email if their primary
  424. // is an institutional email and they dont' already have a secondary.
  425. if (Features.hasFeature('saas') && req.capabilitySet.has('add-affiliation')) {
  426. const confirmedEmails =
  427. await UserGetter.promises.getUserConfirmedEmails(userId)
  428. if (confirmedEmails.length < 2) {
  429. const { email: primaryEmail } = SessionManager.getSessionUser(req.session)
  430. const primaryEmailDomain = EmailHelper.getDomain(primaryEmail)
  431. const institution = (
  432. await Modules.promises.hooks.fire(
  433. 'getInstitutionViaDomain',
  434. primaryEmailDomain
  435. )
  436. )?.[0]
  437. if (institution) {
  438. return AsyncFormHelper.redirect(req, res, '/user/emails/add-secondary')
  439. }
  440. }
  441. }
  442. AsyncFormHelper.redirect(req, res, '/project')
  443. }
  444. async function showConfirm(req, res, next) {
  445. res.render('user/confirm_email', {
  446. token: req.query.token,
  447. title: 'confirm_email',
  448. })
  449. }
  450. async function remove(req, res) {
  451. const userId = SessionManager.getLoggedInUserId(req.session)
  452. const email = EmailHelper.parseEmail(req.body.email)
  453. if (!email) {
  454. return res.sendStatus(422)
  455. }
  456. const auditLog = {
  457. initiatorId: userId,
  458. ipAddress: req.ip,
  459. }
  460. await UserUpdater.promises.removeEmailAddress(userId, email, auditLog)
  461. res.sendStatus(200)
  462. }
  463. const UserEmailsController = {
  464. list(req, res, next) {
  465. const userId = SessionManager.getLoggedInUserId(req.session)
  466. UserGetter.getUserFullEmails(userId, function (error, fullEmails) {
  467. if (error) {
  468. return next(error)
  469. }
  470. res.json(fullEmails)
  471. })
  472. },
  473. add: expressify(add),
  474. addWithConfirmationCode: expressify(addWithConfirmationCode),
  475. checkSecondaryEmailConfirmationCode: expressify(
  476. checkSecondaryEmailConfirmationCode
  477. ),
  478. resendSecondaryEmailConfirmationCode: expressify(
  479. resendSecondaryEmailConfirmationCode
  480. ),
  481. remove: expressify(remove),
  482. setDefault(req, res, next) {
  483. const userId = SessionManager.getLoggedInUserId(req.session)
  484. const email = EmailHelper.parseEmail(req.body.email)
  485. if (!email) {
  486. return res.sendStatus(422)
  487. }
  488. const auditLog = {
  489. initiatorId: userId,
  490. ipAddress: req.ip,
  491. }
  492. UserUpdater.setDefaultEmailAddress(
  493. userId,
  494. email,
  495. false,
  496. auditLog,
  497. true,
  498. err => {
  499. if (err) {
  500. return UserEmailsController._handleEmailError(err, req, res, next)
  501. }
  502. SessionManager.setInSessionUser(req.session, { email })
  503. const user = SessionManager.getSessionUser(req.session)
  504. UserSessionsManager.removeSessionsFromRedis(
  505. user,
  506. req.sessionID, // remove all sessions except the current session
  507. err => {
  508. if (err)
  509. logger.warn(
  510. { err },
  511. 'failed revoking secondary sessions after changing default email'
  512. )
  513. }
  514. )
  515. res.sendStatus(200)
  516. }
  517. )
  518. },
  519. endorse(req, res, next) {
  520. const userId = SessionManager.getLoggedInUserId(req.session)
  521. const email = EmailHelper.parseEmail(req.body.email)
  522. if (!email) {
  523. return res.sendStatus(422)
  524. }
  525. endorseAffiliation(
  526. userId,
  527. email,
  528. req.body.role,
  529. req.body.department,
  530. function (error) {
  531. if (error) {
  532. return next(error)
  533. }
  534. res.sendStatus(204)
  535. }
  536. )
  537. },
  538. resendConfirmation: expressify(resendConfirmation),
  539. sendReconfirmation: expressify(sendReconfirmation),
  540. addSecondaryEmailPage: expressify(addSecondaryEmailPage),
  541. confirmSecondaryEmailPage: expressify(confirmSecondaryEmailPage),
  542. primaryEmailCheckPage: expressify(primaryEmailCheckPage),
  543. primaryEmailCheck: expressify(primaryEmailCheck),
  544. showConfirm: expressify(showConfirm),
  545. confirm(req, res, next) {
  546. const { token } = req.body
  547. if (!token) {
  548. return res.status(422).json({
  549. message: req.i18n.translate('confirmation_link_broken'),
  550. })
  551. }
  552. UserEmailsConfirmationHandler.confirmEmailFromToken(
  553. req,
  554. token,
  555. function (error, userData) {
  556. if (error) {
  557. if (error instanceof Errors.ForbiddenError) {
  558. res.status(403).json({
  559. message: {
  560. key: 'confirm-email-wrong-user',
  561. text: `We can’t confirm this email. You must be logged in with the Overleaf account that requested the new secondary email.`,
  562. },
  563. })
  564. } else if (error instanceof Errors.NotFoundError) {
  565. res.status(404).json({
  566. message: req.i18n.translate('confirmation_token_invalid'),
  567. })
  568. } else {
  569. next(error)
  570. }
  571. } else {
  572. const { userId, email } = userData
  573. const tokenPrefix = token.substring(0, AUDIT_LOG_TOKEN_PREFIX_LENGTH)
  574. UserAuditLogHandler.addEntry(
  575. userId,
  576. 'confirm-email',
  577. userId,
  578. req.ip,
  579. { token: tokenPrefix, email },
  580. auditLogError => {
  581. if (auditLogError) {
  582. logger.error(
  583. { error: auditLogError, userId, token: tokenPrefix },
  584. 'failed to add audit log entry'
  585. )
  586. }
  587. UserGetter.getUser(
  588. userData.userId,
  589. { email: 1 },
  590. function (error, user) {
  591. if (error) {
  592. logger.error(
  593. { error, userId: userData.userId },
  594. 'failed to get user'
  595. )
  596. }
  597. const isPrimary = user?.email === userData.email
  598. AnalyticsManager.recordEventForUserInBackground(
  599. userData.userId,
  600. 'email-verified',
  601. {
  602. provider: 'email',
  603. verification_type: 'link',
  604. isPrimary,
  605. }
  606. )
  607. res.sendStatus(200)
  608. }
  609. )
  610. }
  611. )
  612. }
  613. }
  614. )
  615. },
  616. _handleEmailError(error, req, res, next) {
  617. if (error instanceof Errors.UnconfirmedEmailError) {
  618. return HttpErrorHandler.conflict(req, res, 'email must be confirmed')
  619. } else if (error instanceof Errors.EmailExistsError) {
  620. const message = req.i18n.translate('email_already_registered')
  621. return HttpErrorHandler.conflict(req, res, message)
  622. } else if (error.message === '422: Email does not belong to university') {
  623. const message = req.i18n.translate('email_does_not_belong_to_university')
  624. return HttpErrorHandler.conflict(req, res, message)
  625. }
  626. next(error)
  627. },
  628. }
  629. module.exports = UserEmailsController