1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import 'express-validator'
4 import { body, param } from 'express-validator/check'
5 import { omit } from 'lodash'
6 import { isIdOrUUIDValid } from '../../helpers/custom-validators/misc'
9 isUserAutoPlayVideoValid,
10 isUserBlockedReasonValid,
11 isUserDescriptionValid,
12 isUserDisplayNameValid,
13 isUserNSFWPolicyValid,
18 isUserVideoQuotaDailyValid,
19 isUserVideoQuotaValid,
20 isUserVideosHistoryEnabledValid
21 } from '../../helpers/custom-validators/users'
22 import { logger } from '../../helpers/logger'
23 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
24 import { Redis } from '../../lib/redis'
25 import { UserModel } from '../../models/account/user'
26 import { areValidationErrors } from './utils'
27 import { ActorModel } from '../../models/activitypub/actor'
28 import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor'
29 import { isVideoChannelNameValid } from '../../helpers/custom-validators/video-channels'
30 import { UserRegister } from '../../../shared/models/users/user-register.model'
31 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
32 import { isThemeRegistered } from '../../lib/plugins/theme-utils'
33 import { doesVideoExist } from '../../helpers/middlewares'
35 const usersAddValidator = [
36 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
37 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
38 body('email').isEmail().withMessage('Should have a valid email'),
39 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
40 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
41 body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
42 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
44 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
45 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
47 if (areValidationErrors(req, res)) return
48 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
54 const usersRegisterValidator = [
55 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
56 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
57 body('email').isEmail().withMessage('Should have a valid email'),
60 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
64 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
65 body('channel.displayName')
67 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
69 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
70 logger.debug('Checking usersRegister 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 body: UserRegister = req.body
77 if (!body.channel.name || !body.channel.displayName) {
78 return res.status(400)
79 .send({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
83 if (body.channel.name === body.username) {
84 return res.status(400)
85 .send({ error: 'Channel name cannot be the same than user username.' })
89 const existing = await ActorModel.loadLocalByName(body.channel.name)
91 return res.status(409)
92 .send({ error: `Channel with name ${body.channel.name} already exists.` })
101 const usersRemoveValidator = [
102 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
104 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
105 logger.debug('Checking usersRemove parameters', { parameters: req.params })
107 if (areValidationErrors(req, res)) return
108 if (!await checkUserIdExist(req.params.id, res)) return
110 const user = res.locals.user
111 if (user.username === 'root') {
112 return res.status(400)
113 .send({ error: 'Cannot remove the root user' })
121 const usersBlockingValidator = [
122 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
123 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
125 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
126 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
128 if (areValidationErrors(req, res)) return
129 if (!await checkUserIdExist(req.params.id, res)) return
131 const user = res.locals.user
132 if (user.username === 'root') {
133 return res.status(400)
134 .send({ error: 'Cannot block the root user' })
142 const deleteMeValidator = [
143 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
144 const user = res.locals.oauth.token.User
145 if (user.username === 'root') {
146 return res.status(400)
147 .send({ error: 'You cannot delete your root account.' })
155 const usersUpdateValidator = [
156 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
157 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
158 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
159 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
160 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
161 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
162 body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
163 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
165 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
166 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
168 if (areValidationErrors(req, res)) return
169 if (!await checkUserIdExist(req.params.id, res)) return
171 const user = res.locals.user
172 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
173 return res.status(400)
174 .send({ error: 'Cannot change root role.' })
182 const usersUpdateMeValidator = [
185 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
188 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
189 body('currentPassword')
191 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
194 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
197 .isEmail().withMessage('Should have a valid email attribute'),
200 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
201 body('autoPlayVideo')
203 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
204 body('videoLanguages')
206 .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
207 body('videosHistoryEnabled')
209 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
212 .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
214 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
215 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
217 if (req.body.password || req.body.email) {
218 if (!req.body.currentPassword) {
219 return res.status(400)
220 .send({ error: 'currentPassword parameter is missing.' })
224 const user = res.locals.oauth.token.User
225 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
226 return res.status(401)
227 .send({ error: 'currentPassword is invalid.' })
232 if (areValidationErrors(req, res)) return
238 const usersGetValidator = [
239 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
241 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
242 logger.debug('Checking usersGet parameters', { parameters: req.params })
244 if (areValidationErrors(req, res)) return
245 if (!await checkUserIdExist(req.params.id, res)) return
251 const usersVideoRatingValidator = [
252 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
254 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
255 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
257 if (areValidationErrors(req, res)) return
258 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
264 const ensureUserRegistrationAllowed = [
265 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
266 const allowed = await isSignupAllowed()
267 if (allowed === false) {
268 return res.status(403)
269 .send({ error: 'User registration is not enabled or user limit is reached.' })
277 const ensureUserRegistrationAllowedForIP = [
278 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
279 const allowed = isSignupAllowedForCurrentIP(req.ip)
281 if (allowed === false) {
282 return res.status(403)
283 .send({ error: 'You are not on a network authorized for registration.' })
291 const usersAskResetPasswordValidator = [
292 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
294 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
295 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
297 if (areValidationErrors(req, res)) return
299 const exists = await checkUserEmailExist(req.body.email, res, false)
301 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
302 // Do not leak our emails
303 return res.status(204).end()
310 const usersResetPasswordValidator = [
311 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
312 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
313 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
315 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
316 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
318 if (areValidationErrors(req, res)) return
319 if (!await checkUserIdExist(req.params.id, res)) return
321 const user = res.locals.user
322 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
324 if (redisVerificationString !== req.body.verificationString) {
327 .send({ error: 'Invalid verification string.' })
335 const usersAskSendVerifyEmailValidator = [
336 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
338 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
339 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
341 if (areValidationErrors(req, res)) return
342 const exists = await checkUserEmailExist(req.body.email, res, false)
344 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
345 // Do not leak our emails
346 return res.status(204).end()
353 const usersVerifyEmailValidator = [
355 .isInt().not().isEmpty().withMessage('Should have a valid id'),
357 body('verificationString')
358 .not().isEmpty().withMessage('Should have a valid verification string'),
359 body('isPendingEmail')
363 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
364 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
366 if (areValidationErrors(req, res)) return
367 if (!await checkUserIdExist(req.params.id, res)) return
369 const user = res.locals.user
370 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
372 if (redisVerificationString !== req.body.verificationString) {
375 .send({ error: 'Invalid verification string.' })
383 const userAutocompleteValidator = [
384 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
387 const ensureAuthUserOwnsAccountValidator = [
388 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
389 const user = res.locals.oauth.token.User
391 if (res.locals.account.id !== user.Account.id) {
392 return res.status(403)
393 .send({ error: 'Only owner can access ratings list.' })
401 // ---------------------------------------------------------------------------
406 usersRegisterValidator,
407 usersBlockingValidator,
408 usersRemoveValidator,
409 usersUpdateValidator,
410 usersUpdateMeValidator,
411 usersVideoRatingValidator,
412 ensureUserRegistrationAllowed,
413 ensureUserRegistrationAllowedForIP,
415 usersAskResetPasswordValidator,
416 usersResetPasswordValidator,
417 usersAskSendVerifyEmailValidator,
418 usersVerifyEmailValidator,
419 userAutocompleteValidator,
420 ensureAuthUserOwnsAccountValidator
423 // ---------------------------------------------------------------------------
425 function checkUserIdExist (id: number, res: express.Response) {
426 return checkUserExist(() => UserModel.loadById(id), res)
429 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
430 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
433 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
434 const user = await UserModel.loadByUsernameOrEmail(username, email)
438 .send({ error: 'User with this username or email already exists.' })
443 const actor = await ActorModel.loadLocalByName(username)
446 .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
454 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
455 const user = await finder()
458 if (abortResponse === true) {
460 .send({ error: 'User not found' })
467 res.locals.user = user