]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/users.ts
Fix images size limit
[github/Chocobozzz/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 or too large. 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 return next()
131 }
132 ]
133
134 const usersGetValidator = [
135 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
136
137 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
138 logger.debug('Checking usersGet parameters', { parameters: req.params })
139
140 if (areValidationErrors(req, res)) return
141 if (!await checkUserIdExist(req.params.id, res)) return
142
143 return next()
144 }
145 ]
146
147 const usersVideoRatingValidator = [
148 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
149
150 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
151 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
152
153 if (areValidationErrors(req, res)) return
154 if (!await isVideoExist(req.params.videoId, res)) return
155
156 return next()
157 }
158 ]
159
160 const ensureUserRegistrationAllowed = [
161 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
162 const allowed = await isSignupAllowed()
163 if (allowed === false) {
164 return res.status(403)
165 .send({ error: 'User registration is not enabled or user limit is reached.' })
166 .end()
167 }
168
169 return next()
170 }
171 ]
172
173 const ensureUserRegistrationAllowedForIP = [
174 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
175 const allowed = isSignupAllowedForCurrentIP(req.ip)
176
177 if (allowed === false) {
178 return res.status(403)
179 .send({ error: 'You are not on a network authorized for registration.' })
180 .end()
181 }
182
183 return next()
184 }
185 ]
186
187 const usersAskResetPasswordValidator = [
188 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
189
190 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
191 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
192
193 if (areValidationErrors(req, res)) return
194 const exists = await checkUserEmailExist(req.body.email, res, false)
195 if (!exists) {
196 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
197 // Do not leak our emails
198 return res.status(204).end()
199 }
200
201 return next()
202 }
203 ]
204
205 const usersResetPasswordValidator = [
206 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
207 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
208 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
209
210 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
211 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
212
213 if (areValidationErrors(req, res)) return
214 if (!await checkUserIdExist(req.params.id, res)) return
215
216 const user = res.locals.user as UserModel
217 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
218
219 if (redisVerificationString !== req.body.verificationString) {
220 return res
221 .status(403)
222 .send({ error: 'Invalid verification string.' })
223 .end()
224 }
225
226 return next()
227 }
228 ]
229
230 // ---------------------------------------------------------------------------
231
232 export {
233 usersAddValidator,
234 usersRegisterValidator,
235 usersRemoveValidator,
236 usersUpdateValidator,
237 usersUpdateMeValidator,
238 usersVideoRatingValidator,
239 ensureUserRegistrationAllowed,
240 ensureUserRegistrationAllowedForIP,
241 usersGetValidator,
242 usersUpdateMyAvatarValidator,
243 usersAskResetPasswordValidator,
244 usersResetPasswordValidator
245 }
246
247 // ---------------------------------------------------------------------------
248
249 function checkUserIdExist (id: number, res: express.Response) {
250 return checkUserExist(() => UserModel.loadById(id), res)
251 }
252
253 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
254 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
255 }
256
257 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
258 const user = await UserModel.loadByUsernameOrEmail(username, email)
259
260 if (user) {
261 res.status(409)
262 .send({ error: 'User with this username or email already exists.' })
263 .end()
264 return false
265 }
266
267 const actor = await ActorModel.loadLocalByName(username)
268 if (actor) {
269 res.status(409)
270 .send({ error: 'Another actor (account/channel) with this name already exists.' })
271 .end()
272 return false
273 }
274
275 return true
276 }
277
278 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
279 const user = await finder()
280
281 if (!user) {
282 if (abortResponse === true) {
283 res.status(404)
284 .send({ error: 'User not found' })
285 .end()
286 }
287
288 return false
289 }
290
291 res.locals.user = user
292
293 return true
294 }