Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

- Manage dashboard access rights per Group and per User (in addition to per Profile)

<<<<<<< HEAD
## [1.5.0] - 2026-10-06

### Added

- GLPI 12 compatibility
- Local dev environment (Metabase instance + admin/embedding seeding) for plugin development
=======
### Fixed

- Fix the profile rights tab freezing the browser and failing to save with many dashboards, and the collections page querying Metabase once per collection

## [1.4.3] - 2026-10-06
>>>>>>> 9a5eccd (Perf profile rights and api calls (#173))

### Fixed

Expand Down
4 changes: 3 additions & 1 deletion front/collections.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,10 @@

echo '<h3>' . __s('Extract questions from metabase:', 'metabase') . '</h3>';
echo "<ul class='metabase_collection_list'>";
// all cards in one query, instead of the full list once per collection
$cards_by_collection = $apiclient->getCardsByCollection();
foreach ($collections as $collection) {
$collection_cards = $apiclient->getCards($collection['id']);
$collection_cards = $cards_by_collection === false ? false : ($cards_by_collection[$collection['id']] ?? []);
if (
$collection_cards !== false
&& count($collection_cards)
Expand Down
36 changes: 23 additions & 13 deletions front/profileright.form.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@
if (
!array_key_exists('profiles_id', $_REQUEST)
|| empty($_REQUEST['profiles_id'])
|| !array_key_exists('dashboard', $_REQUEST)
|| !is_array($_REQUEST['dashboard'])
|| !array_key_exists('dashboards', $_REQUEST)
|| !is_string($_REQUEST['dashboards'])
|| !is_string($_REQUEST['dashboards_read'] ?? '')
) {
Session::addMessageAfterRedirect(
__s('Invalid request.', 'metabase'),
Expand All @@ -45,19 +46,26 @@
Html::back();
}

// displayed dashboards and readable ones, each sent as one comma separated field
$readableUuids = array_flip(array_map('intval', array_filter(explode(',', $_REQUEST['dashboards_read'] ?? ''))));

$rightsByDashboard = [];
$viewableDashboardsUuids = [];
foreach ($_REQUEST['dashboard'] as $dashboardUuid => $rights) {
PluginMetabaseProfileright::setDashboardRightsForProfile(
$_REQUEST['profiles_id'],
$dashboardUuid,
$rights,
);
foreach (array_filter(explode(',', $_REQUEST['dashboards'])) as $dashboardUuid) {
$dashboardUuid = (int) $dashboardUuid;
$rights = isset($readableUuids[$dashboardUuid]) ? READ : 0;

$rightsByDashboard[$dashboardUuid] = $rights;
if (($rights & READ) !== 0) {
$viewableDashboardsUuids[] = $dashboardUuid;
}
}

PluginMetabaseProfileright::setDashboardsRightsForProfile(
$_REQUEST['profiles_id'],
$rightsByDashboard,
);

$apiclient = new PluginMetabaseAPIClient();
$apiclient->enableDashboardsEmbeddedDisplay($viewableDashboardsUuids);
} elseif (isset($_REQUEST['set_rights_to_all'])) {
Expand All @@ -74,17 +82,19 @@

$apiclient = new PluginMetabaseAPIClient();

$rightsByDashboard = [];
$viewableDashboardsUuids = [];
foreach ($apiclient->getDashboards() as $dashboard) {
PluginMetabaseProfileright::setDashboardRightsForProfile(
$_REQUEST['profiles_id'],
$dashboard['id'],
$_REQUEST['set_rights_to_all'],
);
$rightsByDashboard[$dashboard['id']] = $_REQUEST['set_rights_to_all'];

$viewableDashboardsUuids[] = $dashboard['id'];
}

PluginMetabaseProfileright::setDashboardsRightsForProfile(
$_REQUEST['profiles_id'],
$rightsByDashboard,
);

$apiclient->enableDashboardsEmbeddedDisplay($viewableDashboardsUuids);
}

Expand Down
48 changes: 32 additions & 16 deletions inc/apiclient.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,11 @@ public function connect()

public function checkSession()
{
// do a simple query
$this->getCurrentUser(true);

// check session token, if set, we still have a valid token
// a stored token is used as is: an expired one is renewed by httpQuery() on the 401 answer
if (isset($_SESSION['metabase']['session_token'])) {
return true;
}

// so reconnect
$this->connect();
// check again session token, if set, we now have a valid token
return isset($_SESSION['metabase']['session_token']);
Expand Down Expand Up @@ -645,6 +641,21 @@ public function retrieveCard($card_name, $collection_id)
* @return boolean|array Array of cards, false if an error occurs.
*/
public function getCards($collection_id = null)
{
$cards_by_collection = $this->getCardsByCollection();
if ($cards_by_collection === false) {
return false;
}

return $cards_by_collection[$collection_id ?? 'root'] ?? [];
}

/**
* Retrieve all cards, grouped by collection.
*
* @return false|array<int|string, array> Cards indexed by collection id ("root" for the root collection), false if an error occurs.
*/
public function getCardsByCollection()
{
if (!$this->checkSession()) {
return false;
Expand All @@ -657,17 +668,15 @@ public function getCards($collection_id = null)
}

// Metabase's API returns id:"root" for the root collection, but cards
// in it have collection_id: null - normalize before comparing.
$normalized_id = $collection_id === 'root' ? null : $collection_id;

$cards = array_filter(
$cards,
fn($card) => is_array($card)
&& array_key_exists('collection_id', $card)
&& $normalized_id === $card['collection_id'],
);
// in it have collection_id: null.
$cards_by_collection = [];
foreach ($cards as $card) {
if (is_array($card) && array_key_exists('collection_id', $card)) {
$cards_by_collection[$card['collection_id'] ?? 'root'][] = $card;
}
}

return $cards;
return $cards_by_collection;
}

/**
Expand Down Expand Up @@ -813,11 +822,13 @@ public function getAPIBaseUri()
* @param string $method Http verb (ex: GET, POST, etc)
* @return array|false data returned by the api
*/
public function httpQuery($resource = '', $params = [], $method = 'GET')
public function httpQuery($resource = '', $params = [], $method = 'GET', bool $is_retry = false)
{
/** @var array $CFG_GLPI */
global $CFG_GLPI;

$query_params = $params;

// declare default params
$default_params = [
'_with_metadata' => false,
Expand Down Expand Up @@ -884,6 +895,11 @@ public function httpQuery($resource = '', $params = [], $method = 'GET')
// session with metabase ko, unset our token
if ($response->getStatusCode() == 401) {
unset($_SESSION['metabase']['session_token']);

// expired token: log in again and replay the query once
if (!$is_retry && $resource !== 'session' && $this->connect()) {
return $this->httpQuery($resource, $query_params, $method, true);
}
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions inc/dashboard.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ public static function showForCentral(Central $item, $withtemplate = 0, $is_help

$dashboards = $apiclient->getDashboards();
if (is_array($dashboards)) {
<<<<<<< HEAD
// User and group rights are resolved once for all dashboards (single query)
// instead of once per dashboard inside the filter below.
$viewable = PluginMetabaseItemright::getViewableDashboardIds(
Expand All @@ -124,6 +125,14 @@ function ($dashboard) use ($viewable, $profileId) {
$dashboardId = (int) $dashboard['id'];
$canView = isset($viewable[$dashboardId])
|| PluginMetabaseProfileright::canProfileViewDashboard($profileId, $dashboardId) !== 0;
=======
$rights = PluginMetabaseProfileright::getProfileRights($_SESSION['glpiactiveprofile']['id']);
$dashboards = array_filter(
$dashboards,
function ($dashboard) use ($rights) {
$isEmbeddingEnabled = $dashboard['enable_embedding'];
$canView = (($rights[$dashboard['id']] ?? 0) & READ) !== 0;
>>>>>>> 9a5eccd (Perf profile rights and api calls (#173))

return $isEmbeddingEnabled && $canView;
},
Expand Down
130 changes: 120 additions & 10 deletions inc/profileright.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,28 @@ public function showForm($id, $options = [])
return false;
}

echo '<form method="post" action="' . self::getFormURL() . '">';
$rights = self::getProfileRights($id);
$rand = mt_rand();

if (Session::haveRight('profile', UPDATE)) {
// own form: these buttons must not send the rights of every dashboard
echo '<form method="post" action="' . self::getFormURL() . '">';
echo '<input type="hidden" name="profiles_id" value="' . $id . '" />';
echo '<div class="center mb-2">';
echo '<button type="submit" class="btn btn-outline-secondary" name="set_rights_to_all" value="1">'
. "<i class='ti ti-check'></i>"
. '<span>' . __s('Allow access to all', 'metabase') . '</span>'
. '</button>';
echo ' &nbsp; ';
echo '<button type="submit" class="btn btn-outline-secondary" name="set_rights_to_all" value="0">'
. "<i class='ti ti-forbid'></i>"
. '<span>' . __s('Disallow access to all', 'metabase') . '</span>'
. '</button>';
echo '</div>';
Html::closeForm();
}

echo '<form method="post" action="' . self::getFormURL() . '" id="metabase_rights_form' . $rand . '">';
echo '<div class="spaced" id="tabsbody">';
echo '<table class="tab_cadre_fixe" id="mainformtable">';

Expand All @@ -104,6 +125,7 @@ public function showForm($id, $options = [])
echo '<tr><th colspan="2">' . __s('Rights management', 'metabase') . '</th></tr>';

echo '<input type="hidden" name="profiles_id" value="' . $id . '" />';
<<<<<<< HEAD

if (Session::haveRight(Profile::$rightname, UPDATE)) {
echo '<tr class="tab_bg_4">';
Expand All @@ -120,20 +142,21 @@ public function showForm($id, $options = [])
echo '</td>';
echo '</tr>';
}
=======
// one field for all the dashboards, to stay below max_input_vars
echo '<input type="hidden" name="dashboards" value="' . implode(',', array_map('intval', array_column($dashboards, 'id'))) . '" />';
echo '<input type="hidden" name="dashboards_read" value="" />';
>>>>>>> 9a5eccd (Perf profile rights and api calls (#173))

foreach ($dashboards as $dashboard) {
$checked = (($rights[$dashboard['id']] ?? 0) & READ) !== 0 ? ' checked' : '';
echo '<tr class="tab_bg_1">';
echo '<td>' . htmlspecialchars($dashboard['name'], ENT_QUOTES | ENT_HTML5) . '</td>';
echo '<td>';
Profile::dropdownRight(
sprintf('dashboard[%d]', $dashboard['id']),
[
'value' => self::getProfileRightForDashboard($id, $dashboard['id']),
'nonone' => 0,
'noread' => 0,
'nowrite' => 1,
],
);
echo '<label class="form-check mb-0">';
echo '<input type="checkbox" class="form-check-input metabase_dashboard_read" value="' . (int) $dashboard['id'] . '"' . $checked . ' />';
echo '<span class="form-check-label">' . __s('Read') . '</span>';
echo '</label>';
echo '</td>';
echo '</tr>';
}
Expand All @@ -155,6 +178,15 @@ public function showForm($id, $options = [])

Html::closeForm();

echo Html::scriptBlock(<<<JS
$('#metabase_rights_form{$rand}').on('submit', function () {
const read = $(this).find('input.metabase_dashboard_read:checked').map(function () {
return this.value;
}).get();
$(this).find('input[name=dashboards_read]').val(read.join(','));
});
JS);

return true;
}

Expand Down Expand Up @@ -188,6 +220,84 @@ public static function canProfileViewDashboards($profileId)
return false;
}

/**
* Returns the rights of a profile on all dashboards.
*
* @param integer $profileId
*
* @return array<int, int> rights indexed by dashboard uuid
*/
public static function getProfileRights($profileId)
{
/** @var DBmysql $DB */
global $DB;

$iterator = $DB->request(
[
'SELECT' => ['dashboard_uuid', 'rights'],
'FROM' => self::getTable(),
'WHERE' => [
'profiles_id' => $profileId,
],
],
);

$rights = [];
foreach ($iterator as $right) {
$rights[(int) $right['dashboard_uuid']] = (int) $right['rights'];
}

return $rights;
}

/**
* Defines profile rights for several dashboards, writing only the rights that change.
*
* @param integer $profileId
* @param array<int, int> $rightsByDashboard rights indexed by dashboard uuid
*
* @return void
*/
public static function setDashboardsRightsForProfile($profileId, array $rightsByDashboard)
{
/** @var DBmysql $DB */
global $DB;

$existing = [];
$iterator = $DB->request(
[
'SELECT' => ['id', 'dashboard_uuid', 'rights'],
'FROM' => self::getTable(),
'WHERE' => [
'profiles_id' => $profileId,
],
],
);
foreach ($iterator as $right) {
$existing[(int) $right['dashboard_uuid']] = $right;
}

$profileRight = new self();
foreach ($rightsByDashboard as $dashboardUuid => $rights) {
if (!isset($existing[$dashboardUuid])) {
$profileRight->add(
[
'profiles_id' => $profileId,
'dashboard_uuid' => $dashboardUuid,
'rights' => $rights,
],
);
} elseif ((int) $existing[$dashboardUuid]['rights'] !== (int) $rights) {
$profileRight->update(
[
'id' => $existing[$dashboardUuid]['id'],
'rights' => $rights,
],
);
}
}
}

/**
* Check if profile is able to view given dashboard.
*
Expand Down
Loading
Loading