]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/middlewares/validators/users.ts
Add more info logging
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / users.ts
... / ...
CommitLineData
1import * as Bluebird from 'bluebird'
2import * as express from 'express'
3import 'express-validator'
4import { body, param } from 'express-validator/check'
5import { omit } from 'lodash'
6import { isIdOrUUIDValid } from '../../helpers/custom-validators/misc'
7import {
8 isUserAutoPlayVideoValid,
9 isUserDescriptionValid,
10 isUserDisplayNameValid,
11 isUserNSFWPolicyValid,
12 isUserPasswordValid,
13 isUserRoleValid,
14 isUserUsernameValid,
15 isUserVideoQuotaValid
16} from '../../helpers/custom-validators/users'
17import { isVideoExist } from '../../helpers/custom-validators/videos'
18import { logger } from '../../helpers/logger'
19import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/utils'
20import { Redis } from '../../lib/redis'
21import { UserModel } from '../../models/account/user'
22import { areValidationErrors } from './utils'
23import { ActorModel } from '../../models/activitypub/actor'
24
25const 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
42const 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
57const 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
77const 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
100const 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
118const usersGetValidator = [
119 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
120
121 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
122 logger.debug('Checking usersGet parameters', { parameters: req.params })
123
124 if (areValidationErrors(req, res)) return
125 if (!await checkUserIdExist(req.params.id, res)) return
126
127 return next()
128 }
129]
130
131const usersVideoRatingValidator = [
132 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
133
134 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
135 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
136
137 if (areValidationErrors(req, res)) return
138 if (!await isVideoExist(req.params.videoId, res)) return
139
140 return next()
141 }
142]
143
144const ensureUserRegistrationAllowed = [
145 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
146 const allowed = await isSignupAllowed()
147 if (allowed === false) {
148 return res.status(403)
149 .send({ error: 'User registration is not enabled or user limit is reached.' })
150 .end()
151 }
152
153 return next()
154 }
155]
156
157const ensureUserRegistrationAllowedForIP = [
158 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
159 const allowed = isSignupAllowedForCurrentIP(req.ip)
160
161 if (allowed === false) {
162 return res.status(403)
163 .send({ error: 'You are not on a network authorized for registration.' })
164 .end()
165 }
166
167 return next()
168 }
169]
170
171const usersAskResetPasswordValidator = [
172 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
173
174 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
175 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
176
177 if (areValidationErrors(req, res)) return
178 const exists = await checkUserEmailExist(req.body.email, res, false)
179 if (!exists) {
180 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
181 // Do not leak our emails
182 return res.status(204).end()
183 }
184
185 return next()
186 }
187]
188
189const usersResetPasswordValidator = [
190 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
191 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
192 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
193
194 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
195 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
196
197 if (areValidationErrors(req, res)) return
198 if (!await checkUserIdExist(req.params.id, res)) return
199
200 const user = res.locals.user as UserModel
201 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
202
203 if (redisVerificationString !== req.body.verificationString) {
204 return res
205 .status(403)
206 .send({ error: 'Invalid verification string.' })
207 .end()
208 }
209
210 return next()
211 }
212]
213
214// ---------------------------------------------------------------------------
215
216export {
217 usersAddValidator,
218 usersRegisterValidator,
219 usersRemoveValidator,
220 usersUpdateValidator,
221 usersUpdateMeValidator,
222 usersVideoRatingValidator,
223 ensureUserRegistrationAllowed,
224 ensureUserRegistrationAllowedForIP,
225 usersGetValidator,
226 usersAskResetPasswordValidator,
227 usersResetPasswordValidator
228}
229
230// ---------------------------------------------------------------------------
231
232function checkUserIdExist (id: number, res: express.Response) {
233 return checkUserExist(() => UserModel.loadById(id), res)
234}
235
236function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
237 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
238}
239
240async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
241 const user = await UserModel.loadByUsernameOrEmail(username, email)
242
243 if (user) {
244 res.status(409)
245 .send({ error: 'User with this username or email already exists.' })
246 .end()
247 return false
248 }
249
250 const actor = await ActorModel.loadLocalByName(username)
251 if (actor) {
252 res.status(409)
253 .send({ error: 'Another actor (account/channel) with this name already exists.' })
254 .end()
255 return false
256 }
257
258 return true
259}
260
261async 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}