Skip to content

Commit

Permalink
Merge pull request #4 from joanrodas/dev
Browse files Browse the repository at this point in the history
Allow callable for roles and capabilities
  • Loading branch information
joanrodas authored Apr 12, 2022
2 parents 37148b0 + 189613f commit d1c1e9f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
18 changes: 15 additions & 3 deletions PluboRoutes/PluboRoutesProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,16 +161,19 @@ private function checkLoggedIn($user)
private function checkRoles($user)
{
$allowed_roles = $this->matched_route->getRoles();
if ($allowed_roles && !array_intersect((array)$user->roles, $allowed_roles)) {
if ($this->matched_route->hasRolesCallback()) {
$allowed_roles = call_user_func($allowed_roles, $this->matched_args);
}
if ($allowed_roles && !array_intersect((array)$user->roles, (array)$allowed_roles)) {
$this->forbidAccess();
}
}

private function checkCapabilities($user)
{
$allowed_caps = $this->matched_route->getCapabilities();
$allowed_caps = $this->getAllowedCapabilities();
$is_allowed = $allowed_caps ? false : true;
foreach ($allowed_caps as $allowed_cap) {
foreach ((array)$allowed_caps as $allowed_cap) {
if ($user->has_cap($allowed_cap)) {
$is_allowed = true;
break;
Expand All @@ -181,6 +184,15 @@ private function checkCapabilities($user)
}
}

private function getAllowedCapabilities()
{
$allowed_caps = $this->matched_route->getCapabilities();
if ($this->matched_route->hasCapabilitiesCallback()) {
$allowed_caps = call_user_func($allowed_caps, $this->matched_args);
}
return $allowed_caps;
}

private function forbidAccess()
{
if ($this->matched_route->hasRedirect()) {
Expand Down
22 changes: 22 additions & 0 deletions PluboRoutes/Route/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,17 @@ public function getRedirect()
return $redirect;
}

/**
* Check if the roles option is a callable.
*
* @return boolean
*/
public function hasRolesCallback()
{
$roles = $this->config['allowed_roles'] ?? [];
return is_callable($roles);
}

/**
* Get the allowed roles.
*
Expand All @@ -146,6 +157,17 @@ public function getRoles()
return $roles;
}

/**
* Check if the capabilities option is a callable.
*
* @return boolean
*/
public function hasCapabilitiesCallback()
{
$capabilities = $this->config['allowed_caps'] ?? [];
return is_callable($capabilities);
}

/**
* Get the allowed capabilities.
*
Expand Down
2 changes: 1 addition & 1 deletion plubo-routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function () {
array(
'private' => true, //Default false
'redirect' => 'https://sirvelia.com',
'allowed_roles' => array('patata'),
'allowed_roles' => 'administrator',
'extra_vars' => [
'client_id' => 'number'
],
Expand Down

0 comments on commit d1c1e9f

Please sign in to comment.