Skip to content

Commit d98fa76

Browse files
committed
Only enable policy cache in non-testing env
1 parent 602a3cc commit d98fa76

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

src/Auth/SharpAuthorizationManager.php

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,13 @@
99

1010
class SharpAuthorizationManager
1111
{
12+
private bool $cacheEnabled;
1213
private array $cachedPolicies = [];
1314

14-
public function __construct(protected SharpEntityManager $entityManager, protected Gate $gate) {}
15+
public function __construct(protected SharpEntityManager $entityManager, protected Gate $gate)
16+
{
17+
$this->cacheEnabled = ! app()->environment('testing');
18+
}
1519

1620
public function isAllowed(string $ability, string $entityKey, ?string $instanceId = null): bool
1721
{
@@ -52,25 +56,29 @@ protected function isGloballyForbidden(string $ability, string $entityKey): bool
5256

5357
protected function isPolicyForbidden(string $ability, string $entityKey, ?string $instanceId = null): bool
5458
{
55-
if (! Arr::exists($this->cachedPolicies, "$ability-$entityKey-$instanceId")) {
56-
$entity = $this->entityManager->entityFor($entityKey);
57-
$policy = $entity->getPolicyOrDefault();
58-
59-
$forbidden = true;
60-
if (in_array($ability, ['entity', 'create', 'reorder'])) {
61-
// Always checked
62-
$forbidden = ! $policy->$ability(auth()->user());
63-
} elseif (in_array($ability, ['view', 'update', 'delete'])) {
64-
// Not checked in create case, as it could lead to unwanted errors in functional policy code (with findOrFail for instance)
65-
if ($instanceId || $entity->isSingle()) {
66-
$forbidden = ! $policy->$ability(auth()->user(), $instanceId);
67-
}
59+
if ($this->cacheEnabled && Arr::exists($this->cachedPolicies, "$ability-$entityKey-$instanceId")) {
60+
return $this->cachedPolicies["$ability-$entityKey-$instanceId"];
61+
}
62+
63+
$entity = $this->entityManager->entityFor($entityKey);
64+
$policy = $entity->getPolicyOrDefault();
65+
66+
$forbidden = true;
67+
if (in_array($ability, ['entity', 'create', 'reorder'])) {
68+
// Always checked
69+
$forbidden = ! $policy->$ability(auth()->user());
70+
} elseif (in_array($ability, ['view', 'update', 'delete'])) {
71+
// Not checked in create case, as it could lead to unwanted errors in functional policy code (with findOrFail for instance)
72+
if ($instanceId || $entity->isSingle()) {
73+
$forbidden = ! $policy->$ability(auth()->user(), $instanceId);
6874
}
75+
}
6976

77+
if ($this->cacheEnabled) {
7078
$this->cachedPolicies["$ability-$entityKey-$instanceId"] = $forbidden;
7179
}
7280

73-
return $this->cachedPolicies["$ability-$entityKey-$instanceId"];
81+
return $forbidden;
7482
}
7583

7684
private function deny()

0 commit comments

Comments
 (0)