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,
18 isUserVideosHistoryEnabledValid
19 } from '../../helpers/custom-validators/users'
20 import { doesVideoExist } from '../../helpers/custom-validators/videos'
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 { AccountModel } from '../../models/account/account'
26 import { areValidationErrors } from './utils'
27 import { ActorModel } from '../../models/activitypub/actor'
29 const usersAddValidator = [
30 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
31 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
32 body('email').isEmail().withMessage('Should have a valid email'),
33 body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
34 body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
35 body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
37 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
38 logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
40 if (areValidationErrors(req, res)) return
41 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
47 const usersRegisterValidator = [
48 body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
49 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
50 body('email').isEmail().withMessage('Should have a valid email'),
52 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
53 logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
55 if (areValidationErrors(req, res)) return
56 if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
62 const usersRemoveValidator = [
63 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
65 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
66 logger.debug('Checking usersRemove parameters', { parameters: req.params })
68 if (areValidationErrors(req, res)) return
69 if (!await checkUserIdExist(req.params.id, res)) return
71 const user = res.locals.user
72 if (user.username === 'root') {
73 return res.status(400)
74 .send({ error: 'Cannot remove the root user' })
82 const usersBlockingValidator = [
83 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
84 body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
86 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
87 logger.debug('Checking usersBlocking parameters', { parameters: req.params })
89 if (areValidationErrors(req, res)) return
90 if (!await checkUserIdExist(req.params.id, res)) return
92 const user = res.locals.user
93 if (user.username === 'root') {
94 return res.status(400)
95 .send({ error: 'Cannot block the root user' })
103 const deleteMeValidator = [
104 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
105 const user = res.locals.oauth.token.User
106 if (user.username === 'root') {
107 return res.status(400)
108 .send({ error: 'You cannot delete your root account.' })
116 const usersUpdateValidator = [
117 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
118 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
119 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
120 body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
121 body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
122 body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
123 body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
125 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
126 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
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' && req.body.role !== undefined && user.role !== req.body.role) {
133 return res.status(400)
134 .send({ error: 'Cannot change root role.' })
142 const usersUpdateMeValidator = [
143 body('displayName').optional().custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
144 body('description').optional().custom(isUserDescriptionValid).withMessage('Should have a valid description'),
145 body('currentPassword').optional().custom(isUserPasswordValid).withMessage('Should have a valid current password'),
146 body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
147 body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
148 body('nsfwPolicy').optional().custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
149 body('autoPlayVideo').optional().custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
150 body('videosHistoryEnabled')
152 .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
154 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
155 logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
157 if (req.body.password) {
158 if (!req.body.currentPassword) {
159 return res.status(400)
160 .send({ error: 'currentPassword parameter is missing.' })
164 const user = res.locals.oauth.token.User
165 if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
166 return res.status(401)
167 .send({ error: 'currentPassword is invalid.' })
172 if (areValidationErrors(req, res)) return
178 const usersGetValidator = [
179 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
181 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
182 logger.debug('Checking usersGet parameters', { parameters: req.params })
184 if (areValidationErrors(req, res)) return
185 if (!await checkUserIdExist(req.params.id, res)) return
191 const usersVideoRatingValidator = [
192 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
194 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
195 logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
197 if (areValidationErrors(req, res)) return
198 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
204 const ensureUserRegistrationAllowed = [
205 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
206 const allowed = await isSignupAllowed()
207 if (allowed === false) {
208 return res.status(403)
209 .send({ error: 'User registration is not enabled or user limit is reached.' })
217 const ensureUserRegistrationAllowedForIP = [
218 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
219 const allowed = isSignupAllowedForCurrentIP(req.ip)
221 if (allowed === false) {
222 return res.status(403)
223 .send({ error: 'You are not on a network authorized for registration.' })
231 const usersAskResetPasswordValidator = [
232 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
234 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
235 logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
237 if (areValidationErrors(req, res)) return
239 const exists = await checkUserEmailExist(req.body.email, res, false)
241 logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
242 // Do not leak our emails
243 return res.status(204).end()
250 const usersResetPasswordValidator = [
251 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
252 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
253 body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
255 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
256 logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
258 if (areValidationErrors(req, res)) return
259 if (!await checkUserIdExist(req.params.id, res)) return
261 const user = res.locals.user
262 const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
264 if (redisVerificationString !== req.body.verificationString) {
267 .send({ error: 'Invalid verification string.' })
275 const usersAskSendVerifyEmailValidator = [
276 body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
278 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
279 logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
281 if (areValidationErrors(req, res)) return
282 const exists = await checkUserEmailExist(req.body.email, res, false)
284 logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
285 // Do not leak our emails
286 return res.status(204).end()
293 const usersVerifyEmailValidator = [
294 param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
295 body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
297 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
298 logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
300 if (areValidationErrors(req, res)) return
301 if (!await checkUserIdExist(req.params.id, res)) return
303 const user = res.locals.user
304 const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
306 if (redisVerificationString !== req.body.verificationString) {
309 .send({ error: 'Invalid verification string.' })
317 const userAutocompleteValidator = [
318 param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
321 const ensureAuthUserOwnsAccountValidator = [
322 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
323 const user = res.locals.oauth.token.User
325 if (res.locals.account.id !== user.Account.id) {
326 return res.status(403)
327 .send({ error: 'Only owner can access ratings list.' })
335 // ---------------------------------------------------------------------------
340 usersRegisterValidator,
341 usersBlockingValidator,
342 usersRemoveValidator,
343 usersUpdateValidator,
344 usersUpdateMeValidator,
345 usersVideoRatingValidator,
346 ensureUserRegistrationAllowed,
347 ensureUserRegistrationAllowedForIP,
349 usersAskResetPasswordValidator,
350 usersResetPasswordValidator,
351 usersAskSendVerifyEmailValidator,
352 usersVerifyEmailValidator,
353 userAutocompleteValidator,
354 ensureAuthUserOwnsAccountValidator
357 // ---------------------------------------------------------------------------
359 function checkUserIdExist (id: number, res: express.Response) {
360 return checkUserExist(() => UserModel.loadById(id), res)
363 function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
364 return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
367 async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
368 const user = await UserModel.loadByUsernameOrEmail(username, email)
372 .send({ error: 'User with this username or email already exists.' })
377 const actor = await ActorModel.loadLocalByName(username)
380 .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
388 async function checkUserExist (finder: () => Bluebird<UserModel>, res: express.Response, abortResponse = true) {
389 const user = await finder()
392 if (abortResponse === true) {
394 .send({ error: 'User not found' })
401 res.locals.user = user