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 isNoInstanceConfigWarningModal,
14 isUserAdminFlagsValid,
15 isUserAutoPlayNextVideoValid,
16 isUserAutoPlayVideoValid,
17 isUserBlockedReasonValid,
18 isUserDescriptionValid,
19 isUserDisplayNameValid,
20 isUserNSFWPolicyValid,
22 isUserPasswordValidOrEmpty,
26 isUserVideoQuotaDailyValid,
27 isUserVideoQuotaValid,
28 isUserVideosHistoryEnabledValid
29 } from '../../helpers/custom-validators/users'
30 import { isVideoChannelDisplayNameValid, isVideoChannelUsernameValid } from '../../helpers/custom-validators/video-channels'
31 import { logger } from '../../helpers/logger'
32 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
33 import { Redis } from '../../lib/redis'
34 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../lib/signup'
35 import { ActorModel } from '../../models/actor/actor'
36 import { UserModel } from '../../models/user/user'
37 import { areValidationErrors, doesVideoExist, isValidVideoIdParam } from './shared'
39 const usersListValidator = [
42 .customSanitizer(toBooleanOrNull)
43 .isBoolean().withMessage('Should be a valid boolean banned state'),
45 (req: express.Request, res: express.Response, next: express.NextFunction) => {
46 logger.debug('Checking usersList parameters', { parameters: req.query })
48 if (areValidationErrors(req, res)) return
54 const usersAddValidator = [
55 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
56 body('password').custom(isUserPasswordValidOrEmpty).withMessage('Should have a valid password'),
57 body('email').isEmail().withMessage('Should have a valid email'),
59 body('channelName').optional().custom(isVideoChannelUsernameValid).withMessage('Should have a valid channel name'),
61 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
62 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
65 .customSanitizer(toIntOrNull)
66 .custom(isUserRoleValid).withMessage('Should have a valid role'),
67 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
69 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
70 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
72 if (areValidationErrors(req, res)) return
73 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
75 const authUser = res.locals.oauth.token.User
76 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
78 status: HttpStatusCode.FORBIDDEN_403,
79 message: 'You can only create users (and not administrators or moderators)'
83 if (req.body.channelName) {
84 if (req.body.channelName === req.body.username) {
85 return res.fail({ message: 'Channel name cannot be the same as user username.' })
88 const existing = await ActorModel.loadLocalByName(req.body.channelName)
91 status: HttpStatusCode.CONFLICT_409,
92 message: `Channel with name ${req.body.channelName} already exists.`
101 const usersRegisterValidator = [
102 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
103 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
104 body('email').isEmail().withMessage('Should have a valid email'),
107 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
111 .custom(isVideoChannelUsernameValid).withMessage('Should have a valid channel name'),
112 body('channel.displayName')
114 .custom(isVideoChannelDisplayNameValid).withMessage('Should have a valid display name'),
116 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
117 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
119 if (areValidationErrors(req, res)) return
120 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
122 const body: UserRegister = req.body
124 if (!body.channel.name || !body.channel.displayName) {
125 return res.fail({ message: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
128 if (body.channel.name === body.username) {
129 return res.fail({ message: 'Channel name cannot be the same as user username.' })
132 const existing = await ActorModel.loadLocalByName(body.channel.name)
135 status: HttpStatusCode.CONFLICT_409,
136 message: `Channel with name ${body.channel.name} already exists.`
145 const usersRemoveValidator = [
146 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
148 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
149 logger.debug('Checking usersRemove parameters', { parameters: req.params })
151 if (areValidationErrors(req, res)) return
152 if (!await checkUserIdExist(req.params.id, res)) return
154 const user = res.locals.user
155 if (user.username === 'root') {
156 return res.fail({ message: 'Cannot remove the root user' })
163 const usersBlockingValidator = [
164 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
165 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
167 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
168 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
170 if (areValidationErrors(req, res)) return
171 if (!await checkUserIdExist(req.params.id, res)) return
173 const user = res.locals.user
174 if (user.username === 'root') {
175 return res.fail({ message: 'Cannot block the root user' })
182 const deleteMeValidator = [
183 (req: express.Request, res: express.Response, next: express.NextFunction) => {
184 const user = res.locals.oauth.token.User
185 if (user.username === 'root') {
186 return res.fail({ message: 'You cannot delete your root account.' })
193 const usersUpdateValidator = [
194 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
196 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
197 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
198 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
199 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
200 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
201 body('pluginAuth').optional(),
204 .customSanitizer(toIntOrNull)
205 .custom(isUserRoleValid).withMessage('Should have a valid role'),
206 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
208 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
209 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
211 if (areValidationErrors(req, res)) return
212 if (!await checkUserIdExist(req.params.id, res)) return
214 const user = res.locals.user
215 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
216 return res.fail({ message: 'Cannot change root role.' })
223 const usersUpdateMeValidator = [
226 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
229 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
230 body('currentPassword')
232 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
235 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
238 .isEmail().withMessage('Should have a valid email attribute'),
241 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
242 body('autoPlayVideo')
244 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
245 body('videoLanguages')
247 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
248 body('videosHistoryEnabled')
250 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
253 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
254 body('noInstanceConfigWarningModal')
256 .custom(v => isNoInstanceConfigWarningModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
257 body('noWelcomeModal')
259 .custom(v => isNoWelcomeModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
260 body('autoPlayNextVideo')
262 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
264 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
265 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
267 const user = res.locals.oauth.token.User
269 if (req.body.password || req.body.email) {
270 if (user.pluginAuth !== null) {
271 return res.fail({ message: 'You cannot update your email or password that is associated with an external auth system.' })
274 if (!req.body.currentPassword) {
275 return res.fail({ message: 'currentPassword parameter is missing.' })
278 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
280 status: HttpStatusCode.UNAUTHORIZED_401,
281 message: 'currentPassword is invalid.'
286 if (areValidationErrors(req, res)) return
292 const usersGetValidator = [
293 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
294 query('withStats').optional().isBoolean().withMessage('Should have a valid stats flag'),
296 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
297 logger.debug('Checking usersGet parameters', { parameters: req.params })
299 if (areValidationErrors(req, res)) return
300 if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
306 const usersVideoRatingValidator = [
307 isValidVideoIdParam('videoId'),
309 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
310 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
312 if (areValidationErrors(req, res)) return
313 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
319 const ensureUserRegistrationAllowed = [
320 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
321 const allowedParams = {
326 const allowedResult = await Hooks.wrapPromiseFun(
329 'filter:api.user.signup.allowed.result'
332 if (allowedResult.allowed === false) {
334 status: HttpStatusCode.FORBIDDEN_403,
335 message: allowedResult.errorMessage || 'User registration is not enabled or user limit is reached.'
343 const ensureUserRegistrationAllowedForIP = [
344 (req: express.Request, res: express.Response, next: express.NextFunction) => {
345 const allowed = isSignupAllowedForCurrentIP(req.ip)
347 if (allowed === false) {
349 status: HttpStatusCode.FORBIDDEN_403,
350 message: 'You are not on a network authorized for registration.'
358 const usersAskResetPasswordValidator = [
359 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
361 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
362 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
364 if (areValidationErrors(req, res)) return
366 const exists = await checkUserEmailExist(req.body.email, res, false)
368 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
369 // Do not leak our emails
370 return res.status(HttpStatusCode.NO_CONTENT_204).end()
377 const usersResetPasswordValidator = [
378 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
379 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
380 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
382 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
383 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
385 if (areValidationErrors(req, res)) return
386 if (!await checkUserIdExist(req.params.id, res)) return
388 const user = res.locals.user
389 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
391 if (redisVerificationString !== req.body.verificationString) {
393 status: HttpStatusCode.FORBIDDEN_403,
394 message: 'Invalid verification string.'
402 const usersAskSendVerifyEmailValidator = [
403 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
405 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
406 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
408 if (areValidationErrors(req, res)) return
409 const exists = await checkUserEmailExist(req.body.email, res, false)
411 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
412 // Do not leak our emails
413 return res.status(HttpStatusCode.NO_CONTENT_204).end()
420 const usersVerifyEmailValidator = [
422 .isInt().not().isEmpty().withMessage('Should have a valid id'),
424 body('verificationString')
425 .not().isEmpty().withMessage('Should have a valid verification string'),
426 body('isPendingEmail')
428 .customSanitizer(toBooleanOrNull),
430 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
431 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
433 if (areValidationErrors(req, res)) return
434 if (!await checkUserIdExist(req.params.id, res)) return
436 const user = res.locals.user
437 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
439 if (redisVerificationString !== req.body.verificationString) {
441 status: HttpStatusCode.FORBIDDEN_403,
442 message: 'Invalid verification string.'
450 const userAutocompleteValidator = [
451 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
454 const ensureAuthUserOwnsAccountValidator = [
455 (req: express.Request, res: express.Response, next: express.NextFunction) => {
456 const user = res.locals.oauth.token.User
458 if (res.locals.account.id !== user.Account.id) {
460 status: HttpStatusCode.FORBIDDEN_403,
461 message: 'Only owner can access ratings list.'
469 const ensureCanManageUser = [
470 (req: express.Request, res: express.Response, next: express.NextFunction) => {
471 const authUser = res.locals.oauth.token.User
472 const onUser = res.locals.user
474 if (authUser.role === UserRole.ADMINISTRATOR) return next()
475 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
478 status: HttpStatusCode.FORBIDDEN_403,
479 message: 'A moderator can only manager users.'
484 // ---------------------------------------------------------------------------
490 usersRegisterValidator,
491 usersBlockingValidator,
492 usersRemoveValidator,
493 usersUpdateValidator,
494 usersUpdateMeValidator,
495 usersVideoRatingValidator,
496 ensureUserRegistrationAllowed,
497 ensureUserRegistrationAllowedForIP,
499 usersAskResetPasswordValidator,
500 usersResetPasswordValidator,
501 usersAskSendVerifyEmailValidator,
502 usersVerifyEmailValidator,
503 userAutocompleteValidator,
504 ensureAuthUserOwnsAccountValidator,
508 // ---------------------------------------------------------------------------
510 function checkUserIdExist (idArg: number | string, res: express.Response, withStats = false) {
511 const id = parseInt(idArg + '', 10)
512 return checkUserExist(() => UserModel.loadByIdWithChannels(id, withStats), res)
515 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
516 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
519 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
520 const user = await UserModel.loadByUsernameOrEmail(username, email)
524 status: HttpStatusCode.CONFLICT_409,
525 message: 'User with this username or email already exists.'
530 const actor = await ActorModel.loadLocalByName(username)
533 status: HttpStatusCode.CONFLICT_409,
534 message: 'Another actor (account/channel) with this name on this instance already exists or has already existed.'
542 async function checkUserExist (finder: () => Promise<MUserDefault>, res: express.Response, abortResponse = true) {
543 const user = await finder()
546 if (abortResponse === true) {
548 status: HttpStatusCode.NOT_FOUND_404,
549 message: 'User not found'
556 res.locals.user = user