Handle line feeds in comments
[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,
11   isUserDisplayNSFWValid,
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 } from '../../helpers/utils'
20 import { 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('description').optional().custom(isUserDescriptionValid).withMessage('Should have a valid description'),
102   body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
103   body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
104   body('displayNSFW').optional().custom(isUserDisplayNSFWValid).withMessage('Should have a valid display Not Safe For Work attribute'),
105   body('autoPlayVideo').optional().custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
106
107   (req: express.Request, res: express.Response, next: express.NextFunction) => {
108     // TODO: Add old password verification
109     logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
110
111     if (areValidationErrors(req, res)) return
112
113     return next()
114   }
115 ]
116
117 const usersUpdateMyAvatarValidator = [
118   body('avatarfile').custom((value, { req }) => isAvatarFile(req.files)).withMessage(
119     'This file is not supported. Please, make sure it is of the following type : '
120     + CONSTRAINTS_FIELDS.ACTORS.AVATAR.EXTNAME.join(', ')
121   ),
122
123   (req: express.Request, res: express.Response, next: express.NextFunction) => {
124     logger.debug('Checking usersUpdateMyAvatarValidator parameters', { files: req.files })
125
126     if (areValidationErrors(req, res)) return
127
128     const imageFile = req.files['avatarfile'][0] as Express.Multer.File
129     if (imageFile.size > CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max) {
130       res.status(400)
131         .send({ error: `The size of the avatar is too big (>${CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max}).` })
132         .end()
133       return
134     }
135
136     return next()
137   }
138 ]
139
140 const usersGetValidator = [
141   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
142
143   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
144     logger.debug('Checking usersGet parameters', { parameters: req.params })
145
146     if (areValidationErrors(req, res)) return
147     if (!await checkUserIdExist(req.params.id, res)) return
148
149     return next()
150   }
151 ]
152
153 const usersVideoRatingValidator = [
154   param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
155
156   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
157     logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
158
159     if (areValidationErrors(req, res)) return
160     if (!await isVideoExist(req.params.videoId, res)) return
161
162     return next()
163   }
164 ]
165
166 const ensureUserRegistrationAllowed = [
167   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
168     const allowed = await isSignupAllowed()
169     if (allowed === false) {
170       return res.status(403)
171                 .send({ error: 'User registration is not enabled or user limit is reached.' })
172                 .end()
173     }
174
175     return next()
176   }
177 ]
178
179 const usersAskResetPasswordValidator = [
180   body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
181
182   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
183     logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
184
185     if (areValidationErrors(req, res)) return
186     const exists = await checkUserEmailExist(req.body.email, res, false)
187     if (!exists) {
188       logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
189       // Do not leak our emails
190       return res.status(204).end()
191     }
192
193     return next()
194   }
195 ]
196
197 const usersResetPasswordValidator = [
198   param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
199   body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
200   body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
201
202   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
203     logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
204
205     if (areValidationErrors(req, res)) return
206     if (!await checkUserIdExist(req.params.id, res)) return
207
208     const user = res.locals.user as UserModel
209     const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
210
211     if (redisVerificationString !== req.body.verificationString) {
212       return res
213         .status(403)
214         .send({ error: 'Invalid verification string.' })
215         .end()
216     }
217
218     return next()
219   }
220 ]
221
222 // ---------------------------------------------------------------------------
223
224 export {
225   usersAddValidator,
226   usersRegisterValidator,
227   usersRemoveValidator,
228   usersUpdateValidator,
229   usersUpdateMeValidator,
230   usersVideoRatingValidator,
231   ensureUserRegistrationAllowed,
232   usersGetValidator,
233   usersUpdateMyAvatarValidator,
234   usersAskResetPasswordValidator,
235   usersResetPasswordValidator
236 }
237
238 // ---------------------------------------------------------------------------
239
240 function checkUserIdExist (id: number, res: express.Response) {
241   return checkUserExist(() => UserModel.loadById(id), res)
242 }
243
244 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
245   return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
246 }
247
248 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
249   const user = await UserModel.loadByUsernameOrEmail(username, email)
250
251   if (user) {
252     res.status(409)
253               .send({ error: 'User with this username of email already exists.' })
254               .end()
255     return false
256   }
257
258   return true
259 }
260
261 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
262   const user = await finder()
263
264   if (!user) {
265     if (abortResponse === true) {
266       res.status(404)
267         .send({ error: 'User not found' })
268         .end()
269     }
270
271     return false
272   }
273
274   res.locals.user = user
275
276   return true
277 }