UserActivateController.mjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import Path from 'node:path'
  2. import { fileURLToPath } from 'node:url'
  3. import UserGetter from '../../../../app/src/Features/User/UserGetter.js'
  4. import UserRegistrationHandler from '../../../../app/src/Features/User/UserRegistrationHandler.mjs'
  5. import ErrorController from '../../../../app/src/Features/Errors/ErrorController.mjs'
  6. import { expressify } from '@overleaf/promise-utils'
  7. const __dirname = Path.dirname(fileURLToPath(import.meta.url))
  8. function registerNewUser(req, res, next) {
  9. res.render(Path.resolve(__dirname, '../views/user/register'))
  10. }
  11. async function register(req, res, next) {
  12. const { email } = req.body
  13. if (email == null || email === '') {
  14. return res.sendStatus(422) // Unprocessable Entity
  15. }
  16. const { user, setNewPasswordUrl } =
  17. await UserRegistrationHandler.promises.registerNewUserAndSendActivationEmail(
  18. email
  19. )
  20. res.json({
  21. email: user.email,
  22. setNewPasswordUrl,
  23. })
  24. }
  25. async function activateAccountPage(req, res, next) {
  26. // An 'activation' is actually just a password reset on an account that
  27. // was set with a random password originally.
  28. if (req.query.user_id == null || req.query.token == null) {
  29. return ErrorController.notFound(req, res)
  30. }
  31. if (typeof req.query.user_id !== 'string') {
  32. return ErrorController.forbidden(req, res)
  33. }
  34. const user = await UserGetter.promises.getUser(req.query.user_id, {
  35. email: 1,
  36. loginCount: 1,
  37. })
  38. if (!user) {
  39. return ErrorController.notFound(req, res)
  40. }
  41. if (user.loginCount > 0) {
  42. // Already seen this user, so account must be activated.
  43. // This lets users keep clicking the 'activate' link in their email
  44. // as a way to log in which, if I know our users, they will.
  45. return res.redirect(`/login`)
  46. }
  47. req.session.doLoginAfterPasswordReset = true
  48. res.render(Path.resolve(__dirname, '../views/user/activate'), {
  49. title: 'activate_account',
  50. email: user.email,
  51. token: req.query.token,
  52. })
  53. }
  54. export default {
  55. registerNewUser,
  56. register: expressify(register),
  57. activateAccountPage: expressify(activateAccountPage),
  58. }