Merge pull request 'Validate and uniqueness-check username on user update (fixes #13)' (#17) from fix/username-validation-update into main
Reviewed-on: UOM/website#17 Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
This commit is contained in:
@@ -475,6 +475,13 @@ async function updateUser(req, res) {
|
|||||||
const target = await users.getById(id)
|
const target = await users.getById(id)
|
||||||
if (!target) return res.status(404).json({ message: 'Not found' })
|
if (!target) return res.status(404).json({ message: 'Not found' })
|
||||||
|
|
||||||
|
// If the username is changing, make sure no other user already has it —
|
||||||
|
// return 409 rather than letting the DB unique constraint throw a 500.
|
||||||
|
if (req.body.username && req.body.username !== target.username) {
|
||||||
|
const clash = await users.getRawByUsername(req.body.username)
|
||||||
|
if (clash) return res.status(409).json({ message: 'Username already taken' })
|
||||||
|
}
|
||||||
|
|
||||||
// Don't let the last admin demote themselves out of admin access.
|
// Don't let the last admin demote themselves out of admin access.
|
||||||
if (target.role === 'admin' && req.body.role && req.body.role !== 'admin') {
|
if (target.role === 'admin' && req.body.role && req.body.role !== 'admin') {
|
||||||
if ((await users.countAdmins()) <= 1) {
|
if ((await users.countAdmins()) <= 1) {
|
||||||
|
|||||||
@@ -160,6 +160,7 @@ adminRouter.post(
|
|||||||
adminRouter.put(
|
adminRouter.put(
|
||||||
'/users/:id',
|
'/users/:id',
|
||||||
param('id').isInt(),
|
param('id').isInt(),
|
||||||
|
body('username').optional().isString().trim().isLength({ min: 3, max: 32 }),
|
||||||
body('password').optional().isString().isLength({ min: 8, max: 64 }),
|
body('password').optional().isString().isLength({ min: 8, max: 64 }),
|
||||||
body('role').optional().isIn(['admin', 'editor']),
|
body('role').optional().isIn(['admin', 'editor']),
|
||||||
validate,
|
validate,
|
||||||
|
|||||||
Reference in New Issue
Block a user