From 0807add38cac765673019b578f026cee0204d3cd Mon Sep 17 00:00:00 2001 From: Tony Murray Date: Thu, 23 May 2019 10:03:00 -0500 Subject: [PATCH] Fix device groups showing multiple times. (#10247) Update hasAccess to not use a join. Move into The Permissions facade so we only query the db once per page load for the permissions. --- LibreNMS/Permissions.php | 21 +++++++++++++++++++++ app/Models/DeviceGroup.php | 7 ++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/LibreNMS/Permissions.php b/LibreNMS/Permissions.php index b4c95ccec8..4eb891c023 100644 --- a/LibreNMS/Permissions.php +++ b/LibreNMS/Permissions.php @@ -37,6 +37,7 @@ class Permissions private $devicePermissions; private $portPermissions; private $billPermissions; + private $deviceGroupMap; /** * Check if a device can be accessed by user (non-global read/admin) @@ -164,6 +165,26 @@ class Permissions ->pluck('bill_id'); } + /** + * Get the ids of all device groups the user can access + * + * @param User|int $user + * @return \Illuminate\Support\Collection + */ + public function deviceGroupsForUser($user = null) + { + $user_id = $this->getUserId($user); + + // if we don't have a map for this user yet, populate it. + if (!isset($this->deviceGroupMap[$user_id])) { + $this->deviceGroupMap[$user_id] = DB::table('device_group_device') + ->whereIn('device_id', $this->devicesForUser($user)) + ->pluck('device_group_id'); + } + + return $this->deviceGroupMap[$user_id]; + } + /** * Get the cached data for device permissions. Use helpers instead. * diff --git a/app/Models/DeviceGroup.php b/app/Models/DeviceGroup.php index c4bb56f8a7..69167f5db4 100644 --- a/app/Models/DeviceGroup.php +++ b/app/Models/DeviceGroup.php @@ -25,6 +25,7 @@ namespace App\Models; +use Permissions; use DB; class DeviceGroup extends BaseModel @@ -291,11 +292,7 @@ class DeviceGroup extends BaseModel return $query; } - if (!$this->isJoined($query, 'device_group_device')) { - $query->join('device_group_device', 'device_group_device.device_group_id', 'device_groups.id'); - } - - return $this->hasDeviceAccess($query, $user, 'device_group_device'); + return $query->whereIn('id', Permissions::deviceGroupsForUser($user)); } // ---- Define Relationships ----