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,
17 isUserVideoQuotaDailyValid,
18 isUserVideoQuotaValid,
19 isUserVideosHistoryEnabledValid
20 } from '../../helpers/custom-validators/users'
21 import { doesVideoExist } from '../../helpers/custom-validators/videos'
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'
32 const usersAddValidator = [
33 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
34 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
35 body('email').isEmail().withMessage('Should have a valid email'),
36 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
37 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
38 body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
39 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
41 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
42 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
44 if (areValidationErrors(req, res)) return
45 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
51 const usersRegisterValidator = [
52 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
53 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
54 body('email').isEmail().withMessage('Should have a valid email'),
57 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
61 .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
62 body('channel.displayName')
64 .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
66 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
67 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
69 if (areValidationErrors(req, res)) return
70 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
72 const body: UserRegister = req.body
74 if (!body.channel.name || !body.channel.displayName) {
75 return res.status(400)
76 .send({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
80 if (body.channel.name === body.username) {
81 return res.status(400)
82 .send({ error: 'Channel name cannot be the same than user username.' })
86 const existing = await ActorModel.loadLocalByName(body.channel.name)
88 return res.status(409)
89 .send({ error: `Channel with name ${body.channel.name} already exists.` })
98 const usersRemoveValidator = [
99 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
101 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
102 logger.debug('Checking usersRemove parameters', { parameters: req.params })
104 if (areValidationErrors(req, res)) return
105 if (!await checkUserIdExist(req.params.id, res)) return
107 const user = res.locals.user
108 if (user.username === 'root') {
109 return res.status(400)
110 .send({ error: 'Cannot remove the root user' })
118 const usersBlockingValidator = [
119 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
120 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
122 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
123 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
125 if (areValidationErrors(req, res)) return
126 if (!await checkUserIdExist(req.params.id, res)) return
128 const user = res.locals.user
129 if (user.username === 'root') {
130 return res.status(400)
131 .send({ error: 'Cannot block the root user' })
139 const deleteMeValidator = [
140 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
141 const user = res.locals.oauth.token.User
142 if (user.username === 'root') {
143 return res.status(400)
144 .send({ error: 'You cannot delete your root account.' })
152 const usersUpdateValidator = [
153 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
154 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
155 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
156 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
157 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
158 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
159 body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
160 body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
162 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
163 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
165 if (areValidationErrors(req, res)) return
166 if (!await checkUserIdExist(req.params.id, res)) return
168 const user = res.locals.user
169 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
170 return res.status(400)
171 .send({ error: 'Cannot change root role.' })
179 const usersUpdateMeValidator = [
182 .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
185 .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
186 body('currentPassword')
188 .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
191 .custom(isUserPasswordValid).withMessage('Should have a valid password'),
194 .isEmail().withMessage('Should have a valid email attribute'),
197 .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
198 body('autoPlayVideo')
200 .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
201 body('videosHistoryEnabled')
203 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
205 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
206 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
208 if (req.body.password) {
209 if (!req.body.currentPassword) {
210 return res.status(400)
211 .send({ error: 'currentPassword parameter is missing.' })
215 const user = res.locals.oauth.token.User
216 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
217 return res.status(401)
218 .send({ error: 'currentPassword is invalid.' })
223 if (areValidationErrors(req, res)) return
229 const usersGetValidator = [
230 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
232 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
233 logger.debug('Checking usersGet parameters', { parameters: req.params })
235 if (areValidationErrors(req, res)) return
236 if (!await checkUserIdExist(req.params.id, res)) return
242 const usersVideoRatingValidator = [
243 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
245 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
246 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
248 if (areValidationErrors(req, res)) return
249 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
255 const ensureUserRegistrationAllowed = [
256 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
257 const allowed = await isSignupAllowed()
258 if (allowed === false) {
259 return res.status(403)
260 .send({ error: 'User registration is not enabled or user limit is reached.' })
268 const ensureUserRegistrationAllowedForIP = [
269 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
270 const allowed = isSignupAllowedForCurrentIP(req.ip)
272 if (allowed === false) {
273 return res.status(403)
274 .send({ error: 'You are not on a network authorized for registration.' })
282 const usersAskResetPasswordValidator = [
283 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
285 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
286 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
288 if (areValidationErrors(req, res)) return
290 const exists = await checkUserEmailExist(req.body.email, res, false)
292 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
293 // Do not leak our emails
294 return res.status(204).end()
301 const usersResetPasswordValidator = [
302 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
303 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
304 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
306 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
307 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
309 if (areValidationErrors(req, res)) return
310 if (!await checkUserIdExist(req.params.id, res)) return
312 const user = res.locals.user
313 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
315 if (redisVerificationString !== req.body.verificationString) {
318 .send({ error: 'Invalid verification string.' })
326 const usersAskSendVerifyEmailValidator = [
327 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
329 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
330 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
332 if (areValidationErrors(req, res)) return
333 const exists = await checkUserEmailExist(req.body.email, res, false)
335 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
336 // Do not leak our emails
337 return res.status(204).end()
344 const usersVerifyEmailValidator = [
346 .isInt().not().isEmpty().withMessage('Should have a valid id'),
348 body('verificationString')
349 .not().isEmpty().withMessage('Should have a valid verification string'),
350 body('isPendingEmail')
354 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
355 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
357 if (areValidationErrors(req, res)) return
358 if (!await checkUserIdExist(req.params.id, res)) return
360 const user = res.locals.user
361 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
363 if (redisVerificationString !== req.body.verificationString) {
366 .send({ error: 'Invalid verification string.' })
374 const userAutocompleteValidator = [
375 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
378 const ensureAuthUserOwnsAccountValidator = [
379 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
380 const user = res.locals.oauth.token.User
382 if (res.locals.account.id !== user.Account.id) {
383 return res.status(403)
384 .send({ error: 'Only owner can access ratings list.' })
392 // ---------------------------------------------------------------------------
397 usersRegisterValidator,
398 usersBlockingValidator,
399 usersRemoveValidator,
400 usersUpdateValidator,
401 usersUpdateMeValidator,
402 usersVideoRatingValidator,
403 ensureUserRegistrationAllowed,
404 ensureUserRegistrationAllowedForIP,
406 usersAskResetPasswordValidator,
407 usersResetPasswordValidator,
408 usersAskSendVerifyEmailValidator,
409 usersVerifyEmailValidator,
410 userAutocompleteValidator,
411 ensureAuthUserOwnsAccountValidator
414 // ---------------------------------------------------------------------------
416 function checkUserIdExist (id: number, res: express.Response) {
417 return checkUserExist(() => UserModel.loadById(id), res)
420 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
421 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
424 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
425 const user = await UserModel.loadByUsernameOrEmail(username, email)
429 .send({ error: 'User with this username or email already exists.' })
434 const actor = await ActorModel.loadLocalByName(username)
437 .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
445 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
446 const user = await finder()
449 if (abortResponse === true) {
451 .send({ error: 'User not found' })
458 res.locals.user = user