1 import * as express from 'express'
2 import { body, param, query } from 'express-validator'
3 import { omit } from 'lodash'
4 import { Hooks } from '@server/lib/plugins/hooks'
5 import { MUserDefault } from '@server/types/models'
6 import { HttpStatusCode } from '../../../shared/models/http/http-error-codes'
7 import { UserRole } from '../../../shared/models/users'
8 import { UserRegister } from '../../../shared/models/users/user-register.model'
9 import { toBooleanOrNull, toIntOrNull } from '../../helpers/custom-validators/misc'
10 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
12 isUserAdminFlagsValid,
13 isUserAutoPlayNextVideoValid,
14 isUserAutoPlayVideoValid,
15 isUserBlockedReasonValid,
16 isUserDescriptionValid,
17 isUserDisplayNameValid,
19 isUserNSFWPolicyValid,
21 isUserPasswordValidOrEmpty,
25 isUserVideoQuotaDailyValid,
26 isUserVideoQuotaValid,
27 isUserVideosHistoryEnabledValid
28 } from '../../helpers/custom-validators/users'
29 import { isVideoChannelDisplayNameValid, isVideoChannelUsernameValid } from '../../helpers/custom-validators/video-channels'
30 import { logger } from '../../helpers/logger'
31 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
32 import { Redis } from '../../lib/redis'
33 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../lib/signup'
34 import { ActorModel } from '../../models/actor/actor'
35 import { UserModel } from '../../models/user/user'
36 import { areValidationErrors, doesVideoExist, isValidVideoIdParam } from './shared'
38 const usersListValidator = [
41 .customSanitizer(toBooleanOrNull)
42 .isBoolean().withMessage('Should be a valid boolean banned state'),
44 (req: express.Request, res: express.Response, next: express.NextFunction) => {
45 logger.debug('Checking usersList parameters', { parameters: req.query })
47 if (areValidationErrors(req, res)) return
53 const usersAddValidator = [
54 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
55 body('password').custom(isUserPasswordValidOrEmpty).withMessage('Should have a valid password'),
56 body('email').isEmail().withMessage('Should have a valid email'),
58 body('channelName').optional().custom(isVideoChannelUsernameValid).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'),
64 .customSanitizer(toIntOrNull)
65 .custom(isUserRoleValid).withMessage('Should have a valid role'),
66 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
68 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
69 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
71 if (areValidationErrors(req, res)) return
72 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
74 const authUser = res.locals.oauth.token.User
75 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
77 status: HttpStatusCode.FORBIDDEN_403,
78 message: 'You can only create users (and not administrators or moderators)'
82 if (req.body.channelName) {
83 if (req.body.channelName === req.body.username) {
84 return res.fail({ message: 'Channel name cannot be the same as user username.' })
87 const existing = await ActorModel.loadLocalByName(req.body.channelName)
90 status: HttpStatusCode.CONFLICT_409,
91 message: `Channel with name ${req.body.channelName} already exists.`
100 const usersRegisterValidator = [
101 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
102 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
103 body('email').isEmail().withMessage('Should have a valid email'),
106 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
110 .custom(isVideoChannelUsernameValid).withMessage('Should have a valid channel name'),
111 body('channel.displayName')
113 .custom(isVideoChannelDisplayNameValid).withMessage('Should have a valid display name'),
115 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
116 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
118 if (areValidationErrors(req, res)) return
119 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
121 const body: UserRegister = req.body
123 if (!body.channel.name || !body.channel.displayName) {
124 return res.fail({ message: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
127 if (body.channel.name === body.username) {
128 return res.fail({ message: 'Channel name cannot be the same as user username.' })
131 const existing = await ActorModel.loadLocalByName(body.channel.name)
134 status: HttpStatusCode.CONFLICT_409,
135 message: `Channel with name ${body.channel.name} already exists.`
144 const usersRemoveValidator = [
145 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
147 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
148 logger.debug('Checking usersRemove parameters', { parameters: req.params })
150 if (areValidationErrors(req, res)) return
151 if (!await checkUserIdExist(req.params.id, res)) return
153 const user = res.locals.user
154 if (user.username === 'root') {
155 return res.fail({ message: 'Cannot remove the root user' })
162 const usersBlockingValidator = [
163 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
164 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
166 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
167 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
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') {
174 return res.fail({ message: 'Cannot block the root user' })
181 const deleteMeValidator = [
182 (req: express.Request, res: express.Response, next: express.NextFunction) => {
183 const user = res.locals.oauth.token.User
184 if (user.username === 'root') {
185 return res.fail({ message: 'You cannot delete your root account.' })
192 const usersUpdateValidator = [
193 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
195 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
196 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
197 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
198 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
199 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
200 body('pluginAuth').optional(),
203 .customSanitizer(toIntOrNull)
204 .custom(isUserRoleValid).withMessage('Should have a valid role'),
205 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
207 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
208 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
210 if (areValidationErrors(req, res)) return
211 if (!await checkUserIdExist(req.params.id, res)) return
213 const user = res.locals.user
214 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
215 return res.fail({ message: 'Cannot change root role.' })
222 const usersUpdateMeValidator = [
225 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
228 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
229 body('currentPassword')
231 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
234 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
237 .isEmail().withMessage('Should have a valid email attribute'),
240 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
241 body('autoPlayVideo')
243 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
244 body('videoLanguages')
246 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
247 body('videosHistoryEnabled')
249 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
252 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
254 body('noInstanceConfigWarningModal')
256 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
257 body('noWelcomeModal')
259 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
260 body('noAccountSetupWarningModal')
262 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noAccountSetupWarningModal boolean'),
264 body('autoPlayNextVideo')
266 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
268 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
269 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
271 const user = res.locals.oauth.token.User
273 if (req.body.password || req.body.email) {
274 if (user.pluginAuth !== null) {
275 return res.fail({ message: 'You cannot update your email or password that is associated with an external auth system.' })
278 if (!req.body.currentPassword) {
279 return res.fail({ message: 'currentPassword parameter is missing.' })
282 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
284 status: HttpStatusCode.UNAUTHORIZED_401,
285 message: 'currentPassword is invalid.'
290 if (areValidationErrors(req, res)) return
296 const usersGetValidator = [
297 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
298 query('withStats').optional().isBoolean().withMessage('Should have a valid stats flag'),
300 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
301 logger.debug('Checking usersGet parameters', { parameters: req.params })
303 if (areValidationErrors(req, res)) return
304 if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
310 const usersVideoRatingValidator = [
311 isValidVideoIdParam('videoId'),
313 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
314 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
316 if (areValidationErrors(req, res)) return
317 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
323 const ensureUserRegistrationAllowed = [
324 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
325 const allowedParams = {
330 const allowedResult = await Hooks.wrapPromiseFun(
333 'filter:api.user.signup.allowed.result'
336 if (allowedResult.allowed === false) {
338 status: HttpStatusCode.FORBIDDEN_403,
339 message: allowedResult.errorMessage || 'User registration is not enabled or user limit is reached.'
347 const ensureUserRegistrationAllowedForIP = [
348 (req: express.Request, res: express.Response, next: express.NextFunction) => {
349 const allowed = isSignupAllowedForCurrentIP(req.ip)
351 if (allowed === false) {
353 status: HttpStatusCode.FORBIDDEN_403,
354 message: 'You are not on a network authorized for registration.'
362 const usersAskResetPasswordValidator = [
363 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
365 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
366 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
368 if (areValidationErrors(req, res)) return
370 const exists = await checkUserEmailExist(req.body.email, res, false)
372 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
373 // Do not leak our emails
374 return res.status(HttpStatusCode.NO_CONTENT_204).end()
381 const usersResetPasswordValidator = [
382 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
383 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
384 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
386 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
387 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
389 if (areValidationErrors(req, res)) return
390 if (!await checkUserIdExist(req.params.id, res)) return
392 const user = res.locals.user
393 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
395 if (redisVerificationString !== req.body.verificationString) {
397 status: HttpStatusCode.FORBIDDEN_403,
398 message: 'Invalid verification string.'
406 const usersAskSendVerifyEmailValidator = [
407 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
409 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
410 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
412 if (areValidationErrors(req, res)) return
413 const exists = await checkUserEmailExist(req.body.email, res, false)
415 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
416 // Do not leak our emails
417 return res.status(HttpStatusCode.NO_CONTENT_204).end()
424 const usersVerifyEmailValidator = [
426 .isInt().not().isEmpty().withMessage('Should have a valid id'),
428 body('verificationString')
429 .not().isEmpty().withMessage('Should have a valid verification string'),
430 body('isPendingEmail')
432 .customSanitizer(toBooleanOrNull),
434 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
435 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
437 if (areValidationErrors(req, res)) return
438 if (!await checkUserIdExist(req.params.id, res)) return
440 const user = res.locals.user
441 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
443 if (redisVerificationString !== req.body.verificationString) {
445 status: HttpStatusCode.FORBIDDEN_403,
446 message: 'Invalid verification string.'
454 const userAutocompleteValidator = [
455 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
458 const ensureAuthUserOwnsAccountValidator = [
459 (req: express.Request, res: express.Response, next: express.NextFunction) => {
460 const user = res.locals.oauth.token.User
462 if (res.locals.account.id !== user.Account.id) {
464 status: HttpStatusCode.FORBIDDEN_403,
465 message: 'Only owner can access ratings list.'
473 const ensureCanManageUser = [
474 (req: express.Request, res: express.Response, next: express.NextFunction) => {
475 const authUser = res.locals.oauth.token.User
476 const onUser = res.locals.user
478 if (authUser.role === UserRole.ADMINISTRATOR) return next()
479 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
482 status: HttpStatusCode.FORBIDDEN_403,
483 message: 'A moderator can only manager users.'
488 // ---------------------------------------------------------------------------
494 usersRegisterValidator,
495 usersBlockingValidator,
496 usersRemoveValidator,
497 usersUpdateValidator,
498 usersUpdateMeValidator,
499 usersVideoRatingValidator,
500 ensureUserRegistrationAllowed,
501 ensureUserRegistrationAllowedForIP,
503 usersAskResetPasswordValidator,
504 usersResetPasswordValidator,
505 usersAskSendVerifyEmailValidator,
506 usersVerifyEmailValidator,
507 userAutocompleteValidator,
508 ensureAuthUserOwnsAccountValidator,
512 // ---------------------------------------------------------------------------
514 function checkUserIdExist (idArg: number | string, res: express.Response, withStats = false) {
515 const id = parseInt(idArg + '', 10)
516 return checkUserExist(() => UserModel.loadByIdWithChannels(id, withStats), res)
519 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
520 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
523 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
524 const user = await UserModel.loadByUsernameOrEmail(username, email)
528 status: HttpStatusCode.CONFLICT_409,
529 message: 'User with this username or email already exists.'
534 const actor = await ActorModel.loadLocalByName(username)
537 status: HttpStatusCode.CONFLICT_409,
538 message: 'Another actor (account/channel) with this name on this instance already exists or has already existed.'
546 async function checkUserExist (finder: () => Promise<MUserDefault>, res: express.Response, abortResponse = true) {
547 const user = await finder()
550 if (abortResponse === true) {
552 status: HttpStatusCode.NOT_FOUND_404,
553 message: 'User not found'
560 res.locals.user = user