]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/validators/users.ts
Fix lint
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / users.ts
index aec6324bf0be21acf1d83f97f56dd46282ebf527..6b845f62bbbe3ed37520e466a71fc18a2012ae9d 100644 (file)
@@ -1,3 +1,4 @@
+import { body, param } from 'express-validator/check'
 import 'express-validator'
 import * as express from 'express'
 import * as Promise from 'bluebird'
@@ -5,120 +6,157 @@ import * as validator from 'validator'
 
 import { database as db } from '../../initializers/database'
 import { checkErrors } from './utils'
-import { isSignupAllowed, logger } from '../../helpers'
+import {
+  isSignupAllowed,
+  logger,
+  isUserUsernameValid,
+  isUserPasswordValid,
+  isUserVideoQuotaValid,
+  isUserDisplayNSFWValid,
+  isIdOrUUIDValid,
+  isUserRoleValid
+} from '../../helpers'
 import { UserInstance, VideoInstance } from '../../models'
 
-function usersAddValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  req.checkBody('username', 'Should have a valid username').isUserUsernameValid()
-  req.checkBody('password', 'Should have a valid password').isUserPasswordValid()
-  req.checkBody('email', 'Should have a valid email').isEmail()
-  req.checkBody('videoQuota', 'Should have a valid user quota').isUserVideoQuotaValid()
+const usersAddValidator = [
+  body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
+  body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
+  body('email').isEmail().withMessage('Should have a valid email'),
+  body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
+  body('role').custom(isUserRoleValid).withMessage('Should have a valid role'),
 
-  logger.debug('Checking usersAdd parameters', { parameters: req.body })
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking usersAdd parameters', { parameters: req.body })
 
-  checkErrors(req, res, () => {
-    checkUserDoesNotAlreadyExist(req.body.username, req.body.email, res, next)
-  })
-}
+    checkErrors(req, res, () => {
+      checkUserDoesNotAlreadyExist(req.body.username, req.body.email, res, next)
+    })
+  }
+]
 
-function usersRegisterValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  req.checkBody('username', 'Should have a valid username').isUserUsernameValid()
-  req.checkBody('password', 'Should have a valid password').isUserPasswordValid()
-  req.checkBody('email', 'Should have a valid email').isEmail()
+const usersRegisterValidator = [
+  body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
+  body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
+  body('email').isEmail().withMessage('Should have a valid email'),
 
-  logger.debug('Checking usersRegister parameters', { parameters: req.body })
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking usersRegister parameters', { parameters: req.body })
 
-  checkErrors(req, res, () => {
-    checkUserDoesNotAlreadyExist(req.body.username, req.body.email, res, next)
-  })
-}
+    checkErrors(req, res, () => {
+      checkUserDoesNotAlreadyExist(req.body.username, req.body.email, res, next)
+    })
+  }
+]
 
-function usersRemoveValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  req.checkParams('id', 'Should have a valid id').notEmpty().isInt()
+const usersRemoveValidator = [
+  param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
 
-  logger.debug('Checking usersRemove parameters', { parameters: req.params })
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking usersRemove parameters', { parameters: req.params })
 
-  checkErrors(req, res, () => {
-    checkUserExists(req.params.id, res, (err, user) => {
-      if (err) {
-        logger.error('Error in usersRemoveValidator.', err)
-        return res.sendStatus(500)
-      }
+    checkErrors(req, res, () => {
+      checkUserExists(req.params.id, res, (err, user) => {
+        if (err) {
+          logger.error('Error in usersRemoveValidator.', err)
+          return res.sendStatus(500)
+        }
 
-      if (user.username === 'root') return res.status(400).send('Cannot remove the root user')
+        if (user.username === 'root') {
+          return res.status(400)
+                    .send({ error: 'Cannot remove the root user' })
+                    .end()
+        }
 
-      next()
+        return next()
+      })
     })
-  })
-}
-
-function usersUpdateValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  req.checkParams('id', 'Should have a valid id').notEmpty().isInt()
-  req.checkBody('email', 'Should have a valid email attribute').optional().isEmail()
-  req.checkBody('videoQuota', 'Should have a valid user quota').optional().isUserVideoQuotaValid()
-
-  logger.debug('Checking usersUpdate parameters', { parameters: req.body })
+  }
+]
 
-  checkErrors(req, res, () => {
-    checkUserExists(req.params.id, res, next)
-  })
-}
+const usersUpdateValidator = [
+  param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
+  body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
+  body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
+  body('role').optional().custom(isUserRoleValid).withMessage('Should have a valid role'),
 
-function usersUpdateMeValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  // Add old password verification
-  req.checkBody('password', 'Should have a valid password').optional().isUserPasswordValid()
-  req.checkBody('email', 'Should have a valid email attribute').optional().isEmail()
-  req.checkBody('displayNSFW', 'Should have a valid display Not Safe For Work attribute').optional().isUserDisplayNSFWValid()
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking usersUpdate parameters', { parameters: req.body })
 
-  logger.debug('Checking usersUpdateMe parameters', { parameters: req.body })
+    checkErrors(req, res, () => {
+      checkUserExists(req.params.id, res, next)
+    })
+  }
+]
 
-  checkErrors(req, res, next)
-}
+const usersUpdateMeValidator = [
+  body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
+  body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
+  body('displayNSFW').optional().custom(isUserDisplayNSFWValid).withMessage('Should have a valid display Not Safe For Work attribute'),
 
-function usersGetValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  req.checkParams('id', 'Should have a valid id').notEmpty().isInt()
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    // TODO: Add old password verification
+    logger.debug('Checking usersUpdateMe parameters', { parameters: req.body })
 
-  checkErrors(req, res, () => {
-    checkUserExists(req.params.id, res, next)
-  })
-}
+    checkErrors(req, res, next)
+  }
+]
 
-function usersVideoRatingValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
-  req.checkParams('videoId', 'Should have a valid video id').notEmpty().isVideoIdOrUUIDValid()
+const usersGetValidator = [
+  param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
 
-  logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    checkErrors(req, res, () => {
+      checkUserExists(req.params.id, res, next)
+    })
+  }
+]
 
-  checkErrors(req, res, () => {
-    let videoPromise: Promise<VideoInstance>
+const usersVideoRatingValidator = [
+  param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
 
-    if (validator.isUUID(req.params.videoId)) {
-      videoPromise = db.Video.loadByUUID(req.params.videoId)
-    } else {
-      videoPromise = db.Video.load(req.params.videoId)
-    }
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
 
-    videoPromise
-      .then(video => {
-        if (!video) return res.status(404).send('Video not found')
+    checkErrors(req, res, () => {
+      let videoPromise: Promise<VideoInstance>
 
-        next()
-      })
-      .catch(err => {
-        logger.error('Error in user request validator.', err)
-        return res.sendStatus(500)
-      })
-  })
-}
+      if (validator.isUUID(req.params.videoId)) {
+        videoPromise = db.Video.loadByUUID(req.params.videoId)
+      } else {
+        videoPromise = db.Video.load(req.params.videoId)
+      }
 
-function ensureUserRegistrationAllowed (req: express.Request, res: express.Response, next: express.NextFunction) {
-  isSignupAllowed().then(allowed => {
-    if (allowed === false) {
-      return res.status(403).send('User registration is not enabled or user limit is reached.')
-    }
+      videoPromise
+        .then(video => {
+          if (!video) {
+            return res.status(404)
+                      .json({ error: 'Video not found' })
+                      .end()
+          }
+
+          return next()
+        })
+        .catch(err => {
+          logger.error('Error in user request validator.', err)
+          return res.sendStatus(500)
+        })
+    })
+  }
+]
+
+const ensureUserRegistrationAllowed = [
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    isSignupAllowed().then(allowed => {
+      if (allowed === false) {
+        return res.status(403)
+                  .send({ error: 'User registration is not enabled or user limit is reached.' })
+                  .end()
+      }
 
-    return next()
-  })
-}
+      return next()
+    })
+  }
+]
 
 // ---------------------------------------------------------------------------
 
@@ -138,10 +176,14 @@ export {
 function checkUserExists (id: number, res: express.Response, callback: (err: Error, user: UserInstance) => void) {
   db.User.loadById(id)
     .then(user => {
-      if (!user) return res.status(404).send('User not found')
+      if (!user) {
+        return res.status(404)
+                  .send({ error: 'User not found' })
+                  .end()
+      }
 
       res.locals.user = user
-      callback(null, user)
+      return callback(null, user)
     })
     .catch(err => {
       logger.error('Error in user request validator.', err)
@@ -152,9 +194,13 @@ function checkUserExists (id: number, res: express.Response, callback: (err: Err
 function checkUserDoesNotAlreadyExist (username: string, email: string, res: express.Response, callback: () => void) {
   db.User.loadByUsernameOrEmail(username, email)
       .then(user => {
-        if (user) return res.status(409).send('User already exists.')
+        if (user) {
+          return res.status(409)
+                    .send({ error: 'User with this username of email already exists.' })
+                    .end()
+        }
 
-        callback()
+        return callback()
       })
       .catch(err => {
         logger.error('Error in usersAdd request validator.', err)