Add tests and fix bugs for video privacy
[oweals/peertube.git] / server / middlewares / validators / pods.ts
1 import { body, param } from 'express-validator/check'
2 import * as express from 'express'
3
4 import { database as db } from '../../initializers/database'
5 import { checkErrors } from './utils'
6 import { logger, isEachUniqueHostValid } from '../../helpers'
7 import { CONFIG } from '../../initializers'
8 import { hasFriends } from '../../lib'
9 import { isTestInstance } from '../../helpers'
10
11 const makeFriendsValidator = [
12   body('hosts').custom(isEachUniqueHostValid).withMessage('Should have an array of unique hosts'),
13
14   (req: express.Request, res: express.Response, next: express.NextFunction) => {
15     // Force https if the administrator wants to make friends
16     if (isTestInstance() === false && CONFIG.WEBSERVER.SCHEME === 'http') {
17       return res.status(400)
18                 .json({
19                   error: 'Cannot make friends with a non HTTPS web server.'
20                 })
21                 .end()
22     }
23
24     logger.debug('Checking makeFriends parameters', { parameters: req.body })
25
26     checkErrors(req, res, () => {
27       hasFriends()
28         .then(heHasFriends => {
29           if (heHasFriends === true) {
30             // We need to quit our friends before make new ones
31             return res.sendStatus(409)
32           }
33
34           return next()
35         })
36         .catch(err => {
37           logger.error('Cannot know if we have friends.', err)
38           res.sendStatus(500)
39         })
40     })
41   }
42 ]
43
44 const podRemoveValidator = [
45   param('id').isNumeric().not().isEmpty().withMessage('Should have a valid id'),
46
47   (req: express.Request, res: express.Response, next: express.NextFunction) => {
48     logger.debug('Checking podRemoveValidator parameters', { parameters: req.params })
49
50     checkErrors(req, res, () => {
51       db.Pod.load(req.params.id)
52         .then(pod => {
53           if (!pod) {
54             logger.error('Cannot find pod %d.', req.params.id)
55             return res.sendStatus(404)
56           }
57
58           res.locals.pod = pod
59           return next()
60         })
61         .catch(err => {
62           logger.error('Cannot load pod %d.', req.params.id, err)
63           res.sendStatus(500)
64         })
65     })
66   }
67 ]
68
69 // ---------------------------------------------------------------------------
70
71 export {
72   makeFriendsValidator,
73   podRemoveValidator
74 }