server.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. 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.fail({
  19. status: HttpStatusCode.NOT_FOUND_404,
  20. message: 'Server host not found.'
  21. })
  22. }
  23. res.locals.server = server
  24. return next()
  25. }
  26. ]
  27. const contactAdministratorValidator = [
  28. body('fromName')
  29. .custom(isUserDisplayNameValid).withMessage('Should have a valid name'),
  30. body('fromEmail')
  31. .isEmail().withMessage('Should have a valid email'),
  32. body('body')
  33. .custom(isValidContactBody).withMessage('Should have a valid body'),
  34. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  35. logger.debug('Checking contactAdministratorValidator parameters', { parameters: req.body })
  36. if (areValidationErrors(req, res)) return
  37. if (CONFIG.CONTACT_FORM.ENABLED === false) {
  38. return res.fail({
  39. status: HttpStatusCode.CONFLICT_409,
  40. message: 'Contact form is not enabled on this instance.'
  41. })
  42. }
  43. if (isEmailEnabled() === false) {
  44. return res.fail({
  45. status: HttpStatusCode.CONFLICT_409,
  46. message: 'Emailer is not enabled on this instance.'
  47. })
  48. }
  49. if (await Redis.Instance.doesContactFormIpExist(req.ip)) {
  50. logger.info('Refusing a contact form by %s: already sent one recently.', req.ip)
  51. return res.fail({
  52. status: HttpStatusCode.FORBIDDEN_403,
  53. message: 'You already sent a contact form recently.'
  54. })
  55. }
  56. return next()
  57. }
  58. ]
  59. // ---------------------------------------------------------------------------
  60. export {
  61. serverGetValidator,
  62. contactAdministratorValidator
  63. }