chenged display of devices according to user`s role. all changes are made in backend
This commit is contained in:
@@ -26,12 +26,52 @@ func (h *DevicesHandler) List(c *gin.Context) {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
var total int64
|
||||
h.db.Model(&models.Device{}).Count(&total)
|
||||
// Get user context
|
||||
userContext, exists := c.Get("user")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
user, ok := userContext.(UserContext)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid user data"})
|
||||
return
|
||||
}
|
||||
|
||||
var total int64
|
||||
var devs []models.Device
|
||||
if err := h.db.Preload("Users").Offset(offset).Limit(limit).Find(&devs).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
var err error
|
||||
|
||||
if user.Role == models.RoleAdmin {
|
||||
// Admin user - show all devices
|
||||
err = h.db.Model(&models.Device{}).Count(&total).Error
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "count query failed: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err = h.db.Preload("Users").Offset(offset).Limit(limit).Find(&devs).Error
|
||||
} else {
|
||||
err = h.db.Model(&models.Device{}).
|
||||
Joins("INNER JOIN user_devices ON user_devices.id = devices.guid").
|
||||
Where("user_devices.guid = ?", user.ID).
|
||||
Count(&total).Error
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "count query failed: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err = h.db.Preload("Users").
|
||||
Joins("INNER JOIN user_devices ON user_devices.id = devices.guid").
|
||||
Where("user_devices.guid = ?", user.ID).
|
||||
Offset(offset).Limit(limit).
|
||||
Find(&devs).Error
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -39,6 +79,7 @@ func (h *DevicesHandler) List(c *gin.Context) {
|
||||
for _, d := range devs {
|
||||
out = append(out, dto.MapDevice(d))
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.DeviceListDto{Devices: out, Offset: offset, Limit: limit, Total: total})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user