Send follow/accept
[oweals/peertube.git] / server / middlewares / validators / users.ts
1 import { body, param } from 'express-validator/check'
2 import 'express-validator'
3 import * as express from 'express'
4 import * as Promise from 'bluebird'
5 import * as validator from 'validator'
6
7 import { database as db } from '../../initializers/database'
8 import { checkErrors } from './utils'
9 import {
10   isSignupAllowed,
11   logger,
12   isUserUsernameValid,
13   isUserPasswordValid,
14   isUserVideoQuotaValid,
15   isUserDisplayNSFWValid,
16   isIdOrUUIDValid,
17   isUserRoleValid
18 } from '../../helpers'
19 import { UserInstance, VideoInstance } from '../../models'
20
21 const usersAddValidator = [
22   body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
23   body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
24   body('email').isEmail().withMessage('Should have a valid email'),
25   body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
26   body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
27
28   (req: express.Request, res: express.Response, next: express.NextFunction) => {
29     logger.debug('Checking usersAdd parameters', { parameters: req.body })
30
31     checkErrors(req, res, () => {
32       checkUserDoesNotAlreadyExist(req.body.username, req.body.email, res, next)
33     })
34   }
35 ]
36
37 const usersRegisterValidator = [
38   body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
39   body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
40   body('email').isEmail().withMessage('Should have a valid email'),
41
42   (req: express.Request, res: express.Response, next: express.NextFunction) => {
43     logger.debug('Checking usersRegister parameters', { parameters: req.body })
44
45     checkErrors(req, res, () => {
46       checkUserDoesNotAlreadyExist(req.body.username, req.body.email, res, next)
47     })
48   }
49 ]
50
51 const usersRemoveValidator = [
52   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
53
54   (req: express.Request, res: express.Response, next: express.NextFunction) => {
55     logger.debug('Checking usersRemove parameters', { parameters: req.params })
56
57     checkErrors(req, res, () => {
58       checkUserExists(req.params.id, res, (err, user) => {
59         if (err) {
60           logger.error('Error in usersRemoveValidator.', err)
61           return res.sendStatus(500)
62         }
63
64         if (user.username === 'root') {
65           return res.status(400)
66                     .send({ error: 'Cannot remove the root user' })
67                     .end()
68         }
69
70         return next()
71       })
72     })
73   }
74 ]
75
76 const usersUpdateValidator = [
77   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
78   body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
79   body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
80   body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
81
82   (req: express.Request, res: express.Response, next: express.NextFunction) => {
83     logger.debug('Checking usersUpdate parameters', { parameters: req.body })
84
85     checkErrors(req, res, () => {
86       checkUserExists(req.params.id, res, next)
87     })
88   }
89 ]
90
91 const usersUpdateMeValidator = [
92   body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
93   body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
94   body('displayNSFW').optional().custom(isUserDisplayNSFWValid).withMessage('Should have a valid display Not Safe For Work attribute'),
95
96   (req: express.Request, res: express.Response, next: express.NextFunction) => {
97     // TODO: Add old password verification
98     logger.debug('Checking usersUpdateMe parameters', { parameters: req.body })
99
100     checkErrors(req, res, next)
101   }
102 ]
103
104 const usersGetValidator = [
105   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
106
107   (req: express.Request, res: express.Response, next: express.NextFunction) => {
108     checkErrors(req, res, () => {
109       checkUserExists(req.params.id, res, next)
110     })
111   }
112 ]
113
114 const usersVideoRatingValidator = [
115   param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
116
117   (req: express.Request, res: express.Response, next: express.NextFunction) => {
118     logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
119
120     checkErrors(req, res, () => {
121       let videoPromise: Promise<VideoInstance>
122
123       if (validator.isUUID(req.params.videoId)) {
124         videoPromise = db.Video.loadByUUID(req.params.videoId)
125       } else {
126         videoPromise = db.Video.load(req.params.videoId)
127       }
128
129       videoPromise
130         .then(video => {
131           if (!video) {
132             return res.status(404)
133                       .json({ error: 'Video not found' })
134                       .end()
135           }
136
137           return next()
138         })
139         .catch(err => {
140           logger.error('Error in user request validator.', err)
141           return res.sendStatus(500)
142         })
143     })
144   }
145 ]
146
147 const ensureUserRegistrationAllowed = [
148   (req: express.Request, res: express.Response, next: express.NextFunction) => {
149     isSignupAllowed().then(allowed => {
150       if (allowed === false) {
151         return res.status(403)
152                   .send({ error: 'User registration is not enabled or user limit is reached.' })
153                   .end()
154       }
155
156       return next()
157     })
158   }
159 ]
160
161 // ---------------------------------------------------------------------------
162
163 export {
164   usersAddValidator,
165   usersRegisterValidator,
166   usersRemoveValidator,
167   usersUpdateValidator,
168   usersUpdateMeValidator,
169   usersVideoRatingValidator,
170   ensureUserRegistrationAllowed,
171   usersGetValidator
172 }
173
174 // ---------------------------------------------------------------------------
175
176 function checkUserExists (id: number, res: express.Response, callback: (err: Error, user: UserInstance) => void) {
177   db.User.loadById(id)
178     .then(user => {
179       if (!user) {
180         return res.status(404)
181                   .send({ error: 'User not found' })
182                   .end()
183       }
184
185       res.locals.user = user
186       return callback(null, user)
187     })
188     .catch(err => {
189       logger.error('Error in user request validator.', err)
190       return res.sendStatus(500)
191     })
192 }
193
194 function checkUserDoesNotAlreadyExist (username: string, email: string, res: express.Response, callback: () => void) {
195   db.User.loadByUsernameOrEmail(username, email)
196       .then(user => {
197         if (user) {
198           return res.status(409)
199                     .send({ error: 'User with this username of email already exists.' })
200                     .end()
201         }
202
203         return callback()
204       })
205       .catch(err => {
206         logger.error('Error in usersAdd request validator.', err)
207         return res.sendStatus(500)
208       })
209 }