1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import { body, param } from 'express-validator'
4 import { omit } from 'lodash'
5 import { isIdOrUUIDValid, toBooleanOrNull, toIntOrNull } from '../../helpers/custom-validators/misc'
8 isUserAutoPlayVideoValid,
9 isUserBlockedReasonValid,
10 isUserDescriptionValid,
11 isUserDisplayNameValid,
12 isUserNSFWPolicyValid,
17 isUserVideoQuotaDailyValid,
18 isUserVideoQuotaValid,
19 isUserVideosHistoryEnabledValid
20 } from '../../helpers/custom-validators/users'
21 import { logger } from '../../helpers/logger'
22 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
23 import { Redis } from '../../lib/redis'
24 import { UserModel } from '../../models/account/user'
25 import { areValidationErrors } from './utils'
26 import { ActorModel } from '../../models/activitypub/actor'
27 import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor'
28 import { isVideoChannelNameValid } from '../../helpers/custom-validators/video-channels'
29 import { UserRegister } from '../../../shared/models/users/user-register.model'
30 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
31 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
32 import { doesVideoExist } from '../../helpers/middlewares'
33 import { UserRole } from '../../../shared/models/users'
35 const usersAddValidator = [
36 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
37 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
38 body('email').isEmail().withMessage('Should have a valid email'),
39 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
40 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
41 body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
42 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
44 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
45 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
47 if (areValidationErrors(req, res)) return
48 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
50 const authUser = res.locals.oauth.token.User
51 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
52 return res.status(403)
53 .json({ error: 'You can only create users (and not administrators or moderators' })
60 const usersRegisterValidator = [
61 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
62 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
63 body('email').isEmail().withMessage('Should have a valid email'),
66 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
70 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
71 body('channel.displayName')
73 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
75 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
76 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
78 if (areValidationErrors(req, res)) return
79 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
81 const body: UserRegister = req.body
83 if (!body.channel.name || !body.channel.displayName) {
84 return res.status(400)
85 .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
88 if (body.channel.name === body.username) {
89 return res.status(400)
90 .json({ error: 'Channel name cannot be the same than user username.' })
93 const existing = await ActorModel.loadLocalByName(body.channel.name)
95 return res.status(409)
96 .json({ error: `Channel with name ${body.channel.name} already exists.` })
104 const usersRemoveValidator = [
105 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
107 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
108 logger.debug('Checking usersRemove parameters', { parameters: req.params })
110 if (areValidationErrors(req, res)) return
111 if (!await checkUserIdExist(req.params.id, res)) return
113 const user = res.locals.user
114 if (user.username === 'root') {
115 return res.status(400)
116 .json({ error: 'Cannot remove the root user' })
123 const usersBlockingValidator = [
124 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
125 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
127 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
128 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
130 if (areValidationErrors(req, res)) return
131 if (!await checkUserIdExist(req.params.id, res)) return
133 const user = res.locals.user
134 if (user.username === 'root') {
135 return res.status(400)
136 .json({ error: 'Cannot block the root user' })
143 const deleteMeValidator = [
144 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
145 const user = res.locals.oauth.token.User
146 if (user.username === 'root') {
147 return res.status(400)
148 .json({ error: 'You cannot delete your root account.' })
156 const usersUpdateValidator = [
157 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
158 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
159 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
160 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
161 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
162 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
163 body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
164 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
166 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
167 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
169 if (areValidationErrors(req, res)) return
170 if (!await checkUserIdExist(req.params.id, res)) return
172 const user = res.locals.user
173 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
174 return res.status(400)
175 .json({ error: 'Cannot change root role.' })
182 const usersUpdateMeValidator = [
185 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
188 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
189 body('currentPassword')
191 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
194 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
197 .isEmail().withMessage('Should have a valid email attribute'),
200 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
201 body('autoPlayVideo')
203 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
204 body('videoLanguages')
206 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
207 body('videosHistoryEnabled')
209 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
212 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
214 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
215 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
217 if (req.body.password || req.body.email) {
218 if (!req.body.currentPassword) {
219 return res.status(400)
220 .json({ error: 'currentPassword parameter is missing.' })
224 const user = res.locals.oauth.token.User
225 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
226 return res.status(401)
227 .json({ error: 'currentPassword is invalid.' })
231 if (areValidationErrors(req, res)) return
237 const usersGetValidator = [
238 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
240 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
241 logger.debug('Checking usersGet parameters', { parameters: req.params })
243 if (areValidationErrors(req, res)) return
244 if (!await checkUserIdExist(req.params.id, res)) return
250 const usersVideoRatingValidator = [
251 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
253 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
254 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
256 if (areValidationErrors(req, res)) return
257 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
263 const ensureUserRegistrationAllowed = [
264 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
265 const allowed = await isSignupAllowed()
266 if (allowed === false) {
267 return res.status(403)
268 .json({ error: 'User registration is not enabled or user limit is reached.' })
275 const ensureUserRegistrationAllowedForIP = [
276 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
277 const allowed = isSignupAllowedForCurrentIP(req.ip)
279 if (allowed === false) {
280 return res.status(403)
281 .json({ error: 'You are not on a network authorized for registration.' })
288 const usersAskResetPasswordValidator = [
289 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
291 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
292 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
294 if (areValidationErrors(req, res)) return
296 const exists = await checkUserEmailExist(req.body.email, res, false)
298 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
299 // Do not leak our emails
300 return res.status(204).end()
307 const usersResetPasswordValidator = [
308 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
309 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
310 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
312 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
313 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
315 if (areValidationErrors(req, res)) return
316 if (!await checkUserIdExist(req.params.id, res)) return
318 const user = res.locals.user
319 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
321 if (redisVerificationString !== req.body.verificationString) {
324 .json({ error: 'Invalid verification string.' })
331 const usersAskSendVerifyEmailValidator = [
332 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
334 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
335 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
337 if (areValidationErrors(req, res)) return
338 const exists = await checkUserEmailExist(req.body.email, res, false)
340 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
341 // Do not leak our emails
342 return res.status(204).end()
349 const usersVerifyEmailValidator = [
351 .isInt().not().isEmpty().withMessage('Should have a valid id'),
353 body('verificationString')
354 .not().isEmpty().withMessage('Should have a valid verification string'),
355 body('isPendingEmail')
357 .customSanitizer(toBooleanOrNull),
359 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
360 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
362 if (areValidationErrors(req, res)) return
363 if (!await checkUserIdExist(req.params.id, res)) return
365 const user = res.locals.user
366 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
368 if (redisVerificationString !== req.body.verificationString) {
371 .json({ error: 'Invalid verification string.' })
378 const userAutocompleteValidator = [
379 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
382 const ensureAuthUserOwnsAccountValidator = [
383 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
384 const user = res.locals.oauth.token.User
386 if (res.locals.account.id !== user.Account.id) {
387 return res.status(403)
388 .json({ error: 'Only owner can access ratings list.' })
395 const ensureCanManageUser = [
396 (req: express.Request, res: express.Response, next: express.NextFunction) => {
397 const authUser = res.locals.oauth.token.User
398 const onUser = res.locals.user
400 if (authUser.role === UserRole.ADMINISTRATOR) return next()
401 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
403 return res.status(403)
404 .json({ error: 'A moderator can only manager users.' })
408 // ---------------------------------------------------------------------------
413 usersRegisterValidator,
414 usersBlockingValidator,
415 usersRemoveValidator,
416 usersUpdateValidator,
417 usersUpdateMeValidator,
418 usersVideoRatingValidator,
419 ensureUserRegistrationAllowed,
420 ensureUserRegistrationAllowedForIP,
422 usersAskResetPasswordValidator,
423 usersResetPasswordValidator,
424 usersAskSendVerifyEmailValidator,
425 usersVerifyEmailValidator,
426 userAutocompleteValidator,
427 ensureAuthUserOwnsAccountValidator,
431 // ---------------------------------------------------------------------------
433 function checkUserIdExist (id: number, res: express.Response) {
434 return checkUserExist(() => UserModel.loadById(id), res)
437 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
438 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
441 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
442 const user = await UserModel.loadByUsernameOrEmail(username, email)
446 .json({ error: 'User with this username or email already exists.' })
450 const actor = await ActorModel.loadLocalByName(username)
453 .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
460 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
461 const user = await finder()
464 if (abortResponse === true) {
466 .json({ error: 'User not found' })
472 res.locals.user = user