server.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import express from 'express'
  2. import { body } from 'express-validator'
  3. import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
  4. import { isHostValid, isValidContactBody } from '../../helpers/custom-validators/servers'
  5. import { isUserDisplayNameValid } from '../../helpers/custom-validators/users'
  6. import { logger } from '../../helpers/logger'
  7. import { CONFIG, isEmailEnabled } from '../../initializers/config'
  8. import { Redis } from '../../lib/redis'
  9. import { ServerModel } from '../../models/server/server'
  10. import { areValidationErrors } from './shared'
  11. const serverGetValidator = [
  12. body('host').custom(isHostValid).withMessage('Should have a valid host'),
  13. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  14. if (areValidationErrors(req, res)) return
  15. const server = await ServerModel.loadByHost(req.body.host)
  16. if (!server) {
  17. return res.fail({
  18. status: HttpStatusCode.NOT_FOUND_404,
  19. message: 'Server host not found.'
  20. })
  21. }
  22. res.locals.server = server
  23. return next()
  24. }
  25. ]
  26. const contactAdministratorValidator = [
  27. body('fromName')
  28. .custom(isUserDisplayNameValid),
  29. body('fromEmail')
  30. .isEmail(),
  31. body('body')
  32. .custom(isValidContactBody),
  33. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  34. if (areValidationErrors(req, res)) return
  35. if (CONFIG.CONTACT_FORM.ENABLED === false) {
  36. return res.fail({
  37. status: HttpStatusCode.CONFLICT_409,
  38. message: 'Contact form is not enabled on this instance.'
  39. })
  40. }
  41. if (isEmailEnabled() === false) {
  42. return res.fail({
  43. status: HttpStatusCode.CONFLICT_409,
  44. message: 'Emailer is not enabled on this instance.'
  45. })
  46. }
  47. if (await Redis.Instance.doesContactFormIpExist(req.ip)) {
  48. logger.info('Refusing a contact form by %s: already sent one recently.', req.ip)
  49. return res.fail({
  50. status: HttpStatusCode.FORBIDDEN_403,
  51. message: 'You already sent a contact form recently.'
  52. })
  53. }
  54. return next()
  55. }
  56. ]
  57. // ---------------------------------------------------------------------------
  58. export {
  59. serverGetValidator,
  60. contactAdministratorValidator
  61. }