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