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 .customSanitizer(toBooleanOrNull)
45 .isBoolean().withMessage('Should be a valid boolean banned state'),
47 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
48 logger.debug('Checking usersList parameters', { parameters: req.query })
50 if (areValidationErrors(req, res)) return
56 const usersAddValidator = [
57 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
58 body('password').custom(isUserPasswordValidOrEmpty).withMessage('Should have a valid password'),
59 body('email').isEmail().withMessage('Should have a valid email'),
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)' })
83 const usersRegisterValidator = [
84 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
85 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
86 body('email').isEmail().withMessage('Should have a valid email'),
89 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
93 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
94 body('channel.displayName')
96 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
98 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
99 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
101 if (areValidationErrors(req, res)) return
102 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
104 const body: UserRegister = req.body
106 if (!body.channel.name || !body.channel.displayName) {
107 return res.status(400)
108 .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
111 if (body.channel.name === body.username) {
112 return res.status(400)
113 .json({ error: 'Channel name cannot be the same as user username.' })
116 const existing = await ActorModel.loadLocalByName(body.channel.name)
118 return res.status(409)
119 .json({ error: `Channel with name ${body.channel.name} already exists.` })
127 const usersRemoveValidator = [
128 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
130 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
131 logger.debug('Checking usersRemove parameters', { parameters: req.params })
133 if (areValidationErrors(req, res)) return
134 if (!await checkUserIdExist(req.params.id, res)) return
136 const user = res.locals.user
137 if (user.username === 'root') {
138 return res.status(400)
139 .json({ error: 'Cannot remove the root user' })
146 const usersBlockingValidator = [
147 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
148 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
150 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
151 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
153 if (areValidationErrors(req, res)) return
154 if (!await checkUserIdExist(req.params.id, res)) return
156 const user = res.locals.user
157 if (user.username === 'root') {
158 return res.status(400)
159 .json({ error: 'Cannot block the root user' })
166 const deleteMeValidator = [
167 (req: express.Request, res: express.Response, next: express.NextFunction) => {
168 const user = res.locals.oauth.token.User
169 if (user.username === 'root') {
170 return res.status(400)
171 .json({ error: 'You cannot delete your root account.' })
179 const usersUpdateValidator = [
180 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
181 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
182 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
183 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
184 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
185 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
188 .customSanitizer(toIntOrNull)
189 .custom(isUserRoleValid).withMessage('Should have a valid role'),
190 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
192 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
193 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
195 if (areValidationErrors(req, res)) return
196 if (!await checkUserIdExist(req.params.id, res)) return
198 const user = res.locals.user
199 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
200 return res.status(400)
201 .json({ error: 'Cannot change root role.' })
208 const usersUpdateMeValidator = [
211 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
214 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
215 body('currentPassword')
217 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
220 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
223 .isEmail().withMessage('Should have a valid email attribute'),
226 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
227 body('autoPlayVideo')
229 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
230 body('videoLanguages')
232 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
233 body('videosHistoryEnabled')
235 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
238 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
239 body('noInstanceConfigWarningModal')
241 .custom(v => isNoInstanceConfigWarningModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
242 body('noWelcomeModal')
244 .custom(v => isNoWelcomeModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
245 body('autoPlayNextVideo')
247 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
249 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
250 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
252 const user = res.locals.oauth.token.User
254 if (req.body.password || req.body.email) {
255 if (user.pluginAuth !== null) {
256 return res.status(400)
257 .json({ error: 'You cannot update your email or password that is associated with an external auth system.' })
260 if (!req.body.currentPassword) {
261 return res.status(400)
262 .json({ error: 'currentPassword parameter is missing.' })
265 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
266 return res.status(401)
267 .json({ error: 'currentPassword is invalid.' })
271 if (areValidationErrors(req, res)) return
277 const usersGetValidator = [
278 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
279 query('withStats').optional().isBoolean().withMessage('Should have a valid stats flag'),
281 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
282 logger.debug('Checking usersGet parameters', { parameters: req.params })
284 if (areValidationErrors(req, res)) return
285 if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
291 const usersVideoRatingValidator = [
292 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
294 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
295 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
297 if (areValidationErrors(req, res)) return
298 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
304 const ensureUserRegistrationAllowed = [
305 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
306 const allowedParams = {
311 const allowedResult = await Hooks.wrapPromiseFun(
314 'filter:api.user.signup.allowed.result'
317 if (allowedResult.allowed === false) {
318 return res.status(403)
319 .json({ error: allowedResult.errorMessage || 'User registration is not enabled or user limit is reached.' })
326 const ensureUserRegistrationAllowedForIP = [
327 (req: express.Request, res: express.Response, next: express.NextFunction) => {
328 const allowed = isSignupAllowedForCurrentIP(req.ip)
330 if (allowed === false) {
331 return res.status(403)
332 .json({ error: 'You are not on a network authorized for registration.' })
339 const usersAskResetPasswordValidator = [
340 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
342 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
343 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
345 if (areValidationErrors(req, res)) return
347 const exists = await checkUserEmailExist(req.body.email, res, false)
349 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
350 // Do not leak our emails
351 return res.status(204).end()
358 const usersResetPasswordValidator = [
359 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
360 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
361 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
363 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
364 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
366 if (areValidationErrors(req, res)) return
367 if (!await checkUserIdExist(req.params.id, res)) return
369 const user = res.locals.user
370 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
372 if (redisVerificationString !== req.body.verificationString) {
375 .json({ error: 'Invalid verification string.' })
382 const usersAskSendVerifyEmailValidator = [
383 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
385 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
386 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
388 if (areValidationErrors(req, res)) return
389 const exists = await checkUserEmailExist(req.body.email, res, false)
391 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
392 // Do not leak our emails
393 return res.status(204).end()
400 const usersVerifyEmailValidator = [
402 .isInt().not().isEmpty().withMessage('Should have a valid id'),
404 body('verificationString')
405 .not().isEmpty().withMessage('Should have a valid verification string'),
406 body('isPendingEmail')
408 .customSanitizer(toBooleanOrNull),
410 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
411 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
413 if (areValidationErrors(req, res)) return
414 if (!await checkUserIdExist(req.params.id, res)) return
416 const user = res.locals.user
417 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
419 if (redisVerificationString !== req.body.verificationString) {
422 .json({ error: 'Invalid verification string.' })
429 const userAutocompleteValidator = [
430 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
433 const ensureAuthUserOwnsAccountValidator = [
434 (req: express.Request, res: express.Response, next: express.NextFunction) => {
435 const user = res.locals.oauth.token.User
437 if (res.locals.account.id !== user.Account.id) {
438 return res.status(403)
439 .json({ error: 'Only owner can access ratings list.' })
446 const ensureCanManageUser = [
447 (req: express.Request, res: express.Response, next: express.NextFunction) => {
448 const authUser = res.locals.oauth.token.User
449 const onUser = res.locals.user
451 if (authUser.role === UserRole.ADMINISTRATOR) return next()
452 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
454 return res.status(403)
455 .json({ error: 'A moderator can only manager users.' })
459 // ---------------------------------------------------------------------------
465 usersRegisterValidator,
466 usersBlockingValidator,
467 usersRemoveValidator,
468 usersUpdateValidator,
469 usersUpdateMeValidator,
470 usersVideoRatingValidator,
471 ensureUserRegistrationAllowed,
472 ensureUserRegistrationAllowedForIP,
474 usersAskResetPasswordValidator,
475 usersResetPasswordValidator,
476 usersAskSendVerifyEmailValidator,
477 usersVerifyEmailValidator,
478 userAutocompleteValidator,
479 ensureAuthUserOwnsAccountValidator,
483 // ---------------------------------------------------------------------------
485 function checkUserIdExist (idArg: number | string, res: express.Response, withStats = false) {
486 const id = parseInt(idArg + '', 10)
487 return checkUserExist(() => UserModel.loadById(id, withStats), res)
490 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
491 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
494 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
495 const user = await UserModel.loadByUsernameOrEmail(username, email)
499 .json({ error: 'User with this username or email already exists.' })
503 const actor = await ActorModel.loadLocalByName(username)
506 .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
513 async function checkUserExist (finder: () => Bluebird<MUserDefault>, res: express.Response, abortResponse = true) {
514 const user = await finder()
517 if (abortResponse === true) {
519 .json({ error: 'User not found' })
525 res.locals.user = user