Relax on tags (accept any characters and not required anymore)
[oweals/peertube.git] / server / middlewares / validators / users.js
1 'use strict'
2
3 const checkErrors = require('./utils').checkErrors
4 const db = require('../../initializers/database')
5 const logger = require('../../helpers/logger')
6
7 const validatorsUsers = {
8   usersAdd,
9   usersRemove,
10   usersUpdate,
11   usersVideoRating
12 }
13
14 function usersAdd (req, res, next) {
15   req.checkBody('username', 'Should have a valid username').isUserUsernameValid()
16   req.checkBody('password', 'Should have a valid password').isUserPasswordValid()
17   req.checkBody('email', 'Should have a valid email').isEmail()
18
19   logger.debug('Checking usersAdd parameters', { parameters: req.body })
20
21   checkErrors(req, res, function () {
22     db.User.loadByUsernameOrEmail(req.body.username, req.body.email, function (err, user) {
23       if (err) {
24         logger.error('Error in usersAdd request validator.', { error: err })
25         return res.sendStatus(500)
26       }
27
28       if (user) return res.status(409).send('User already exists.')
29
30       next()
31     })
32   })
33 }
34
35 function usersRemove (req, res, next) {
36   req.checkParams('id', 'Should have a valid id').notEmpty().isInt()
37
38   logger.debug('Checking usersRemove parameters', { parameters: req.params })
39
40   checkErrors(req, res, function () {
41     db.User.loadById(req.params.id, function (err, user) {
42       if (err) {
43         logger.error('Error in usersRemove request validator.', { error: err })
44         return res.sendStatus(500)
45       }
46
47       if (!user) return res.status(404).send('User not found')
48
49       if (user.username === 'root') return res.status(400).send('Cannot remove the root user')
50
51       next()
52     })
53   })
54 }
55
56 function usersUpdate (req, res, next) {
57   req.checkParams('id', 'Should have a valid id').notEmpty().isInt()
58   // Add old password verification
59   req.checkBody('password', 'Should have a valid password').isUserPasswordValid()
60
61   logger.debug('Checking usersUpdate parameters', { parameters: req.body })
62
63   checkErrors(req, res, next)
64 }
65
66 function usersVideoRating (req, res, next) {
67   req.checkParams('videoId', 'Should have a valid video id').notEmpty().isUUID(4)
68
69   logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
70
71   checkErrors(req, res, function () {
72     db.Video.load(req.params.videoId, function (err, video) {
73       if (err) {
74         logger.error('Error in user request validator.', { error: err })
75         return res.sendStatus(500)
76       }
77
78       if (!video) return res.status(404).send('Video not found')
79
80       next()
81     })
82   })
83 }
84
85 // ---------------------------------------------------------------------------
86
87 module.exports = validatorsUsers