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