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'
9 isUserAutoPlayVideoValid,
10 isUserDescriptionValid, isUserDisplayNameValid,
11 isUserNSFWPolicyValid,
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'
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'),
33 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
34 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
36 if (areValidationErrors(req, res)) return
37 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
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'),
48 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
49 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
51 if (areValidationErrors(req, res)) return
52 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
58 const usersRemoveValidator = [
59 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
61 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
62 logger.debug('Checking usersRemove parameters', { parameters: req.params })
64 if (areValidationErrors(req, res)) return
65 if (!await checkUserIdExist(req.params.id, res)) return
67 const user = res.locals.user
68 if (user.username === 'root') {
69 return res.status(400)
70 .send({ error: 'Cannot remove the root user' })
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'),
84 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
85 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
87 if (areValidationErrors(req, res)) return
88 if (!await checkUserIdExist(req.params.id, res)) return
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.' })
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'),
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') })
113 if (areValidationErrors(req, res)) return
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(', ')
125 (req: express.Request, res: express.Response, next: express.NextFunction) => {
126 logger.debug('Checking usersUpdateMyAvatarValidator parameters', { files: req.files })
128 if (areValidationErrors(req, res)) return
130 const imageFile = req.files['avatarfile'][0] as Express.Multer.File
131 if (imageFile.size > CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max) {
133 .send({ error: `The size of the avatar is too big (>${CONSTRAINTS_FIELDS.ACTORS.AVATAR.FILE_SIZE.max}).` })
142 const usersGetValidator = [
143 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
145 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
146 logger.debug('Checking usersGet parameters', { parameters: req.params })
148 if (areValidationErrors(req, res)) return
149 if (!await checkUserIdExist(req.params.id, res)) return
155 const usersVideoRatingValidator = [
156 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
158 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
159 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
161 if (areValidationErrors(req, res)) return
162 if (!await isVideoExist(req.params.videoId, res)) return
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.' })
181 const ensureUserRegistrationAllowedForIP = [
182 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
183 const allowed = isSignupAllowedForCurrentIP(req.ip)
185 if (allowed === false) {
186 return res.status(403)
187 .send({ error: 'You are not on a network authorized for registration.' })
195 const usersAskResetPasswordValidator = [
196 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
198 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
199 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
201 if (areValidationErrors(req, res)) return
202 const exists = await checkUserEmailExist(req.body.email, res, false)
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()
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'),
218 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
219 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
221 if (areValidationErrors(req, res)) return
222 if (!await checkUserIdExist(req.params.id, res)) return
224 const user = res.locals.user as UserModel
225 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
227 if (redisVerificationString !== req.body.verificationString) {
230 .send({ error: 'Invalid verification string.' })
238 // ---------------------------------------------------------------------------
242 usersRegisterValidator,
243 usersRemoveValidator,
244 usersUpdateValidator,
245 usersUpdateMeValidator,
246 usersVideoRatingValidator,
247 ensureUserRegistrationAllowed,
248 ensureUserRegistrationAllowedForIP,
250 usersUpdateMyAvatarValidator,
251 usersAskResetPasswordValidator,
252 usersResetPasswordValidator
255 // ---------------------------------------------------------------------------
257 function checkUserIdExist (id: number, res: express.Response) {
258 return checkUserExist(() => UserModel.loadById(id), res)
261 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
262 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
265 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
266 const user = await UserModel.loadByUsernameOrEmail(username, email)
270 .send({ error: 'User with this username or email already exists.' })
275 const actor = await ActorModel.loadLocalByName(username)
278 .send({ error: 'Another actor (account/channel) with this name already exists.' })
286 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
287 const user = await finder()
290 if (abortResponse === true) {
292 .send({ error: 'User not found' })
299 res.locals.user = user