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'
8 isUserAutoPlayVideoValid,
9 isUserBlockedReasonValid,
10 isUserDescriptionValid,
11 isUserDisplayNameValid,
12 isUserNSFWPolicyValid,
17 isUserVideoQuotaDailyValid,
18 isUserVideoQuotaValid,
19 isUserVideosHistoryEnabledValid
20 } from '../../helpers/custom-validators/users'
21 import { logger } from '../../helpers/logger'
22 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
23 import { Redis } from '../../lib/redis'
24 import { UserModel } from '../../models/account/user'
25 import { areValidationErrors } from './utils'
26 import { ActorModel } from '../../models/activitypub/actor'
27 import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor'
28 import { isVideoChannelNameValid } from '../../helpers/custom-validators/video-channels'
29 import { UserRegister } from '../../../shared/models/users/user-register.model'
30 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
31 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
32 import { doesVideoExist } from '../../helpers/middlewares'
34 const usersAddValidator = [
35 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
36 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
37 body('email').isEmail().withMessage('Should have a valid email'),
38 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
39 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
40 body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
41 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
43 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
44 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
46 if (areValidationErrors(req, res)) return
47 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
53 const usersRegisterValidator = [
54 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
55 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
56 body('email').isEmail().withMessage('Should have a valid email'),
59 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
63 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
64 body('channel.displayName')
66 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
68 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
69 logger.debug('Checking usersRegister 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 body: UserRegister = req.body
76 if (!body.channel.name || !body.channel.displayName) {
77 return res.status(400)
78 .send({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
82 if (body.channel.name === body.username) {
83 return res.status(400)
84 .send({ error: 'Channel name cannot be the same than user username.' })
88 const existing = await ActorModel.loadLocalByName(body.channel.name)
90 return res.status(409)
91 .send({ error: `Channel with name ${body.channel.name} already exists.` })
100 const usersRemoveValidator = [
101 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
103 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
104 logger.debug('Checking usersRemove parameters', { parameters: req.params })
106 if (areValidationErrors(req, res)) return
107 if (!await checkUserIdExist(req.params.id, res)) return
109 const user = res.locals.user
110 if (user.username === 'root') {
111 return res.status(400)
112 .send({ error: 'Cannot remove the root user' })
120 const usersBlockingValidator = [
121 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
122 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
124 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
125 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
127 if (areValidationErrors(req, res)) return
128 if (!await checkUserIdExist(req.params.id, res)) return
130 const user = res.locals.user
131 if (user.username === 'root') {
132 return res.status(400)
133 .send({ error: 'Cannot block the root user' })
141 const deleteMeValidator = [
142 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
143 const user = res.locals.oauth.token.User
144 if (user.username === 'root') {
145 return res.status(400)
146 .send({ error: 'You cannot delete your root account.' })
154 const usersUpdateValidator = [
155 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
156 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
157 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
158 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
159 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
160 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
161 body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
162 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
164 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
165 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
167 if (areValidationErrors(req, res)) return
168 if (!await checkUserIdExist(req.params.id, res)) return
170 const user = res.locals.user
171 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
172 return res.status(400)
173 .send({ error: 'Cannot change root role.' })
181 const usersUpdateMeValidator = [
184 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
187 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
188 body('currentPassword')
190 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
193 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
196 .isEmail().withMessage('Should have a valid email attribute'),
199 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
200 body('autoPlayVideo')
202 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
203 body('videoLanguages')
205 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
206 body('videosHistoryEnabled')
208 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
211 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
213 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
214 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
216 if (req.body.password || req.body.email) {
217 if (!req.body.currentPassword) {
218 return res.status(400)
219 .send({ error: 'currentPassword parameter is missing.' })
223 const user = res.locals.oauth.token.User
224 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
225 return res.status(401)
226 .send({ error: 'currentPassword is invalid.' })
231 if (areValidationErrors(req, res)) return
237 const usersGetValidator = [
238 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
240 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
241 logger.debug('Checking usersGet parameters', { parameters: req.params })
243 if (areValidationErrors(req, res)) return
244 if (!await checkUserIdExist(req.params.id, res)) return
250 const usersVideoRatingValidator = [
251 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
253 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
254 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
256 if (areValidationErrors(req, res)) return
257 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
263 const ensureUserRegistrationAllowed = [
264 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
265 const allowed = await isSignupAllowed()
266 if (allowed === false) {
267 return res.status(403)
268 .send({ error: 'User registration is not enabled or user limit is reached.' })
276 const ensureUserRegistrationAllowedForIP = [
277 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
278 const allowed = isSignupAllowedForCurrentIP(req.ip)
280 if (allowed === false) {
281 return res.status(403)
282 .send({ error: 'You are not on a network authorized for registration.' })
290 const usersAskResetPasswordValidator = [
291 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
293 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
294 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
296 if (areValidationErrors(req, res)) return
298 const exists = await checkUserEmailExist(req.body.email, res, false)
300 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
301 // Do not leak our emails
302 return res.status(204).end()
309 const usersResetPasswordValidator = [
310 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
311 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
312 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
314 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
315 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
317 if (areValidationErrors(req, res)) return
318 if (!await checkUserIdExist(req.params.id, res)) return
320 const user = res.locals.user
321 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
323 if (redisVerificationString !== req.body.verificationString) {
326 .send({ error: 'Invalid verification string.' })
334 const usersAskSendVerifyEmailValidator = [
335 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
337 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
338 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
340 if (areValidationErrors(req, res)) return
341 const exists = await checkUserEmailExist(req.body.email, res, false)
343 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
344 // Do not leak our emails
345 return res.status(204).end()
352 const usersVerifyEmailValidator = [
354 .isInt().not().isEmpty().withMessage('Should have a valid id'),
356 body('verificationString')
357 .not().isEmpty().withMessage('Should have a valid verification string'),
358 body('isPendingEmail')
360 .customSanitizer(toBooleanOrNull),
362 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
363 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
365 if (areValidationErrors(req, res)) return
366 if (!await checkUserIdExist(req.params.id, res)) return
368 const user = res.locals.user
369 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
371 if (redisVerificationString !== req.body.verificationString) {
374 .send({ error: 'Invalid verification string.' })
382 const userAutocompleteValidator = [
383 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
386 const ensureAuthUserOwnsAccountValidator = [
387 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
388 const user = res.locals.oauth.token.User
390 if (res.locals.account.id !== user.Account.id) {
391 return res.status(403)
392 .send({ error: 'Only owner can access ratings list.' })
400 // ---------------------------------------------------------------------------
405 usersRegisterValidator,
406 usersBlockingValidator,
407 usersRemoveValidator,
408 usersUpdateValidator,
409 usersUpdateMeValidator,
410 usersVideoRatingValidator,
411 ensureUserRegistrationAllowed,
412 ensureUserRegistrationAllowedForIP,
414 usersAskResetPasswordValidator,
415 usersResetPasswordValidator,
416 usersAskSendVerifyEmailValidator,
417 usersVerifyEmailValidator,
418 userAutocompleteValidator,
419 ensureAuthUserOwnsAccountValidator
422 // ---------------------------------------------------------------------------
424 function checkUserIdExist (id: number, res: express.Response) {
425 return checkUserExist(() => UserModel.loadById(id), res)
428 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
429 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
432 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
433 const user = await UserModel.loadByUsernameOrEmail(username, email)
437 .send({ error: 'User with this username or email already exists.' })
442 const actor = await ActorModel.loadLocalByName(username)
445 .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
453 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
454 const user = await finder()
457 if (abortResponse === true) {
459 .send({ error: 'User not found' })
466 res.locals.user = user