Skip to content

Commit 536ae7f

Browse files
committed
PermissionChecker
1 parent 089d18a commit 536ae7f

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpList\Core\Domain\Common\Model;
6+
7+
enum Ability: string
8+
{
9+
case VIEW = 'view';
10+
case CREATE = 'create';
11+
case EDIT = 'edit';
12+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpList\Core\Domain\Identity\Service;
6+
7+
use PhpList\Core\Domain\Common\Model\Ability;
8+
use PhpList\Core\Domain\Common\Model\Interfaces\OwnableInterface;
9+
use PhpList\Core\Domain\Identity\Model\Administrator;
10+
11+
class PermissionChecker
12+
{
13+
public function isGranted(
14+
Ability $ability,
15+
Administrator $actor,
16+
?OwnableInterface $resource = null,
17+
): bool {
18+
if ($this->isSuperAdmin($actor)) {
19+
return true;
20+
}
21+
22+
return match ($ability) {
23+
Ability::VIEW => $resource && $this->isOwner($actor, $resource),
24+
Ability::EDIT => $resource && $this->isOwner($actor, $resource),
25+
Ability::CREATE => $this->canCreate($actor),
26+
};
27+
}
28+
29+
public function canView(Administrator $actor, OwnableInterface $resource): bool
30+
{
31+
if ($this->isSuperAdmin($actor)) {
32+
return true;
33+
}
34+
35+
return $this->isOwner($actor, $resource);
36+
}
37+
38+
public function canEdit(Administrator $actor, OwnableInterface $resource): bool
39+
{
40+
if ($this->isSuperAdmin($actor)) {
41+
return true;
42+
}
43+
44+
return $this->isOwner($actor, $resource);
45+
}
46+
47+
public function canCreate(Administrator $actor): bool
48+
{
49+
if ($this->isSuperAdmin($actor)) {
50+
return true;
51+
}
52+
53+
return $actor->getId() !== null;
54+
}
55+
56+
private function isSuperAdmin(Administrator $actor): bool
57+
{
58+
if ($actor->isSuperUser()) {
59+
return true;
60+
}
61+
62+
return false;
63+
}
64+
65+
private function isOwner(Administrator $actor, OwnableInterface $resource): bool
66+
{
67+
$owner = $resource->getOwner();
68+
$myId = $actor->getId();
69+
70+
return $owner !== null
71+
&& $myId !== null
72+
&& $owner->getId() === $myId;
73+
}
74+
}

0 commit comments

Comments
 (0)