Skip to content

Commit

Permalink
fix: ignore duplicate roles and permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Dec 22, 2024
1 parent 6bc7f06 commit 72a0783
Showing 1 changed file with 31 additions and 27 deletions.
58 changes: 31 additions & 27 deletions src/Auth/UsesRoles.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,10 @@ trait UsesRoles
*/
public function assign($role): bool
{
if (!array_key_exists($role, Config::get('roles'))) {
return false;
}

if (in_array($role, $this->roles)) {
return true;
}
$this->setRolesAndPermissions($role);

$roleKey = Config::get('roles.key');

$this->setRolesAndPermissions($role);

if (!($this->data[$roleKey] ?? null)) {
$this->db->query("ALTER TABLE users ADD COLUMN $roleKey TEXT NOT NULL DEFAULT '[]'")->execute();
}
Expand Down Expand Up @@ -134,10 +126,7 @@ public function unassign($role): void
is_array($role) ? $role : [$role]
);

$this->permissions = array_diff(
$this->permissions,
$this->getRolePermissions($role)
);
$this->permissions = $this->getRolePermissions($this->roles);

$this->db
->update('users')
Expand All @@ -151,18 +140,27 @@ public function unassign($role): void
/**
* Set the roles and permissions for a user
*
* @param string|array $role The role(s) to set
* @param string|array $roles The role(s) to set
*/
protected function setRolesAndPermissions($role): void
protected function setRolesAndPermissions($roles): void
{
$this->roles = array_merge(
$this->roles,
is_array($role) ? $role : [$role]
);
if (is_string($roles)) {
$roles = [$roles];
}

foreach ($roles as $role) {
if (!array_key_exists($role, Config::get('roles'))) {
continue;
}

foreach ($this->roles as $role) {
$this->permissions = array_merge($this->permissions, $this->getRolePermissions($role));
if (in_array($role, $this->roles)) {
continue;
}

$this->roles[] = $role;
}

$this->permissions = $this->getRolePermissions($this->roles);
}

/**
Expand All @@ -171,14 +169,20 @@ protected function setRolesAndPermissions($role): void
* @param string|array $role
* @return array
*/
protected function getRolePermissions($role): array
protected function getRolePermissions($roles): array
{
if (is_string($role)) {
return Config::get('roles')[$role] ?? [];
$allRoles = Config::get('roles');

if (is_string($roles)) {
return $allRoles[$roles] ?? [];
}

return array_reduce($role, function ($acc, $role) {
return array_merge($acc, Config::get('roles')[$role] ?? []);
}, []);
return array_values(array_unique(array_reduce($roles, function ($carry, $role) use ($allRoles) {
if (isset($allRoles[$role])) {
$carry = array_merge($carry, $allRoles[$role]); // Merge permissions for the selected role
}

return $carry;
}, [])));
}
}

0 comments on commit 72a0783

Please sign in to comment.