user-registrations.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import express from 'express'
  2. import { UserRegistrationModel } from '@server/models/user/user-registration'
  3. import { MRegistration } from '@server/types/models'
  4. import { forceNumber, pick } from '@shared/core-utils'
  5. import { HttpStatusCode } from '@shared/models'
  6. function checkRegistrationIdExist (idArg: number | string, res: express.Response) {
  7. const id = forceNumber(idArg)
  8. return checkRegistrationExist(() => UserRegistrationModel.load(id), res)
  9. }
  10. function checkRegistrationEmailExist (email: string, res: express.Response, abortResponse = true) {
  11. return checkRegistrationExist(() => UserRegistrationModel.loadByEmail(email), res, abortResponse)
  12. }
  13. async function checkRegistrationHandlesDoNotAlreadyExist (options: {
  14. username: string
  15. channelHandle: string
  16. email: string
  17. res: express.Response
  18. }) {
  19. const { res } = options
  20. const registration = await UserRegistrationModel.loadByEmailOrHandle(pick(options, [ 'username', 'email', 'channelHandle' ]))
  21. if (registration) {
  22. res.fail({
  23. status: HttpStatusCode.CONFLICT_409,
  24. message: 'Registration with this username, channel name or email already exists.'
  25. })
  26. return false
  27. }
  28. return true
  29. }
  30. async function checkRegistrationExist (finder: () => Promise<MRegistration>, res: express.Response, abortResponse = true) {
  31. const registration = await finder()
  32. if (!registration) {
  33. if (abortResponse === true) {
  34. res.fail({
  35. status: HttpStatusCode.NOT_FOUND_404,
  36. message: 'User not found'
  37. })
  38. }
  39. return false
  40. }
  41. res.locals.userRegistration = registration
  42. return true
  43. }
  44. export {
  45. checkRegistrationIdExist,
  46. checkRegistrationEmailExist,
  47. checkRegistrationHandlesDoNotAlreadyExist,
  48. checkRegistrationExist
  49. }