server.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import * as express from 'express'
  2. import { logger } from '../../helpers/logger'
  3. import { areValidationErrors } from './utils'
  4. import { isHostValid, isValidContactBody } from '../../helpers/custom-validators/servers'
  5. import { ServerModel } from '../../models/server/server'
  6. import { body } from 'express-validator/check'
  7. import { isUserDisplayNameValid } from '../../helpers/custom-validators/users'
  8. import { Emailer } from '../../lib/emailer'
  9. import { Redis } from '../../lib/redis'
  10. import { CONFIG } from '../../initializers/config'
  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. logger.debug('Checking serverGetValidator parameters', { parameters: req.body })
  15. if (areValidationErrors(req, res)) return
  16. const server = await ServerModel.loadByHost(req.body.host)
  17. if (!server) {
  18. return res.status(404)
  19. .send({ error: 'Server host not found.' })
  20. .end()
  21. }
  22. res.locals.server = server
  23. return next()
  24. }
  25. ]
  26. const contactAdministratorValidator = [
  27. body('fromName')
  28. .custom(isUserDisplayNameValid).withMessage('Should have a valid name'),
  29. body('fromEmail')
  30. .isEmail().withMessage('Should have a valid email'),
  31. body('body')
  32. .custom(isValidContactBody).withMessage('Should have a valid body'),
  33. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  34. logger.debug('Checking contactAdministratorValidator parameters', { parameters: req.body })
  35. if (areValidationErrors(req, res)) return
  36. if (CONFIG.CONTACT_FORM.ENABLED === false) {
  37. return res
  38. .status(409)
  39. .send({ error: 'Contact form is not enabled on this instance.' })
  40. .end()
  41. }
  42. if (Emailer.isEnabled() === false) {
  43. return res
  44. .status(409)
  45. .send({ error: 'Emailer is not enabled on this instance.' })
  46. .end()
  47. }
  48. if (await Redis.Instance.doesContactFormIpExist(req.ip)) {
  49. logger.info('Refusing a contact form by %s: already sent one recently.', req.ip)
  50. return res
  51. .status(403)
  52. .send({ error: 'You already sent a contact form recently.' })
  53. .end()
  54. }
  55. return next()
  56. }
  57. ]
  58. // ---------------------------------------------------------------------------
  59. export {
  60. serverGetValidator,
  61. contactAdministratorValidator
  62. }