Type functions
[oweals/peertube.git] / server / middlewares / validators / pods.ts
1 import 'express-validator'
2 import * as express from 'express'
3
4 import { database as db } from '../../initializers/database'
5 import { checkErrors } from './utils'
6 import { logger } from '../../helpers'
7 import { CONFIG } from '../../initializers'
8 import { hasFriends } from '../../lib'
9 import { isTestInstance } from '../../helpers'
10
11 function makeFriendsValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
12   // Force https if the administrator wants to make friends
13   if (isTestInstance() === false && CONFIG.WEBSERVER.SCHEME === 'http') {
14     return res.status(400).send('Cannot make friends with a non HTTPS webserver.')
15   }
16
17   req.checkBody('hosts', 'Should have an array of unique hosts').isEachUniqueHostValid()
18
19   logger.debug('Checking makeFriends parameters', { parameters: req.body })
20
21   checkErrors(req, res, function () {
22     hasFriends(function (err, heHasFriends) {
23       if (err) {
24         logger.error('Cannot know if we have friends.', { error: err })
25         res.sendStatus(500)
26       }
27
28       if (heHasFriends === true) {
29         // We need to quit our friends before make new ones
30         return res.sendStatus(409)
31       }
32
33       return next()
34     })
35   })
36 }
37
38 function podsAddValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
39   req.checkBody('host', 'Should have a host').isHostValid()
40   req.checkBody('email', 'Should have an email').isEmail()
41   req.checkBody('publicKey', 'Should have a public key').notEmpty()
42   logger.debug('Checking podsAdd parameters', { parameters: req.body })
43
44   checkErrors(req, res, function () {
45     db.Pod.loadByHost(req.body.host, function (err, pod) {
46       if (err) {
47         logger.error('Cannot load pod by host.', { error: err })
48         res.sendStatus(500)
49       }
50
51       // Pod with this host already exists
52       if (pod) {
53         return res.sendStatus(409)
54       }
55
56       return next()
57     })
58   })
59 }
60
61 // ---------------------------------------------------------------------------
62
63 export {
64   makeFriendsValidator,
65   podsAddValidator
66 }