UserActivateController.mjs 2.2 KB

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