Skip to content

Commit

Permalink
feat: Add getAllUsersByDomain rbac method
Browse files Browse the repository at this point in the history
feat: Add getAllUsersByDomain rbac method
  • Loading branch information
basakest committed Sep 23, 2021
1 parent 1eb5fd0 commit 59079b5
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Enforcer.php
Expand Up @@ -433,6 +433,40 @@ public function getImplicitUsersForPermission(string ...$permission): array
return $res;
}

/**
* GetAllUsersByDomain would get all users associated with the domain.
*
* @param string $domain
* @return string[]
*/
public function getAllUsersByDomain(string $domain): array
{
$m = [];
$g = $this->model['g']['g'];
$p = $this->model['p']['p'];
$users = [];
$index = $this->getDomainIndex('p');

$getUser = function (int $index, array $policies, string $domain, array $m): array {
if (count($policies) == 0 || count($policies[0]) <= $index) {
return [];
}
$res = [];
foreach ($policies as $policy) {
$ok = isset($m[$policy[0]]);
if ($policy[$index] == $domain && !$ok) {
$res[] = $policy[0];
$m[$policy[0]] = [];
}
}
return $res;
};

$users[] = $getUser(2, $g->policy, $domain, $m)[0];
$users[] = $getUser($index, $p->policy, $domain, $m)[0];
return $users;
}

/**
* Gets the users that has a role inside a domain. Add by Gordon.
*
Expand Down
20 changes: 20 additions & 0 deletions src/InternalEnforcer.php
Expand Up @@ -342,4 +342,24 @@ protected function updateFilteredPoliciesInternal(string $sec, string $ptype, ar

return $ruleChanged;
}

/**
* Undocumented function
*
* @param string $ptype
* @return int
*/
protected function getDomainIndex(string $ptype): int
{
$p = $this->model['p'][$ptype];
$pattern = sprintf("%s_dom", $ptype);
$index = count($p->tokens);
foreach ($p->tokens as $i => $token) {
if ($token == $pattern) {
$index = $i;
break;
}
}
return $index;
}
}
8 changes: 8 additions & 0 deletions tests/Unit/EnforcerTest.php
Expand Up @@ -345,4 +345,12 @@ public function testGetPermissionsForUserInDomain()
$this->assertEquals($e->getPermissionsForUserInDomain('admin', 'domain2'), [['admin', 'domain2', 'data2', 'read'], ['admin', 'domain2', 'data2', 'write']]);
$this->assertEquals($e->getPermissionsForUserInDomain('non_exist', 'domain2'), []);
}

public function testGetAllUsersByDomain()
{
$e = new Enforcer($this->modelAndPolicyPath . '/rbac_with_domains_model.conf', $this->modelAndPolicyPath . '/rbac_with_domains_policy.csv');

$this->assertEquals(['alice', 'admin'], $e->getAllUsersByDomain('domain1'));
$this->assertEquals(['bob', 'admin'], $e->getAllUsersByDomain('domain2'));
}
}

0 comments on commit 59079b5

Please sign in to comment.