Skip to content

Commit

Permalink
Merge pull request #38 from sofia-lpz/newEndpoints
Browse files Browse the repository at this point in the history
New endpoints
  • Loading branch information
sofia-lpz authored Oct 14, 2024
2 parents 73afc8b + b7d638a commit 8afe81f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
16 changes: 16 additions & 0 deletions api/crm.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,14 @@ export const getUsuarios = async (req, res) => {

export const updateUsuario = async (req, res) => {
try {
const user = await crmService.getOneUsuario(req.params.id);
if (user.role === 'admin' && req.body.role !== 'admin') {
const adminCount = await crmService.countAdminUsers();
if (adminCount <= 1) {
res.status(400).json({ error: "Cannot demote the last admin user" });
return;
}
}
const data = await crmService.updateUsuario(req.params.id, req.body);
res.json(data);
} catch (error) {
Expand All @@ -167,6 +175,14 @@ export const deleteUsuario = async (req, res) => {
return;
}
try {
const user = await crmService.getOneUsuario(req.params.id);
if (user.role === 'admin') {
const adminCount = await crmService.countAdminUsers();
if (adminCount <= 1) {
res.status(400).json({ error: "Cannot delete the last admin user" });
return;
}
}
const data = await crmService.deleteUsuario(req.params.id);
res.json(data);
} catch (error) {
Expand Down
7 changes: 7 additions & 0 deletions api/crm.mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ async function connectToDB() {
});
}

export async function countAdminUsers() {
const conn = await connectToDB();
const [rows] = await conn.execute("SELECT COUNT(*) as count FROM usuarios WHERE role = 'admin'");
conn.end();
return rows[0].count;
}

export async function verifyPassword(username, password) {
const user = await getUserByUsername(username);
if (!user) {
Expand Down

0 comments on commit 8afe81f

Please sign in to comment.