1 import express from 'express'
2 import { body, param, query } from 'express-validator'
3 import { forceNumber } from '@shared/core-utils'
4 import { HttpStatusCode, UserRight, UserRole } from '@shared/models'
5 import { exists, isBooleanValid, isIdValid, toBooleanOrNull, toIntOrNull } from '../../helpers/custom-validators/misc'
6 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
9 isUserAutoPlayNextVideoValid,
10 isUserAutoPlayVideoValid,
11 isUserBlockedReasonValid,
12 isUserDescriptionValid,
13 isUserDisplayNameValid,
14 isUserEmailPublicValid,
16 isUserNSFWPolicyValid,
17 isUserP2PEnabledValid,
19 isUserPasswordValidOrEmpty,
23 isUserVideoQuotaDailyValid,
24 isUserVideoQuotaValid,
25 isUserVideosHistoryEnabledValid
26 } from '../../helpers/custom-validators/users'
27 import { isVideoChannelUsernameValid } from '../../helpers/custom-validators/video-channels'
28 import { logger } from '../../helpers/logger'
29 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
30 import { Redis } from '../../lib/redis'
31 import { ActorModel } from '../../models/actor/actor'
36 checkUserNameOrEmailDoNotAlreadyExist,
37 doesVideoChannelIdExist,
42 const usersListValidator = [
45 .customSanitizer(toBooleanOrNull)
46 .isBoolean().withMessage('Should be a valid blocked boolean'),
48 (req: express.Request, res: express.Response, next: express.NextFunction) => {
49 if (areValidationErrors(req, res)) return
55 const usersAddValidator = [
57 .custom(isUserUsernameValid)
58 .withMessage('Should have a valid username (lowercase alphanumeric characters)'),
60 .custom(isUserPasswordValidOrEmpty),
66 .custom(isVideoChannelUsernameValid),
70 .custom(isUserVideoQuotaValid),
72 body('videoQuotaDaily')
74 .custom(isUserVideoQuotaDailyValid),
77 .customSanitizer(toIntOrNull)
78 .custom(isUserRoleValid),
82 .custom(isUserAdminFlagsValid),
84 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
85 if (areValidationErrors(req, res, { omitBodyLog: true })) return
86 if (!await checkUserNameOrEmailDoNotAlreadyExist(req.body.username, req.body.email, res)) return
88 const authUser = res.locals.oauth.token.User
89 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
91 status: HttpStatusCode.FORBIDDEN_403,
92 message: 'You can only create users (and not administrators or moderators)'
96 if (req.body.channelName) {
97 if (req.body.channelName === req.body.username) {
98 return res.fail({ message: 'Channel name cannot be the same as user username.' })
101 const existing = await ActorModel.loadLocalByName(req.body.channelName)
104 status: HttpStatusCode.CONFLICT_409,
105 message: `Channel with name ${req.body.channelName} already exists.`
114 const usersRemoveValidator = [
118 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
119 if (areValidationErrors(req, res)) return
120 if (!await checkUserIdExist(req.params.id, res)) return
122 const user = res.locals.user
123 if (user.username === 'root') {
124 return res.fail({ message: 'Cannot remove the root user' })
131 const usersBlockingValidator = [
136 .custom(isUserBlockedReasonValid),
138 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
139 if (areValidationErrors(req, res)) return
140 if (!await checkUserIdExist(req.params.id, res)) return
142 const user = res.locals.user
143 if (user.username === 'root') {
144 return res.fail({ message: 'Cannot block the root user' })
151 const deleteMeValidator = [
152 (req: express.Request, res: express.Response, next: express.NextFunction) => {
153 const user = res.locals.oauth.token.User
154 if (user.username === 'root') {
155 return res.fail({ message: 'You cannot delete your root account.' })
162 const usersUpdateValidator = [
163 param('id').custom(isIdValid),
167 .custom(isUserPasswordValid),
171 body('emailVerified')
176 .custom(isUserVideoQuotaValid),
177 body('videoQuotaDaily')
179 .custom(isUserVideoQuotaDailyValid),
185 .customSanitizer(toIntOrNull)
186 .custom(isUserRoleValid),
189 .custom(isUserAdminFlagsValid),
191 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
192 if (areValidationErrors(req, res, { omitBodyLog: true })) return
193 if (!await checkUserIdExist(req.params.id, res)) return
195 const user = res.locals.user
196 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
197 return res.fail({ message: 'Cannot change root role.' })
204 const usersUpdateMeValidator = [
207 .custom(isUserDisplayNameValid),
210 .custom(isUserDescriptionValid),
211 body('currentPassword')
213 .custom(isUserPasswordValid),
216 .custom(isUserPasswordValid),
219 .custom(isUserEmailPublicValid),
225 .custom(isUserNSFWPolicyValid),
226 body('autoPlayVideo')
228 .custom(isUserAutoPlayVideoValid),
231 .custom(isUserP2PEnabledValid).withMessage('Should have a valid p2p enabled boolean'),
232 body('videoLanguages')
234 .custom(isUserVideoLanguages),
235 body('videosHistoryEnabled')
237 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled boolean'),
240 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)),
242 body('noInstanceConfigWarningModal')
244 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
245 body('noWelcomeModal')
247 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
248 body('noAccountSetupWarningModal')
250 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noAccountSetupWarningModal boolean'),
252 body('autoPlayNextVideo')
254 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
256 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
257 const user = res.locals.oauth.token.User
259 if (req.body.password || req.body.email) {
260 if (user.pluginAuth !== null) {
261 return res.fail({ message: 'You cannot update your email or password that is associated with an external auth system.' })
264 if (!req.body.currentPassword) {
265 return res.fail({ message: 'currentPassword parameter is missing.' })
268 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
270 status: HttpStatusCode.UNAUTHORIZED_401,
271 message: 'currentPassword is invalid.'
276 if (areValidationErrors(req, res, { omitBodyLog: true })) return
282 const usersGetValidator = [
287 .isBoolean().withMessage('Should have a valid withStats boolean'),
289 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
290 if (areValidationErrors(req, res)) return
291 if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
297 const usersVideoRatingValidator = [
298 isValidVideoIdParam('videoId'),
300 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
301 if (areValidationErrors(req, res)) return
302 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
308 const usersVideosValidator = [
311 .customSanitizer(toBooleanOrNull)
312 .custom(isBooleanValid).withMessage('Should have a valid isLive boolean'),
316 .customSanitizer(toIntOrNull)
319 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
320 if (areValidationErrors(req, res)) return
322 if (req.query.channelId && !await doesVideoChannelIdExist(req.query.channelId, res)) return
328 const usersAskResetPasswordValidator = [
332 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
333 if (areValidationErrors(req, res)) return
335 const exists = await checkUserEmailExist(req.body.email, res, false)
337 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
338 // Do not leak our emails
339 return res.status(HttpStatusCode.NO_CONTENT_204).end()
342 if (res.locals.user.pluginAuth) {
344 status: HttpStatusCode.CONFLICT_409,
345 message: 'Cannot recover password of a user that uses a plugin authentication.'
353 const usersResetPasswordValidator = [
356 body('verificationString')
359 .custom(isUserPasswordValid),
361 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
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.getResetPasswordVerificationString(user.id)
368 if (redisVerificationString !== req.body.verificationString) {
370 status: HttpStatusCode.FORBIDDEN_403,
371 message: 'Invalid verification string.'
379 const usersCheckCurrentPasswordFactory = (targetUserIdGetter: (req: express.Request) => number | string) => {
381 body('currentPassword').optional().custom(exists),
383 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
384 if (areValidationErrors(req, res)) return
386 const user = res.locals.oauth.token.User
387 const isAdminOrModerator = user.role === UserRole.ADMINISTRATOR || user.role === UserRole.MODERATOR
388 const targetUserId = forceNumber(targetUserIdGetter(req))
390 // Admin/moderator action on another user, skip the password check
391 if (isAdminOrModerator && targetUserId !== user.id) {
395 if (!req.body.currentPassword) {
397 status: HttpStatusCode.BAD_REQUEST_400,
398 message: 'currentPassword is missing'
402 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
404 status: HttpStatusCode.FORBIDDEN_403,
405 message: 'currentPassword is invalid.'
414 const userAutocompleteValidator = [
420 const ensureAuthUserOwnsAccountValidator = [
421 (req: express.Request, res: express.Response, next: express.NextFunction) => {
422 const user = res.locals.oauth.token.User
424 if (res.locals.account.id !== user.Account.id) {
426 status: HttpStatusCode.FORBIDDEN_403,
427 message: 'Only owner of this account can access this resource.'
435 const ensureCanManageChannelOrAccount = [
436 (req: express.Request, res: express.Response, next: express.NextFunction) => {
437 const user = res.locals.oauth.token.user
438 const account = res.locals.videoChannel?.Account ?? res.locals.account
439 const isUserOwner = account.userId === user.id
441 if (!isUserOwner && user.hasRight(UserRight.MANAGE_ANY_VIDEO_CHANNEL) === false) {
442 const message = `User ${user.username} does not have right this channel or account.`
445 status: HttpStatusCode.FORBIDDEN_403,
454 const ensureCanModerateUser = [
455 (req: express.Request, res: express.Response, next: express.NextFunction) => {
456 const authUser = res.locals.oauth.token.User
457 const onUser = res.locals.user
459 if (authUser.role === UserRole.ADMINISTRATOR) return next()
460 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
463 status: HttpStatusCode.FORBIDDEN_403,
464 message: 'A moderator can only manage users.'
469 // ---------------------------------------------------------------------------
475 usersBlockingValidator,
476 usersRemoveValidator,
477 usersUpdateValidator,
478 usersUpdateMeValidator,
479 usersVideoRatingValidator,
480 usersCheckCurrentPasswordFactory,
482 usersVideosValidator,
483 usersAskResetPasswordValidator,
484 usersResetPasswordValidator,
485 userAutocompleteValidator,
486 ensureAuthUserOwnsAccountValidator,
487 ensureCanModerateUser,
488 ensureCanManageChannelOrAccount