UserEmailsConfirmationHandler.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const EmailHelper = require('../Helpers/EmailHelper')
  2. const EmailHandler = require('../Email/EmailHandler')
  3. const OneTimeTokenHandler = require('../Security/OneTimeTokenHandler')
  4. const settings = require('settings-sharelatex')
  5. const Errors = require('../Errors/Errors')
  6. const UserUpdater = require('./UserUpdater')
  7. const UserGetter = require('./UserGetter')
  8. const ONE_YEAR_IN_S = 365 * 24 * 60 * 60
  9. const UserEmailsConfirmationHandler = {
  10. sendConfirmationEmail(userId, email, emailTemplate, callback) {
  11. if (arguments.length === 3) {
  12. callback = emailTemplate
  13. emailTemplate = 'confirmEmail'
  14. }
  15. // when force-migrating accounts to v2 from v1, we don't want to send confirmation messages -
  16. // setting this env var allows us to turn this behaviour off
  17. if (process.env['SHARELATEX_NO_CONFIRMATION_MESSAGES'] != null) {
  18. return callback(null)
  19. }
  20. email = EmailHelper.parseEmail(email)
  21. if (!email) {
  22. return callback(new Error('invalid email'))
  23. }
  24. const data = { user_id: userId, email }
  25. OneTimeTokenHandler.getNewToken(
  26. 'email_confirmation',
  27. data,
  28. { expiresIn: ONE_YEAR_IN_S },
  29. function(err, token) {
  30. if (err) {
  31. return callback(err)
  32. }
  33. const emailOptions = {
  34. to: email,
  35. confirmEmailUrl: `${
  36. settings.siteUrl
  37. }/user/emails/confirm?token=${token}`,
  38. sendingUser_id: userId
  39. }
  40. EmailHandler.sendEmail(emailTemplate, emailOptions, callback)
  41. }
  42. )
  43. },
  44. confirmEmailFromToken(token, callback) {
  45. OneTimeTokenHandler.getValueFromTokenAndExpire(
  46. 'email_confirmation',
  47. token,
  48. function(error, data) {
  49. if (error) {
  50. return callback(error)
  51. }
  52. if (!data) {
  53. return callback(new Errors.NotFoundError('no token found'))
  54. }
  55. const userId = data.user_id
  56. const email = data.email
  57. if (!userId || email !== EmailHelper.parseEmail(email)) {
  58. return callback(new Errors.NotFoundError('invalid data'))
  59. }
  60. UserGetter.getUser(userId, {}, function(error, user) {
  61. if (error) {
  62. return callback(error)
  63. }
  64. if (!user) {
  65. return callback(new Errors.NotFoundError('user not found'))
  66. }
  67. const emailExists = user.emails.some(
  68. emailData => emailData.email === email
  69. )
  70. if (!emailExists) {
  71. return callback(new Errors.NotFoundError('email missing for user'))
  72. }
  73. UserUpdater.confirmEmail(userId, email, callback)
  74. })
  75. }
  76. )
  77. }
  78. }
  79. module.exports = UserEmailsConfirmationHandler