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'
8 isUserAutoPlayVideoValid,
9 isUserBlockedReasonValid,
10 isUserDescriptionValid,
11 isUserDisplayNameValid,
12 isUserNSFWPolicyValid,
16 isUserVideoQuotaDailyValid,
17 isUserVideoQuotaValid, isUserVideosHistoryEnabledValid
18 } from '../../helpers/custom-validators/users'
19 import { isVideoExist } from '../../helpers/custom-validators/videos'
20 import { logger } from '../../helpers/logger'
21 import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
22 import { Redis } from '../../lib/redis'
23 import { UserModel } from '../../models/account/user'
24 import { areValidationErrors } from './utils'
25 import { ActorModel } from '../../models/activitypub/actor'
27 const usersAddValidator = [
28 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
29 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
30 body('email').isEmail().withMessage('Should have a valid email'),
31 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
32 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
33 body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
35 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
36 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
38 if (areValidationErrors(req, res)) return
39 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
45 const usersRegisterValidator = [
46 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
47 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
48 body('email').isEmail().withMessage('Should have a valid email'),
50 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
51 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
53 if (areValidationErrors(req, res)) return
54 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
60 const usersRemoveValidator = [
61 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
63 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
64 logger.debug('Checking usersRemove parameters', { parameters: req.params })
66 if (areValidationErrors(req, res)) return
67 if (!await checkUserIdExist(req.params.id, res)) return
69 const user = res.locals.user
70 if (user.username === 'root') {
71 return res.status(400)
72 .send({ error: 'Cannot remove the root user' })
80 const usersBlockingValidator = [
81 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
82 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
84 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
85 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
87 if (areValidationErrors(req, res)) return
88 if (!await checkUserIdExist(req.params.id, res)) return
90 const user = res.locals.user
91 if (user.username === 'root') {
92 return res.status(400)
93 .send({ error: 'Cannot block the root user' })
101 const deleteMeValidator = [
102 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
103 const user: UserModel = res.locals.oauth.token.User
104 if (user.username === 'root') {
105 return res.status(400)
106 .send({ error: 'You cannot delete your root account.' })
114 const usersUpdateValidator = [
115 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
116 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
117 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
118 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
119 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
120 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
121 body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
123 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
124 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
126 if (areValidationErrors(req, res)) return
127 if (!await checkUserIdExist(req.params.id, res)) return
129 const user = res.locals.user
130 if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
131 return res.status(400)
132 .send({ error: 'Cannot change root role.' })
140 const usersUpdateMeValidator = [
141 body('displayName').optional().custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
142 body('description').optional().custom(isUserDescriptionValid).withMessage('Should have a valid description'),
143 body('currentPassword').optional().custom(isUserPasswordValid).withMessage('Should have a valid current password'),
144 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
145 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
146 body('nsfwPolicy').optional().custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
147 body('autoPlayVideo').optional().custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
148 body('videosHistoryEnabled')
150 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
152 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
153 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
155 if (req.body.password) {
156 if (!req.body.currentPassword) {
157 return res.status(400)
158 .send({ error: 'currentPassword parameter is missing.' })
162 const user: UserModel = res.locals.oauth.token.User
164 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
165 return res.status(401)
166 .send({ error: 'currentPassword is invalid.' })
171 if (areValidationErrors(req, res)) return
177 const usersGetValidator = [
178 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
180 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
181 logger.debug('Checking usersGet parameters', { parameters: req.params })
183 if (areValidationErrors(req, res)) return
184 if (!await checkUserIdExist(req.params.id, res)) return
190 const usersVideoRatingValidator = [
191 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
193 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
194 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
196 if (areValidationErrors(req, res)) return
197 if (!await isVideoExist(req.params.videoId, res, 'id')) return
203 const ensureUserRegistrationAllowed = [
204 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
205 const allowed = await isSignupAllowed()
206 if (allowed === false) {
207 return res.status(403)
208 .send({ error: 'User registration is not enabled or user limit is reached.' })
216 const ensureUserRegistrationAllowedForIP = [
217 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
218 const allowed = isSignupAllowedForCurrentIP(req.ip)
220 if (allowed === false) {
221 return res.status(403)
222 .send({ error: 'You are not on a network authorized for registration.' })
230 const usersAskResetPasswordValidator = [
231 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
233 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
234 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
236 if (areValidationErrors(req, res)) return
238 const exists = await checkUserEmailExist(req.body.email, res, false)
240 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
241 // Do not leak our emails
242 return res.status(204).end()
249 const usersResetPasswordValidator = [
250 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
251 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
252 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
254 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
255 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
257 if (areValidationErrors(req, res)) return
258 if (!await checkUserIdExist(req.params.id, res)) return
260 const user = res.locals.user as UserModel
261 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
263 if (redisVerificationString !== req.body.verificationString) {
266 .send({ error: 'Invalid verification string.' })
274 const usersAskSendVerifyEmailValidator = [
275 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
277 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
278 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
280 if (areValidationErrors(req, res)) return
281 const exists = await checkUserEmailExist(req.body.email, res, false)
283 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
284 // Do not leak our emails
285 return res.status(204).end()
292 const usersVerifyEmailValidator = [
293 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
294 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
296 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
297 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
299 if (areValidationErrors(req, res)) return
300 if (!await checkUserIdExist(req.params.id, res)) return
302 const user = res.locals.user as UserModel
303 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
305 if (redisVerificationString !== req.body.verificationString) {
308 .send({ error: 'Invalid verification string.' })
316 const userAutocompleteValidator = [
317 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
320 // ---------------------------------------------------------------------------
325 usersRegisterValidator,
326 usersBlockingValidator,
327 usersRemoveValidator,
328 usersUpdateValidator,
329 usersUpdateMeValidator,
330 usersVideoRatingValidator,
331 ensureUserRegistrationAllowed,
332 ensureUserRegistrationAllowedForIP,
334 usersAskResetPasswordValidator,
335 usersResetPasswordValidator,
336 usersAskSendVerifyEmailValidator,
337 usersVerifyEmailValidator,
338 userAutocompleteValidator
341 // ---------------------------------------------------------------------------
343 function checkUserIdExist (id: number, res: express.Response) {
344 return checkUserExist(() => UserModel.loadById(id), res)
347 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
348 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
351 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
352 const user = await UserModel.loadByUsernameOrEmail(username, email)
356 .send({ error: 'User with this username or email already exists.' })
361 const actor = await ActorModel.loadLocalByName(username)
364 .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
372 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
373 const user = await finder()
376 if (abortResponse === true) {
378 .send({ error: 'User not found' })
385 res.locals.user = user