]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/users.js
Server: forbid to remove the root user
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / users.js
1 'use strict'
2
3 const mongoose = require('mongoose')
4
5 const checkErrors = require('./utils').checkErrors
6 const logger = require('../../helpers/logger')
7
8 const User = mongoose.model('User')
9
10 const validatorsUsers = {
11 usersAdd,
12 usersRemove,
13 usersUpdate
14 }
15
16 function usersAdd (req, res, next) {
17 req.checkBody('username', 'Should have a valid username').isUserUsernameValid()
18 req.checkBody('password', 'Should have a valid password').isUserPasswordValid()
19
20 logger.debug('Checking usersAdd parameters', { parameters: req.body })
21
22 checkErrors(req, res, function () {
23 User.loadByUsername(req.body.username, function (err, user) {
24 if (err) {
25 logger.error('Error in usersAdd request validator.', { error: err })
26 return res.sendStatus(500)
27 }
28
29 if (user) return res.status(409).send('User already exists.')
30
31 next()
32 })
33 })
34 }
35
36 function usersRemove (req, res, next) {
37 req.checkParams('id', 'Should have a valid id').notEmpty().isMongoId()
38
39 logger.debug('Checking usersRemove parameters', { parameters: req.params })
40
41 checkErrors(req, res, function () {
42 User.loadById(req.params.id, function (err, user) {
43 if (err) {
44 logger.error('Error in usersRemove request validator.', { error: err })
45 return res.sendStatus(500)
46 }
47
48 if (!user) return res.status(404).send('User not found')
49
50 if (user.username === 'root') return res.status(400).send('Cannot remove the root user')
51
52 next()
53 })
54 })
55 }
56
57 function usersUpdate (req, res, next) {
58 req.checkParams('id', 'Should have a valid id').notEmpty().isMongoId()
59 // Add old password verification
60 req.checkBody('password', 'Should have a valid password').isUserPasswordValid()
61
62 logger.debug('Checking usersUpdate parameters', { parameters: req.body })
63
64 checkErrors(req, res, next)
65 }
66
67 // ---------------------------------------------------------------------------
68
69 module.exports = validatorsUsers