checkpoint before gorm fix
This commit is contained in:
@@ -96,3 +96,30 @@ func (h *UsersHandler) Create(c *gin.Context) {
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapUser(u))
|
||||
}
|
||||
|
||||
// DELETE /users/:id (admin) — delete user and clear device relations
|
||||
func (h *UsersHandler) Delete(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
id, _ := strconv.Atoi(idStr)
|
||||
if id <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
var u models.User
|
||||
if err := h.db.Preload("Devices").First(&u, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
// optional safeguard: prevent self-delete; uncomment if desired
|
||||
// if ClaimUserID(MustClaims(c)) == u.ID { c.JSON(http.StatusBadRequest, gin.H{"error":"cannot delete yourself"}); return }
|
||||
if err := h.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&u).Association("Devices").Clear(); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&u).Error
|
||||
}); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "delete failed"})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user