From 71ec298db53a1bb38e6ba9ae05992b20fbd694a0 Mon Sep 17 00:00:00 2001 From: StarFleetCPTN Date: Sun, 6 Apr 2025 23:58:56 -0700 Subject: [PATCH] fix: Update admin user deletion logic to prevent deletion of the last administrator - Changed the logic in the HandleDeleteUser function to check for other administrators using the actual 'is_admin' column instead of counting all admins. - Prevented deletion if no other administrators exist, ensuring at least one admin remains in the system. https://github.com/StarFleetCPTN/GoMFT/issues/67 --- internal/web/handlers/admin_handlers.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/internal/web/handlers/admin_handlers.go b/internal/web/handlers/admin_handlers.go index 3523c9c..a3f71b5 100644 --- a/internal/web/handlers/admin_handlers.go +++ b/internal/web/handlers/admin_handlers.go @@ -1181,15 +1181,18 @@ func (h *Handlers) HandleDeleteUser(c *gin.Context) { // Check if this is an admin user if user.GetIsAdmin() { - // Count how many admins there are - var adminCount int64 - if err := h.DB.Model(&db.User{}).Where("metadata->>'is_admin' = 'true'").Count(&adminCount).Error; err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to check admin count"}) + // Check if other administrators exist + var otherAdminCount int64 + // Use the actual 'is_admin' column, comparing against true + if err := h.DB.Model(&db.User{}). + Where("is_admin = ? AND id != ?", true, user.ID). + Count(&otherAdminCount).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to check for other administrators"}) return } - // If this is the last admin, prevent deletion - if adminCount <= 1 { + // If no other administrators exist, prevent deletion + if otherAdminCount == 0 { c.JSON(http.StatusBadRequest, gin.H{"error": "Cannot delete the last administrator"}) return }