UserEmailsConfirmationHandler.js 2.7 KB

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