From 3cb3fc1a20bbe070859968bd624761ac4660105a Mon Sep 17 00:00:00 2001 From: canove Date: Fri, 4 Sep 2020 11:22:53 -0300 Subject: [PATCH] feat: allowing user editing only to admins --- backend/src/controllers/UserController.js | 35 ++++++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/backend/src/controllers/UserController.js b/backend/src/controllers/UserController.js index 359cdf3..710d433 100644 --- a/backend/src/controllers/UserController.js +++ b/backend/src/controllers/UserController.js @@ -40,6 +40,7 @@ exports.index = async (req, res) => { }; exports.store = async (req, res, next) => { + console.log(req.url); const schema = Yup.object().shape({ name: Yup.string().required().min(2), email: Yup.string() @@ -56,12 +57,18 @@ exports.store = async (req, res, next) => { password: Yup.string().required().min(5), }); - const { value: userCreation } = await Setting.findByPk("userCreation"); + if (req.url === "/signup") { + const { value: userCreation } = await Setting.findByPk("userCreation"); - if (userCreation === "disabled") { + if (userCreation === "disabled") { + return res + .status(403) + .json({ error: "User creation is disabled by administrator." }); + } + } else if (req.user.profile !== "admin") { return res .status(403) - .json({ error: "User creation is disabled by administrator" }); + .json({ error: "Only administrators can create users." }); } await schema.validate(req.body); @@ -98,7 +105,11 @@ exports.update = async (req, res) => { password: Yup.string(), }); - console.log("cai aqui"); + if (req.user.profile !== "admin") { + return res + .status(403) + .json({ error: "Only administrators can edit users." }); + } await schema.validate(req.body); @@ -113,6 +124,16 @@ exports.update = async (req, res) => { res.status(400).json({ error: "No user found with this id." }); } + if (user.profile === "admin" && req.body.profile === "user") { + const adminUsers = await User.count({ where: { profile: "admin" } }); + if (adminUsers <= 1) { + return res + .status(403) + .json({ error: "There must be at leat one admin user." }); + } + console.log("found", adminUsers); + } + await user.update(req.body); io.emit("user", { @@ -133,6 +154,12 @@ exports.delete = async (req, res) => { res.status(400).json({ error: "No user found with this id." }); } + if (req.user.profile !== "admin") { + return res + .status(403) + .json({ error: "Only administrators can edit users." }); + } + await user.destroy(); io.emit("user", {