aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/validators/server.ts
blob: f6812647bf3cc8cce20f6b902d98ef2742e1e4ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import * as express from 'express'
import { logger } from '../../helpers/logger'
import { areValidationErrors } from './utils'
import { isHostValid, isValidContactBody } from '../../helpers/custom-validators/servers'
import { ServerModel } from '../../models/server/server'
import { body } from 'express-validator'
import { isUserDisplayNameValid } from '../../helpers/custom-validators/users'
import { Emailer } from '../../lib/emailer'
import { Redis } from '../../lib/redis'
import { CONFIG } from '../../initializers/config'

const serverGetValidator = [
  body('host').custom(isHostValid).withMessage('Should have a valid host'),

  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    logger.debug('Checking serverGetValidator parameters', { parameters: req.body })

    if (areValidationErrors(req, res)) return

    const server = await ServerModel.loadByHost(req.body.host)
    if (!server) {
      return res.status(404)
         .send({ error: 'Server host not found.' })
         .end()
    }

    res.locals.server = server

    return next()
  }
]

const contactAdministratorValidator = [
  body('fromName')
    .custom(isUserDisplayNameValid).withMessage('Should have a valid name'),
  body('fromEmail')
    .isEmail().withMessage('Should have a valid email'),
  body('body')
    .custom(isValidContactBody).withMessage('Should have a valid body'),

  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    logger.debug('Checking contactAdministratorValidator parameters', { parameters: req.body })

    if (areValidationErrors(req, res)) return

    if (CONFIG.CONTACT_FORM.ENABLED === false) {
      return res
        .status(409)
        .send({ error: 'Contact form is not enabled on this instance.' })
        .end()
    }

    if (Emailer.isEnabled() === false) {
      return res
        .status(409)
        .send({ error: 'Emailer is not enabled on this instance.' })
        .end()
    }

    if (await Redis.Instance.doesContactFormIpExist(req.ip)) {
      logger.info('Refusing a contact form by %s: already sent one recently.', req.ip)

      return res
        .status(403)
        .send({ error: 'You already sent a contact form recently.' })
        .end()
    }

    return next()
  }
]

// ---------------------------------------------------------------------------

export {
  serverGetValidator,
  contactAdministratorValidator
}