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,
15 isUserNSFWPolicyValid,
16 isUserP2PEnabledValid,
18 isUserPasswordValidOrEmpty,
22 isUserVideoQuotaDailyValid,
23 isUserVideoQuotaValid,
24 isUserVideosHistoryEnabledValid
25 } from '../../helpers/custom-validators/users'
26 import { isVideoChannelUsernameValid } from '../../helpers/custom-validators/video-channels'
27 import { logger } from '../../helpers/logger'
28 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
29 import { Redis } from '../../lib/redis'
30 import { ActorModel } from '../../models/actor/actor'
35 checkUserNameOrEmailDoNotAlreadyExist,
36 doesVideoChannelIdExist,
41 const usersListValidator = [
44 .customSanitizer(toBooleanOrNull)
45 .isBoolean().withMessage('Should be a valid blocked boolean'),
47 (req: express.Request, res: express.Response, next: express.NextFunction) => {
48 if (areValidationErrors(req, res)) return
54 const usersAddValidator = [
56 .custom(isUserUsernameValid)
57 .withMessage('Should have a valid username (lowercase alphanumeric characters)'),
59 .custom(isUserPasswordValidOrEmpty),
65 .custom(isVideoChannelUsernameValid),
69 .custom(isUserVideoQuotaValid),
71 body('videoQuotaDaily')
73 .custom(isUserVideoQuotaDailyValid),
76 .customSanitizer(toIntOrNull)
77 .custom(isUserRoleValid),
81 .custom(isUserAdminFlagsValid),
83 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
84 if (areValidationErrors(req, res, { omitBodyLog: true })) return
85 if (!await checkUserNameOrEmailDoNotAlreadyExist(req.body.username, req.body.email, res)) return
87 const authUser = res.locals.oauth.token.User
88 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
90 status: HttpStatusCode.FORBIDDEN_403,
91 message: 'You can only create users (and not administrators or moderators)'
95 if (req.body.channelName) {
96 if (req.body.channelName === req.body.username) {
97 return res.fail({ message: 'Channel name cannot be the same as user username.' })
100 const existing = await ActorModel.loadLocalByName(req.body.channelName)
103 status: HttpStatusCode.CONFLICT_409,
104 message: `Channel with name ${req.body.channelName} already exists.`
113 const usersRemoveValidator = [
117 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
118 if (areValidationErrors(req, res)) return
119 if (!await checkUserIdExist(req.params.id, res)) return
121 const user = res.locals.user
122 if (user.username === 'root') {
123 return res.fail({ message: 'Cannot remove the root user' })
130 const usersBlockingValidator = [
135 .custom(isUserBlockedReasonValid),
137 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
138 if (areValidationErrors(req, res)) return
139 if (!await checkUserIdExist(req.params.id, res)) return
141 const user = res.locals.user
142 if (user.username === 'root') {
143 return res.fail({ message: 'Cannot block the root user' })
150 const deleteMeValidator = [
151 (req: express.Request, res: express.Response, next: express.NextFunction) => {
152 const user = res.locals.oauth.token.User
153 if (user.username === 'root') {
154 return res.fail({ message: 'You cannot delete your root account.' })
161 const usersUpdateValidator = [
162 param('id').custom(isIdValid),
166 .custom(isUserPasswordValid),
170 body('emailVerified')
175 .custom(isUserVideoQuotaValid),
176 body('videoQuotaDaily')
178 .custom(isUserVideoQuotaDailyValid),
184 .customSanitizer(toIntOrNull)
185 .custom(isUserRoleValid),
188 .custom(isUserAdminFlagsValid),
190 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
191 if (areValidationErrors(req, res, { omitBodyLog: true })) return
192 if (!await checkUserIdExist(req.params.id, res)) return
194 const user = res.locals.user
195 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
196 return res.fail({ message: 'Cannot change root role.' })
203 const usersUpdateMeValidator = [
206 .custom(isUserDisplayNameValid),
209 .custom(isUserDescriptionValid),
210 body('currentPassword')
212 .custom(isUserPasswordValid),
215 .custom(isUserPasswordValid),
221 .custom(isUserNSFWPolicyValid),
222 body('autoPlayVideo')
224 .custom(isUserAutoPlayVideoValid),
227 .custom(isUserP2PEnabledValid).withMessage('Should have a valid p2p enabled boolean'),
228 body('videoLanguages')
230 .custom(isUserVideoLanguages),
231 body('videosHistoryEnabled')
233 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled boolean'),
236 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)),
238 body('noInstanceConfigWarningModal')
240 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
241 body('noWelcomeModal')
243 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
244 body('noAccountSetupWarningModal')
246 .custom(v => isUserNoModal(v)).withMessage('Should have a valid noAccountSetupWarningModal boolean'),
248 body('autoPlayNextVideo')
250 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
252 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
253 const user = res.locals.oauth.token.User
255 if (req.body.password || req.body.email) {
256 if (user.pluginAuth !== null) {
257 return res.fail({ message: 'You cannot update your email or password that is associated with an external auth system.' })
260 if (!req.body.currentPassword) {
261 return res.fail({ message: 'currentPassword parameter is missing.' })
264 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
266 status: HttpStatusCode.UNAUTHORIZED_401,
267 message: 'currentPassword is invalid.'
272 if (areValidationErrors(req, res, { omitBodyLog: true })) return
278 const usersGetValidator = [
283 .isBoolean().withMessage('Should have a valid withStats boolean'),
285 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
286 if (areValidationErrors(req, res)) return
287 if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
293 const usersVideoRatingValidator = [
294 isValidVideoIdParam('videoId'),
296 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
297 if (areValidationErrors(req, res)) return
298 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
304 const usersVideosValidator = [
307 .customSanitizer(toBooleanOrNull)
308 .custom(isBooleanValid).withMessage('Should have a valid isLive boolean'),
312 .customSanitizer(toIntOrNull)
315 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
316 if (areValidationErrors(req, res)) return
318 if (req.query.channelId && !await doesVideoChannelIdExist(req.query.channelId, res)) return
324 const usersAskResetPasswordValidator = [
328 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
329 if (areValidationErrors(req, res)) return
331 const exists = await checkUserEmailExist(req.body.email, res, false)
333 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
334 // Do not leak our emails
335 return res.status(HttpStatusCode.NO_CONTENT_204).end()
338 if (res.locals.user.pluginAuth) {
340 status: HttpStatusCode.CONFLICT_409,
341 message: 'Cannot recover password of a user that uses a plugin authentication.'
349 const usersResetPasswordValidator = [
352 body('verificationString')
355 .custom(isUserPasswordValid),
357 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
358 if (areValidationErrors(req, res)) return
359 if (!await checkUserIdExist(req.params.id, res)) return
361 const user = res.locals.user
362 const redisVerificationString = await Redis.Instance.getResetPasswordVerificationString(user.id)
364 if (redisVerificationString !== req.body.verificationString) {
366 status: HttpStatusCode.FORBIDDEN_403,
367 message: 'Invalid verification string.'
375 const usersCheckCurrentPasswordFactory = (targetUserIdGetter: (req: express.Request) => number | string) => {
377 body('currentPassword').optional().custom(exists),
379 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
380 if (areValidationErrors(req, res)) return
382 const user = res.locals.oauth.token.User
383 const isAdminOrModerator = user.role === UserRole.ADMINISTRATOR || user.role === UserRole.MODERATOR
384 const targetUserId = forceNumber(targetUserIdGetter(req))
386 // Admin/moderator action on another user, skip the password check
387 if (isAdminOrModerator && targetUserId !== user.id) {
391 if (!req.body.currentPassword) {
393 status: HttpStatusCode.BAD_REQUEST_400,
394 message: 'currentPassword is missing'
398 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
400 status: HttpStatusCode.FORBIDDEN_403,
401 message: 'currentPassword is invalid.'
410 const userAutocompleteValidator = [
416 const ensureAuthUserOwnsAccountValidator = [
417 (req: express.Request, res: express.Response, next: express.NextFunction) => {
418 const user = res.locals.oauth.token.User
420 if (res.locals.account.id !== user.Account.id) {
422 status: HttpStatusCode.FORBIDDEN_403,
423 message: 'Only owner of this account can access this resource.'
431 const ensureCanManageChannelOrAccount = [
432 (req: express.Request, res: express.Response, next: express.NextFunction) => {
433 const user = res.locals.oauth.token.user
434 const account = res.locals.videoChannel?.Account ?? res.locals.account
435 const isUserOwner = account.userId === user.id
437 if (!isUserOwner && user.hasRight(UserRight.MANAGE_ANY_VIDEO_CHANNEL) === false) {
438 const message = `User ${user.username} does not have right this channel or account.`
441 status: HttpStatusCode.FORBIDDEN_403,
450 const ensureCanModerateUser = [
451 (req: express.Request, res: express.Response, next: express.NextFunction) => {
452 const authUser = res.locals.oauth.token.User
453 const onUser = res.locals.user
455 if (authUser.role === UserRole.ADMINISTRATOR) return next()
456 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
459 status: HttpStatusCode.FORBIDDEN_403,
460 message: 'A moderator can only manage users.'
465 // ---------------------------------------------------------------------------
471 usersBlockingValidator,
472 usersRemoveValidator,
473 usersUpdateValidator,
474 usersUpdateMeValidator,
475 usersVideoRatingValidator,
476 usersCheckCurrentPasswordFactory,
478 usersVideosValidator,
479 usersAskResetPasswordValidator,
480 usersResetPasswordValidator,
481 userAutocompleteValidator,
482 ensureAuthUserOwnsAccountValidator,
483 ensureCanModerateUser,
484 ensureCanManageChannelOrAccount