1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import { body, param } 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,
20 isUserVideoQuotaDailyValid,
21 isUserVideoQuotaValid,
22 isUserVideosHistoryEnabledValid
23 } from '../../helpers/custom-validators/users'
24 import { logger } from '../../helpers/logger'
25 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
26 import { Redis } from '../../lib/redis'
27 import { UserModel } from '../../models/account/user'
28 import { areValidationErrors } from './utils'
29 import { ActorModel } from '../../models/activitypub/actor'
30 import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor'
31 import { isVideoChannelNameValid } from '../../helpers/custom-validators/video-channels'
32 import { UserRegister } from '../../../shared/models/users/user-register.model'
33 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
34 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
35 import { doesVideoExist } from '../../helpers/middlewares'
36 import { UserRole } from '../../../shared/models/users'
37 import { MUserDefault } from '@server/typings/models'
39 const usersAddValidator = [
40 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
41 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
42 body('email').isEmail().withMessage('Should have a valid email'),
43 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
44 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
46 .customSanitizer(toIntOrNull)
47 .custom(isUserRoleValid).withMessage('Should have a valid role'),
48 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
50 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
51 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
53 if (areValidationErrors(req, res)) return
54 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
56 const authUser = res.locals.oauth.token.User
57 if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
58 return res.status(403)
59 .json({ error: 'You can only create users (and not administrators or moderators)' })
66 const usersRegisterValidator = [
67 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
68 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
69 body('email').isEmail().withMessage('Should have a valid email'),
72 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
76 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
77 body('channel.displayName')
79 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
81 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
82 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
84 if (areValidationErrors(req, res)) return
85 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
87 const body: UserRegister = req.body
89 if (!body.channel.name || !body.channel.displayName) {
90 return res.status(400)
91 .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
94 if (body.channel.name === body.username) {
95 return res.status(400)
96 .json({ error: 'Channel name cannot be the same as user username.' })
99 const existing = await ActorModel.loadLocalByName(body.channel.name)
101 return res.status(409)
102 .json({ error: `Channel with name ${body.channel.name} already exists.` })
110 const usersRemoveValidator = [
111 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
113 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
114 logger.debug('Checking usersRemove parameters', { parameters: req.params })
116 if (areValidationErrors(req, res)) return
117 if (!await checkUserIdExist(req.params.id, res)) return
119 const user = res.locals.user
120 if (user.username === 'root') {
121 return res.status(400)
122 .json({ error: 'Cannot remove the root user' })
129 const usersBlockingValidator = [
130 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
131 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
133 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
134 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
136 if (areValidationErrors(req, res)) return
137 if (!await checkUserIdExist(req.params.id, res)) return
139 const user = res.locals.user
140 if (user.username === 'root') {
141 return res.status(400)
142 .json({ error: 'Cannot block the root user' })
149 const deleteMeValidator = [
150 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
151 const user = res.locals.oauth.token.User
152 if (user.username === 'root') {
153 return res.status(400)
154 .json({ error: 'You cannot delete your root account.' })
162 const usersUpdateValidator = [
163 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
164 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
165 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
166 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
167 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
168 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
171 .customSanitizer(toIntOrNull)
172 .custom(isUserRoleValid).withMessage('Should have a valid role'),
173 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
175 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
176 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
178 if (areValidationErrors(req, res)) return
179 if (!await checkUserIdExist(req.params.id, res)) return
181 const user = res.locals.user
182 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
183 return res.status(400)
184 .json({ error: 'Cannot change root role.' })
191 const usersUpdateMeValidator = [
194 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
197 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
198 body('currentPassword')
200 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
203 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
206 .isEmail().withMessage('Should have a valid email attribute'),
209 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
210 body('autoPlayVideo')
212 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
213 body('videoLanguages')
215 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
216 body('videosHistoryEnabled')
218 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
221 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
222 body('noInstanceConfigWarningModal')
224 .custom(v => isNoInstanceConfigWarningModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
225 body('noWelcomeModal')
227 .custom(v => isNoWelcomeModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
228 body('autoPlayNextVideo')
230 .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
232 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
233 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
235 if (req.body.password || req.body.email) {
236 if (!req.body.currentPassword) {
237 return res.status(400)
238 .json({ error: 'currentPassword parameter is missing.' })
242 const user = res.locals.oauth.token.User
243 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
244 return res.status(401)
245 .json({ error: 'currentPassword is invalid.' })
249 if (areValidationErrors(req, res)) return
255 const usersGetValidator = [
256 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
258 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
259 logger.debug('Checking usersGet parameters', { parameters: req.params })
261 if (areValidationErrors(req, res)) return
262 if (!await checkUserIdExist(req.params.id, res)) return
268 const usersVideoRatingValidator = [
269 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
271 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
272 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
274 if (areValidationErrors(req, res)) return
275 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
281 const ensureUserRegistrationAllowed = [
282 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
283 const allowed = await isSignupAllowed()
284 if (allowed === false) {
285 return res.status(403)
286 .json({ error: 'User registration is not enabled or user limit is reached.' })
293 const ensureUserRegistrationAllowedForIP = [
294 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
295 const allowed = isSignupAllowedForCurrentIP(req.ip)
297 if (allowed === false) {
298 return res.status(403)
299 .json({ error: 'You are not on a network authorized for registration.' })
306 const usersAskResetPasswordValidator = [
307 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
309 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
310 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
312 if (areValidationErrors(req, res)) return
314 const exists = await checkUserEmailExist(req.body.email, res, false)
316 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
317 // Do not leak our emails
318 return res.status(204).end()
325 const usersResetPasswordValidator = [
326 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
327 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
328 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
330 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
331 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
333 if (areValidationErrors(req, res)) return
334 if (!await checkUserIdExist(req.params.id, res)) return
336 const user = res.locals.user
337 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
339 if (redisVerificationString !== req.body.verificationString) {
342 .json({ error: 'Invalid verification string.' })
349 const usersAskSendVerifyEmailValidator = [
350 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
352 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
353 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
355 if (areValidationErrors(req, res)) return
356 const exists = await checkUserEmailExist(req.body.email, res, false)
358 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
359 // Do not leak our emails
360 return res.status(204).end()
367 const usersVerifyEmailValidator = [
369 .isInt().not().isEmpty().withMessage('Should have a valid id'),
371 body('verificationString')
372 .not().isEmpty().withMessage('Should have a valid verification string'),
373 body('isPendingEmail')
375 .customSanitizer(toBooleanOrNull),
377 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
378 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
380 if (areValidationErrors(req, res)) return
381 if (!await checkUserIdExist(req.params.id, res)) return
383 const user = res.locals.user
384 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
386 if (redisVerificationString !== req.body.verificationString) {
389 .json({ error: 'Invalid verification string.' })
396 const userAutocompleteValidator = [
397 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
400 const ensureAuthUserOwnsAccountValidator = [
401 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
402 const user = res.locals.oauth.token.User
404 if (res.locals.account.id !== user.Account.id) {
405 return res.status(403)
406 .json({ error: 'Only owner can access ratings list.' })
413 const ensureCanManageUser = [
414 (req: express.Request, res: express.Response, next: express.NextFunction) => {
415 const authUser = res.locals.oauth.token.User
416 const onUser = res.locals.user
418 if (authUser.role === UserRole.ADMINISTRATOR) return next()
419 if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
421 return res.status(403)
422 .json({ error: 'A moderator can only manager users.' })
426 // ---------------------------------------------------------------------------
431 usersRegisterValidator,
432 usersBlockingValidator,
433 usersRemoveValidator,
434 usersUpdateValidator,
435 usersUpdateMeValidator,
436 usersVideoRatingValidator,
437 ensureUserRegistrationAllowed,
438 ensureUserRegistrationAllowedForIP,
440 usersAskResetPasswordValidator,
441 usersResetPasswordValidator,
442 usersAskSendVerifyEmailValidator,
443 usersVerifyEmailValidator,
444 userAutocompleteValidator,
445 ensureAuthUserOwnsAccountValidator,
449 // ---------------------------------------------------------------------------
451 function checkUserIdExist (id: number, res: express.Response) {
452 return checkUserExist(() => UserModel.loadById(id), res)
455 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
456 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
459 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
460 const user = await UserModel.loadByUsernameOrEmail(username, email)
464 .json({ error: 'User with this username or email already exists.' })
468 const actor = await ActorModel.loadLocalByName(username)
471 .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
478 async function checkUserExist (finder: () => Bluebird<MUserDefault>, res: express.Response, abortResponse = true) {
479 const user = await finder()
482 if (abortResponse === true) {
484 .json({ error: 'User not found' })
490 res.locals.user = user