Add ability for uploaders to schedule video update
[oweals/peertube.git] / server / middlewares / validators / users.ts
1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import 'express-validator'
4 import { body, param } from 'express-validator/check'
5 import { omit } from 'lodash'
6 import { isIdOrUUIDValid } from '../../helpers/custom-validators/misc'
7 import {
8   isAvatarFile,
9   isUserAutoPlayVideoValid,
10   isUserDescriptionValid, isUserDisplayNameValid,
11   isUserNSFWPolicyValid,
12   isUserPasswordValid,
13   isUserRoleValid,
14   isUserUsernameValid,
15   isUserVideoQuotaValid
16 } from '../../helpers/custom-validators/users'
17 import { isVideoExist } from '../../helpers/custom-validators/videos'
18 import { logger } from '../../helpers/logger'
19 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/utils'
20 import { CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
21 import { Redis } from '../../lib/redis'
22 import { UserModel } from '../../models/account/user'
23 import { areValidationErrors } from './utils'
24
25 const usersAddValidator = [
26   body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
27   body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
28   body('email').isEmail().withMessage('Should have a valid email'),
29   body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
30   body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
31
32   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
33     logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
34
35     if (areValidationErrors(req, res)) return
36     if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
37
38     return next()
39   }
40 ]
41
42 const usersRegisterValidator = [
43   body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
44   body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
45   body('email').isEmail().withMessage('Should have a valid email'),
46
47   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
48     logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
49
50     if (areValidationErrors(req, res)) return
51     if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
52
53     return next()
54   }
55 ]
56
57 const usersRemoveValidator = [
58   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
59
60   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
61     logger.debug('Checking usersRemove parameters', { parameters: req.params })
62
63     if (areValidationErrors(req, res)) return
64     if (!await checkUserIdExist(req.params.id, res)) return
65
66     const user = res.locals.user
67     if (user.username === 'root') {
68       return res.status(400)
69                 .send({ error: 'Cannot remove the root user' })
70                 .end()
71     }
72
73     return next()
74   }
75 ]
76
77 const usersUpdateValidator = [
78   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
79   body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
80   body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
81   body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
82
83   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
84     logger.debug('Checking usersUpdate parameters', { parameters: req.body })
85
86     if (areValidationErrors(req, res)) return
87     if (!await checkUserIdExist(req.params.id, res)) return
88
89     const user = res.locals.user
90     if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
91       return res.status(400)
92         .send({ error: 'Cannot change root role.' })
93         .end()
94     }
95
96     return next()
97   }
98 ]
99
100 const usersUpdateMeValidator = [
101   body('displayName').optional().custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
102   body('description').optional().custom(isUserDescriptionValid).withMessage('Should have a valid description'),
103   body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
104   body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
105   body('nsfwPolicy').optional().custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
106   body('autoPlayVideo').optional().custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
107
108   (req: express.Request, res: express.Response, next: express.NextFunction) => {
109     // TODO: Add old password verification
110     logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
111
112     if (areValidationErrors(req, res)) return
113
114     return next()
115   }
116 ]
117
118 const usersUpdateMyAvatarValidator = [
119   body('avatarfile').custom((value, { req }) => isAvatarFile(req.files)).withMessage(
120     'This file is not supported. Please, make sure it is of the following type : '
121     + CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME.join(', ')
122   ),
123
124   (req: express.Request, res: express.Response, next: express.NextFunction) => {
125     logger.debug('Checking usersUpdateMyAvatarValidator parameters', { files: req.files })
126
127     if (areValidationErrors(req, res)) return
128
129     const imageFile = req.files['avatarfile'][0] as Express.Multer.File
130     if (imageFile.size > CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max) {
131       res.status(400)
132         .send({ error: `The size of the avatar is too big (>${CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max}).` })
133         .end()
134       return
135     }
136
137     return next()
138   }
139 ]
140
141 const usersGetValidator = [
142   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
143
144   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
145     logger.debug('Checking usersGet parameters', { parameters: req.params })
146
147     if (areValidationErrors(req, res)) return
148     if (!await checkUserIdExist(req.params.id, res)) return
149
150     return next()
151   }
152 ]
153
154 const usersVideoRatingValidator = [
155   param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
156
157   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
158     logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
159
160     if (areValidationErrors(req, res)) return
161     if (!await isVideoExist(req.params.videoId, res)) return
162
163     return next()
164   }
165 ]
166
167 const ensureUserRegistrationAllowed = [
168   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
169     const allowed = await isSignupAllowed()
170     if (allowed === false) {
171       return res.status(403)
172                 .send({ error: 'User registration is not enabled or user limit is reached.' })
173                 .end()
174     }
175
176     return next()
177   }
178 ]
179
180 const ensureUserRegistrationAllowedForIP = [
181   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
182     const allowed = isSignupAllowedForCurrentIP(req.ip)
183
184     if (allowed === false) {
185       return res.status(403)
186                 .send({ error: 'You are not on a network authorized for registration.' })
187                 .end()
188     }
189
190     return next()
191   }
192 ]
193
194 const usersAskResetPasswordValidator = [
195   body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
196
197   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
198     logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
199
200     if (areValidationErrors(req, res)) return
201     const exists = await checkUserEmailExist(req.body.email, res, false)
202     if (!exists) {
203       logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
204       // Do not leak our emails
205       return res.status(204).end()
206     }
207
208     return next()
209   }
210 ]
211
212 const usersResetPasswordValidator = [
213   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
214   body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
215   body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
216
217   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
218     logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
219
220     if (areValidationErrors(req, res)) return
221     if (!await checkUserIdExist(req.params.id, res)) return
222
223     const user = res.locals.user as UserModel
224     const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
225
226     if (redisVerificationString !== req.body.verificationString) {
227       return res
228         .status(403)
229         .send({ error: 'Invalid verification string.' })
230         .end()
231     }
232
233     return next()
234   }
235 ]
236
237 // ---------------------------------------------------------------------------
238
239 export {
240   usersAddValidator,
241   usersRegisterValidator,
242   usersRemoveValidator,
243   usersUpdateValidator,
244   usersUpdateMeValidator,
245   usersVideoRatingValidator,
246   ensureUserRegistrationAllowed,
247   ensureUserRegistrationAllowedForIP,
248   usersGetValidator,
249   usersUpdateMyAvatarValidator,
250   usersAskResetPasswordValidator,
251   usersResetPasswordValidator
252 }
253
254 // ---------------------------------------------------------------------------
255
256 function checkUserIdExist (id: number, res: express.Response) {
257   return checkUserExist(() => UserModel.loadById(id), res)
258 }
259
260 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
261   return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
262 }
263
264 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
265   const user = await UserModel.loadByUsernameOrEmail(username, email)
266
267   if (user) {
268     res.status(409)
269               .send({ error: 'User with this username or email already exists.' })
270               .end()
271     return false
272   }
273
274   return true
275 }
276
277 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
278   const user = await finder()
279
280   if (!user) {
281     if (abortResponse === true) {
282       res.status(404)
283         .send({ error: 'User not found' })
284         .end()
285     }
286
287     return false
288   }
289
290   res.locals.user = user
291
292   return true
293 }