]>
Commit | Line | Data |
---|---|---|
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 | } | |
12 | ||
13 | function usersAdd (req, res, next) { | |
14 | req.checkBody('username', 'Should have a valid username').isUserUsernameValid() | |
15 | req.checkBody('password', 'Should have a valid password').isUserPasswordValid() | |
16 | ||
17 | logger.debug('Checking usersAdd parameters', { parameters: req.body }) | |
18 | ||
19 | checkErrors(req, res, function () { | |
20 | db.User.loadByUsername(req.body.username, function (err, user) { | |
21 | if (err) { | |
22 | logger.error('Error in usersAdd request validator.', { error: err }) | |
23 | return res.sendStatus(500) | |
24 | } | |
25 | ||
26 | if (user) return res.status(409).send('User already exists.') | |
27 | ||
28 | next() | |
29 | }) | |
30 | }) | |
31 | } | |
32 | ||
33 | function usersRemove (req, res, next) { | |
34 | req.checkParams('id', 'Should have a valid id').notEmpty().isInt() | |
35 | ||
36 | logger.debug('Checking usersRemove parameters', { parameters: req.params }) | |
37 | ||
38 | checkErrors(req, res, function () { | |
39 | db.User.loadById(req.params.id, function (err, user) { | |
40 | if (err) { | |
41 | logger.error('Error in usersRemove request validator.', { error: err }) | |
42 | return res.sendStatus(500) | |
43 | } | |
44 | ||
45 | if (!user) return res.status(404).send('User not found') | |
46 | ||
47 | if (user.username === 'root') return res.status(400).send('Cannot remove the root user') | |
48 | ||
49 | next() | |
50 | }) | |
51 | }) | |
52 | } | |
53 | ||
54 | function usersUpdate (req, res, next) { | |
55 | req.checkParams('id', 'Should have a valid id').notEmpty().isInt() | |
56 | // Add old password verification | |
57 | req.checkBody('password', 'Should have a valid password').isUserPasswordValid() | |
58 | ||
59 | logger.debug('Checking usersUpdate parameters', { parameters: req.body }) | |
60 | ||
61 | checkErrors(req, res, next) | |
62 | } | |
63 | ||
64 | // --------------------------------------------------------------------------- | |
65 | ||
66 | module.exports = validatorsUsers |