Delete deletes a user.
(w http.ResponseWriter, r *http.Request)
| 408 | |
| 409 | // Delete deletes a user. |
| 410 | func (h *UsersHandler) Delete(w http.ResponseWriter, r *http.Request) { |
| 411 | userID := chi.URLParam(r, "userId") |
| 412 | currentUserID, _ := r.Context().Value(middleware.UserIDKey).(string) |
| 413 | if currentUserID != "" && userID == currentUserID { |
| 414 | Error(w, http.StatusBadRequest, "Cannot delete your own account") |
| 415 | return |
| 416 | } |
| 417 | |
| 418 | existing, err := h.users.GetByID(r.Context(), userID) |
| 419 | if err != nil || existing == nil { |
| 420 | Error(w, http.StatusNotFound, "User not found") |
| 421 | return |
| 422 | } |
| 423 | |
| 424 | // Prevent deleting users with a higher-privilege role. |
| 425 | callerRole, _ := r.Context().Value(middleware.UserRoleKey).(string) |
| 426 | if roleRank(existing.Role) > roleRank(callerRole) { |
| 427 | Error(w, http.StatusForbidden, "Cannot delete a user with a higher-privilege role") |
| 428 | return |
| 429 | } |
| 430 | // Deleting a superadmin requires being superadmin or having can_manage_superusers. |
| 431 | if existing.Role == "superadmin" && callerRole != "superadmin" { |
| 432 | perm, permErr := h.permissions.GetByRole(r.Context(), callerRole) |
| 433 | if permErr != nil || perm == nil || !perm.CanManageSuperusers { |
| 434 | Error(w, http.StatusForbidden, "You do not have permission to delete superadmin users") |
| 435 | return |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | var superCount, adminCount int |
| 440 | if existing.Role == "superadmin" { |
| 441 | superCount, _ = h.users.CountSuperadmins(r.Context()) |
| 442 | if superCount <= 1 { |
| 443 | Error(w, http.StatusBadRequest, "Cannot delete the last superadmin user") |
| 444 | return |
| 445 | } |
| 446 | } |
| 447 | if existing.Role == "admin" { |
| 448 | superCount, _ = h.users.CountSuperadmins(r.Context()) |
| 449 | if superCount == 0 { |
| 450 | adminCount, _ = h.users.CountActiveAdmins(r.Context()) |
| 451 | if adminCount <= 1 { |
| 452 | Error(w, http.StatusBadRequest, "Cannot delete the last admin user") |
| 453 | return |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | if err := h.users.Delete(r.Context(), userID); err != nil { |
| 459 | Error(w, http.StatusInternalServerError, "Failed to delete user") |
| 460 | return |
| 461 | } |
| 462 | |
| 463 | JSON(w, http.StatusOK, map[string]string{"message": "User deleted successfully"}) |
| 464 | } |
| 465 | |
| 466 | // ResetPassword resets a user's password. |
| 467 | func (h *UsersHandler) ResetPassword(w http.ResponseWriter, r *http.Request) { |
no test coverage detected