Commit 8d1b1927 authored by Taylor Otwell's avatar Taylor Otwell Committed by GitHub

Merge pull request #1068 from lucasmichot/feature/7.0/inherited-parent-scopes-support

[7.0] Let Passport support inherited parent scopes.
parents 89a0383f a36eb1f9
......@@ -138,6 +138,13 @@ class Passport
*/
public static $unserializesCookies = false;
/**
* Indicates the scope should inherit its parent scope.
*
* @var bool
*/
public static $withInheritedScopes = false;
/**
* Enable the implicit grant type.
*
......
......@@ -83,8 +83,40 @@ class Token extends Model
*/
public function can($scope)
{
return in_array('*', $this->scopes) ||
array_key_exists($scope, array_flip($this->scopes));
if (in_array('*', $this->scopes)) {
return true;
}
$scopes = Passport::$withInheritedScopes
? $this->resolveInheritedScopes($scope)
: [$scope];
foreach ($scopes as $scope) {
if (array_key_exists($scope, array_flip($this->scopes))) {
return true;
}
}
return false;
}
/**
* Resolve all possible scopes.
*
* @param string $scope
* @return array
*/
protected function resolveInheritedScopes($scope)
{
$parts = explode(':', $scope);
$scopes = [];
for ($i = 0; $i <= count($parts); $i++) {
$scopes[] = implode(':', array_slice($parts, 0, $i));
}
return $scopes;
}
/**
......
......@@ -3,10 +3,18 @@
namespace Laravel\Passport\Tests;
use Laravel\Passport\Token;
use Laravel\Passport\Passport;
use PHPUnit\Framework\TestCase;
class TokenTest extends TestCase
{
public function tearDown()
{
parent::tearDown();
Passport::$withInheritedScopes = false;
}
public function test_token_can_determine_if_it_has_scopes()
{
$token = new Token(['scopes' => ['user']]);
......@@ -16,8 +24,38 @@ class TokenTest extends TestCase
$this->assertTrue($token->cant('something'));
$this->assertFalse($token->cant('user'));
$this->assertTrue($token->cant('user:read'));
$token = new Token(['scopes' => ['*']]);
$this->assertTrue($token->can('user'));
$this->assertTrue($token->can('something'));
}
public function test_token_can_determine_if_it_has_inherited_scopes()
{
Passport::$withInheritedScopes = true;
$token = new Token([
'scopes' => [
'user',
'group',
'admin:webhooks:read',
],
]);
$this->assertTrue($token->can('user'));
$this->assertTrue($token->can('group'));
$this->assertTrue($token->can('user:read'));
$this->assertTrue($token->can('group:read'));
$this->assertTrue($token->can('admin:webhooks:read'));
$this->assertTrue($token->cant('admin:webhooks'));
$this->assertFalse($token->can('something'));
$token = new Token(['scopes' => ['*']]);
$this->assertTrue($token->can('user'));
$this->assertTrue($token->can('something'));
$this->assertTrue($token->can('admin:webhooks:write'));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment