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