1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Security\Command; |
6
|
|
|
|
7
|
|
|
use Spiral\Console\Command; |
8
|
|
|
use Spiral\Console\Exception\CommandException; |
9
|
|
|
use Spiral\Security\PermissionsInterface; |
10
|
|
|
use Spiral\Security\Rule\AllowRule; |
11
|
|
|
use Symfony\Component\Console\Input\InputArgument; |
12
|
|
|
|
13
|
|
|
class RolePermissionsCommand extends Command |
14
|
|
|
{ |
15
|
|
|
protected const NAME = 'security:role:permissions'; |
16
|
|
|
protected const DESCRIPTION = 'Get Role(s) Permissions'; |
17
|
|
|
protected const ARGUMENTS = [ |
18
|
|
|
['role', InputArgument::OPTIONAL, 'Role to get permissions'], |
19
|
|
|
]; |
20
|
|
|
private const TABLE_HEADERS = ['role', 'permission', 'rule', 'allowed']; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @throws CommandException |
24
|
|
|
*/ |
25
|
|
|
protected function perform(PermissionsInterface $rbac): int |
26
|
|
|
{ |
27
|
|
|
$role = $this->argument('role'); |
28
|
|
|
|
29
|
|
|
if ($role !== null && !$rbac->hasRole($role)) { |
30
|
|
|
throw new CommandException('Unknown role provided'); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
if ($role !== null) { |
34
|
|
|
$rows = $this->getRolePermissions($role, $rbac); |
35
|
|
|
} else { |
36
|
|
|
$rows = []; |
37
|
|
|
|
38
|
|
|
foreach ($rbac->getRoles() as $role) { |
39
|
|
|
/** @noinspection SlowArrayOperationsInLoopInspection */ |
40
|
|
|
$rows = \array_merge( |
41
|
|
|
$this->getRolePermissions($role, $rbac), |
42
|
|
|
$rows, |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$this->table(self::TABLE_HEADERS, $rows)->render(); |
48
|
|
|
|
49
|
|
|
return self::SUCCESS; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Can be used in your command to prepare more complex output |
54
|
|
|
*/ |
55
|
|
|
protected function markPermissionAllowed(string $rule): ?string |
56
|
|
|
{ |
57
|
|
|
return $rule === AllowRule::class ? '+' : null; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function getRolePermissions(string $role, PermissionsInterface $rbac): array |
61
|
|
|
{ |
62
|
|
|
$permissions = []; |
63
|
|
|
|
64
|
|
|
foreach ($rbac->getPermissions($role) as $permission => $rule) { |
65
|
|
|
$permissions[] = [ |
66
|
|
|
'role' => $role, |
67
|
|
|
'permission' => $permission, |
68
|
|
|
'rule' => $rule, |
69
|
|
|
'allowed' => $this->markPermissionAllowed($rule), |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $permissions; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|