1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import { body, param, query } from 'express-validator'
4 import { omit } from 'lodash'
5 import { isIdOrUUIDValid, toBooleanOrNull, toIntOrNull } from '../../helpers/custom-validators/misc'
7 isNoInstanceConfigWarningModal,
10 isUserAutoPlayNextVideoValid,
11 isUserAutoPlayVideoValid,
12 isUserBlockedReasonValid,
13 isUserDescriptionValid,
14 isUserDisplayNameValid,
15 isUserNSFWPolicyValid,
17 isUserPasswordValidOrEmpty,
21 isUserVideoQuotaDailyValid,
22 isUserVideoQuotaValid,
23 isUserVideosHistoryEnabledValid
24 } from '../../helpers/custom-validators/users'
25 import { logger } from '../../helpers/logger'
26 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
27 import { Redis } from '../../lib/redis'
28 import { UserModel } from '../../models/account/user'
29 import { areValidationErrors } from './utils'
30 import { ActorModel } from '../../models/activitypub/actor'
31 import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor'
32 import { isVideoChannelNameValid } from '../../helpers/custom-validators/video-channels'
33 import { UserRegister } from '../../../shared/models/users/user-register.model'
34 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
35 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
36 import { doesVideoExist } from '../../helpers/middlewares'
37 import { UserRole } from '../../../shared/models/users'
38 import { MUserDefault } from '@server/types/models'
39 import { Hooks } from '@server/lib/plugins/hooks'
41 const usersListValidator = [
44 .isBoolean().withMessage('Should be a valid boolean banned state'),
46 (req: express.Request, res: express.Response, next: express.NextFunction) => {
47 logger.debug('Checking usersList parameters', { parameters: req.query })
49 if (areValidationErrors(req, res)) return
55 const usersAddValidator = [
56 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
57 body('password').custom(isUserPasswordValidOrEmpty).withMessage('Should have a valid password'),
58 body('email').isEmail().withMessage('Should have a valid email'),
59 body('channelName').optional().custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
60 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
61 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
63 .customSanitizer(toIntOrNull)
64 .custom(isUserRoleValid).withMessage('Should have a valid role'),
65 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
67 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
68 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
70 if (areValidationErrors(req, res)) return
71 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
73 const authUser = res.locals.oauth.token.User
74 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
75 return res.status(403)
76 .json({ error: 'You can only create users (and not administrators or moderators)' })
79 if (req.body.channelName) {
80 if (req.body.channelName === req.body.username) {
81 return res.status(400)
82 .json({ error: 'Channel name cannot be the same as user username.' })
85 const existing = await ActorModel.loadLocalByName(req.body.channelName)
87 return res.status(409)
88 .json({ error: `Channel with name ${req.body.channelName} already exists.` })
96 const usersRegisterValidator = [
97 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
98 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
99 body('email').isEmail().withMessage('Should have a valid email'),
102 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
106 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
107 body('channel.displayName')
109 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
111 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
112 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
114 if (areValidationErrors(req, res)) return
115 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
117 const body: UserRegister = req.body
119 if (!body.channel.name || !body.channel.displayName) {
120 return res.status(400)
121 .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
124 if (body.channel.name === body.username) {
125 return res.status(400)
126 .json({ error: 'Channel name cannot be the same as user username.' })
129 const existing = await ActorModel.loadLocalByName(body.channel.name)
131 return res.status(409)
132 .json({ error: `Channel with name ${body.channel.name} already exists.` })
140 const usersRemoveValidator = [
141 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
143 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
144 logger.debug('Checking usersRemove parameters', { parameters: req.params })
146 if (areValidationErrors(req, res)) return
147 if (!await checkUserIdExist(req.params.id, res)) return
149 const user = res.locals.user
150 if (user.username === 'root') {
151 return res.status(400)
152 .json({ error: 'Cannot remove the root user' })
159 const usersBlockingValidator = [
160 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
161 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
163 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
164 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
166 if (areValidationErrors(req, res)) return
167 if (!await checkUserIdExist(req.params.id, res)) return
169 const user = res.locals.user
170 if (user.username === 'root') {
171 return res.status(400)
172 .json({ error: 'Cannot block the root user' })
179 const deleteMeValidator = [
180 (req: express.Request, res: express.Response, next: express.NextFunction) => {
181 const user = res.locals.oauth.token.User
182 if (user.username === 'root') {
183 return res.status(400)
184 .json({ error: 'You cannot delete your root account.' })
192 const usersUpdateValidator = [
193 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
194 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
195 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
196 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
197 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
198 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
201 .customSanitizer(toIntOrNull)
202 .custom(isUserRoleValid).withMessage('Should have a valid role'),
203 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
205 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
206 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
208 if (areValidationErrors(req, res)) return
209 if (!await checkUserIdExist(req.params.id, res)) return
211 const user = res.locals.user
212 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
213 return res.status(400)
214 .json({ error: 'Cannot change root role.' })
221 const usersUpdateMeValidator = [
224 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
227 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
228 body('currentPassword')
230 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
233 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
236 .isEmail().withMessage('Should have a valid email attribute'),
239 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
240 body('autoPlayVideo')
242 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
243 body('videoLanguages')
245 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
246 body('videosHistoryEnabled')
248 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
251 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
252 body('noInstanceConfigWarningModal')
254 .custom(v => isNoInstanceConfigWarningModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
255 body('noWelcomeModal')
257 .custom(v => isNoWelcomeModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
258 body('autoPlayNextVideo')
260 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
262 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
263 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
265 const user = res.locals.oauth.token.User
267 if (req.body.password || req.body.email) {
268 if (user.pluginAuth !== null) {
269 return res.status(400)
270 .json({ error: 'You cannot update your email or password that is associated with an external auth system.' })
273 if (!req.body.currentPassword) {
274 return res.status(400)
275 .json({ error: 'currentPassword parameter is missing.' })
278 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
279 return res.status(401)
280 .json({ error: 'currentPassword is invalid.' })
284 if (areValidationErrors(req, res)) return
290 const usersGetValidator = [
291 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
292 query('withStats').optional().isBoolean().withMessage('Should have a valid stats flag'),
294 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
295 logger.debug('Checking usersGet parameters', { parameters: req.params })
297 if (areValidationErrors(req, res)) return
298 if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
304 const usersVideoRatingValidator = [
305 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
307 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
308 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
310 if (areValidationErrors(req, res)) return
311 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
317 const ensureUserRegistrationAllowed = [
318 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
319 const allowedParams = {
324 const allowedResult = await Hooks.wrapPromiseFun(
327 'filter:api.user.signup.allowed.result'
330 if (allowedResult.allowed === false) {
331 return res.status(403)
332 .json({ error: allowedResult.errorMessage || 'User registration is not enabled or user limit is reached.' })
339 const ensureUserRegistrationAllowedForIP = [
340 (req: express.Request, res: express.Response, next: express.NextFunction) => {
341 const allowed = isSignupAllowedForCurrentIP(req.ip)
343 if (allowed === false) {
344 return res.status(403)
345 .json({ error: 'You are not on a network authorized for registration.' })
352 const usersAskResetPasswordValidator = [
353 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
355 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
356 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
358 if (areValidationErrors(req, res)) return
360 const exists = await checkUserEmailExist(req.body.email, res, false)
362 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
363 // Do not leak our emails
364 return res.status(204).end()
371 const usersResetPasswordValidator = [
372 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
373 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
374 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
376 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
377 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
379 if (areValidationErrors(req, res)) return
380 if (!await checkUserIdExist(req.params.id, res)) return
382 const user = res.locals.user
383 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
385 if (redisVerificationString !== req.body.verificationString) {
388 .json({ error: 'Invalid verification string.' })
395 const usersAskSendVerifyEmailValidator = [
396 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
398 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
399 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
401 if (areValidationErrors(req, res)) return
402 const exists = await checkUserEmailExist(req.body.email, res, false)
404 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
405 // Do not leak our emails
406 return res.status(204).end()
413 const usersVerifyEmailValidator = [
415 .isInt().not().isEmpty().withMessage('Should have a valid id'),
417 body('verificationString')
418 .not().isEmpty().withMessage('Should have a valid verification string'),
419 body('isPendingEmail')
421 .customSanitizer(toBooleanOrNull),
423 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
424 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
426 if (areValidationErrors(req, res)) return
427 if (!await checkUserIdExist(req.params.id, res)) return
429 const user = res.locals.user
430 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
432 if (redisVerificationString !== req.body.verificationString) {
435 .json({ error: 'Invalid verification string.' })
442 const userAutocompleteValidator = [
443 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
446 const ensureAuthUserOwnsAccountValidator = [
447 (req: express.Request, res: express.Response, next: express.NextFunction) => {
448 const user = res.locals.oauth.token.User
450 if (res.locals.account.id !== user.Account.id) {
451 return res.status(403)
452 .json({ error: 'Only owner can access ratings list.' })
459 const ensureCanManageUser = [
460 (req: express.Request, res: express.Response, next: express.NextFunction) => {
461 const authUser = res.locals.oauth.token.User
462 const onUser = res.locals.user
464 if (authUser.role === UserRole.ADMINISTRATOR) return next()
465 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
467 return res.status(403)
468 .json({ error: 'A moderator can only manager users.' })
472 // ---------------------------------------------------------------------------
478 usersRegisterValidator,
479 usersBlockingValidator,
480 usersRemoveValidator,
481 usersUpdateValidator,
482 usersUpdateMeValidator,
483 usersVideoRatingValidator,
484 ensureUserRegistrationAllowed,
485 ensureUserRegistrationAllowedForIP,
487 usersAskResetPasswordValidator,
488 usersResetPasswordValidator,
489 usersAskSendVerifyEmailValidator,
490 usersVerifyEmailValidator,
491 userAutocompleteValidator,
492 ensureAuthUserOwnsAccountValidator,
496 // ---------------------------------------------------------------------------
498 function checkUserIdExist (idArg: number | string, res: express.Response, withStats = false) {
499 const id = parseInt(idArg + '', 10)
500 return checkUserExist(() => UserModel.loadById(id, withStats), res)
503 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
504 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
507 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
508 const user = await UserModel.loadByUsernameOrEmail(username, email)
512 .json({ error: 'User with this username or email already exists.' })
516 const actor = await ActorModel.loadLocalByName(username)
519 .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
526 async function checkUserExist (finder: () => Bluebird<MUserDefault>, res: express.Response, abortResponse = true) {
527 const user = await finder()
530 if (abortResponse === true) {
532 .json({ error: 'User not found' })
538 res.locals.user = user