Skip to content

Commit

Permalink
disable ban and delete button on users who are admins
Browse files Browse the repository at this point in the history
  • Loading branch information
singharaj-usai committed Oct 15, 2024
1 parent e6b4ef8 commit 2e7c7e1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 30 deletions.
33 changes: 10 additions & 23 deletions client/js/admin/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,14 @@ function displayUsers(users) {
</p>
</div>
<div class="user-actions mt-3">
<button class="btn btn-sm btn-${user.isBanned ? 'success' : 'warning'} ban-user" data-user-id="${user._id}" data-is-banned="${user.isBanned}">
<button class="btn btn-sm btn-${user.isBanned ? 'success' : 'warning'} ban-user" data-user-id="${user._id}" data-is-banned="${user.isBanned}" ${user.isAdmin ? 'disabled' : ''}>
<i class="fa fa-${user.isBanned ? 'unlock' : 'ban'}"></i> ${user.isBanned ? 'Unban User' : 'Ban User'}
</button>
${user.isAdmin ? user._id !== currentAdminId ? `<button class="btn btn-sm btn-danger demote-admin" data-user-id="${user._id}"><i class="fa fa-level-down"></i> Demote from Admin</button>`
: '<button class="btn btn-sm btn-success" disabled><i class="fa fa-user-circle"></i> Current Admin</button>'
: `<button class="btn btn-sm btn-info promote-admin" data-user-id="${user._id}"><i class="fa fa-level-up"></i> Promote to Admin</button>`
}
<button class="btn btn-sm btn-danger delete-user" data-user-id="${
user._id
}"><i class="fa fa-trash"></i> Delete User</button>
<button class="btn btn-sm btn-danger delete-user" data-user-id="${user._id}" ${user.isAdmin ? 'disabled' : ''}><i class="fa fa-trash"></i> Delete User</button>
<button class="btn btn-sm btn-info view-messages" data-user-id="${user._id}"><i class="fa fa-envelope"></i> View Messages</button>
</div>
</div>
Expand Down Expand Up @@ -161,8 +158,8 @@ function banUser(userId, banReason) {
showAlert('success', 'User banned successfully.');
loadUsers();
},
error: function () {
showAlert('danger', 'Error banning user. Please try again.');
error: function (xhr) {
showAlert('danger', `Error banning user: ${xhr.responseJSON.error}`);
},
});
}
Expand All @@ -181,8 +178,8 @@ function unbanUser(userId) {
showAlert('success', 'User unbanned successfully.');
loadUsers();
},
error: function () {
showAlert('danger', 'Error unbanning user. Please try again.');
error: function (xhr) {
showAlert('danger', `Error unbanning user: ${xhr.responseJSON.error}`);
},
});
}
Expand All @@ -201,10 +198,7 @@ function promoteToAdmin(userId) {
loadUsers();
},
error: function (xhr) {
showAlert(
'danger',
`Error promoting user to admin: ${xhr.responseJSON.error}`
);
showAlert('danger', `Error promoting user to admin: ${xhr.responseJSON.error}`);
},
});
}
Expand All @@ -223,21 +217,14 @@ function demoteAdmin(userId) {
loadUsers();
},
error: function (xhr) {
showAlert(
'danger',
`Error demoting user from admin: ${xhr.responseJSON.error}`
);
showAlert('danger', `Error demoting user from admin: ${xhr.responseJSON.error}`);
},
});
}
}

function deleteUser(userId) {
if (
confirm(
'Are you sure you want to delete this user? This action cannot be undone.'
)
) {
if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
$.ajax({
url: `/api/admin/users/${userId}`,
method: 'DELETE',
Expand All @@ -249,7 +236,7 @@ function deleteUser(userId) {
loadUsers();
},
error: function () {
showAlert('danger', 'Error deleting user. Please try again.');
showAlert('danger', `Error deleting user: ${xhr.responseJSON.error}`);
},
});
}
Expand Down
35 changes: 28 additions & 7 deletions server/functions/api/routes/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,19 @@ router.delete('/games/:id', async (req, res) => {
router.post('/users/:id/ban', authenticateToken, isAdmin, async (req, res) => {
try {
const { ban, banReason } = req.body;
const userToBan = await User.findById(req.params.id);

if (!userToBan) {
return res.status(404).json({ error: 'User not found.' });
}

if (userToBan.isAdmin) {
return res.status(403).json({ error: 'Cannot ban an admin user.' });
}

if (userToBan._id.toString() === req.user.id) {
return res.status(403).json({ error: 'You cannot ban yourself.' });
}

if (ban && (!banReason || banReason.trim() === '')) {
return res.status(400).json({ error: 'Ban reason is required when banning a user.' });
Expand All @@ -402,10 +415,6 @@ router.post('/users/:id/ban', authenticateToken, isAdmin, async (req, res) => {

const user = await User.findByIdAndUpdate(req.params.id, updateFields, { new: true });

if (!user) {
return res.status(404).json({ error: 'User not found.' });
}

return res.json({ message: ban ? 'User banned successfully.' : 'User unbanned successfully.' });
} catch (error) {
console.error('Error updating user ban status:', error);
Expand All @@ -414,14 +423,26 @@ router.post('/users/:id/ban', authenticateToken, isAdmin, async (req, res) => {
});

// Delete a user (ONLY USE AS LAST RESORT, THIS IS DESTRUCTIVE)
router.delete('/users/:id', async (req, res) => {
router.delete('/users/:id', authenticateToken, isAdmin, async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
const userToDelete = await User.findById(req.params.id);

if (!userToDelete) {
return res.status(404).json({ error: 'User not found' });
}

if (userToDelete.isAdmin) {
return res.status(403).json({ error: 'Cannot delete an admin user.' });
}

if (userToDelete._id.toString() === req.user.id) {
return res.status(403).json({ error: 'You cannot delete yourself.' });
}

await User.findByIdAndDelete(req.params.id);
res.json({ message: 'User deleted successfully' });
} catch (error) {
console.error('Error deleting user:', error);
res.status(500).json({ error: 'Error deleting user' });
}
});
Expand Down

0 comments on commit 2e7c7e1

Please sign in to comment.