Skip to content

Commit 0780dba

Browse files
vazaha-nlLennart Hengstmengel
and
Lennart Hengstmengel
authored
Bugfix: include class in cache key to prevent incorrect cached values (#15)
* added test for policies depending on user class * bug fix: include the user class in the cache key --------- Co-authored-by: Lennart Hengstmengel <[email protected]>
1 parent ade810d commit 0780dba

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/LaravelPolicySoftCache.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,6 @@ protected function callPolicyMethod(Model $user, object $policy, string $ability
9797
*/
9898
protected function getCacheKey(Model $user, object $policy, array $args, string $ability): string
9999
{
100-
return $user->{$user->getKeyName()}.'_'.hash_hmac('sha512', (string) json_encode($args), config('app.key')).'_'.$ability.'_'.$policy::class;
100+
return get_class($user).'_'.$user->{$user->getKeyName()}.'_'.hash_hmac('sha512', (string) json_encode($args), config('app.key')).'_'.$ability.'_'.$policy::class;
101101
}
102102
}

tests/PolicySoftCacheTest.php

+30
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,20 @@
9292
expect(true)->toBeTrue();
9393
});
9494

95+
it('caches correct value if it depends on the user class', function () {
96+
$user = new User();
97+
$customUser = new CustomUser();
98+
$testModel = new TestModel();
99+
100+
Gate::policy(TestModel::class, PolicyWithDifferingCustomUserLogic::class);
101+
102+
$userCanView = $user->can('view', $testModel);
103+
expect($userCanView)->toBeTrue();
104+
105+
$customUserCanView = $customUser->can('view', $testModel);
106+
expect($customUserCanView)->toBeFalse();
107+
});
108+
95109
class PolicyWithSoftCache implements SoftCacheable
96110
{
97111
public static int $called = 0;
@@ -127,3 +141,19 @@ public function create(User $user, int $value): bool
127141
class TestModel extends Model
128142
{
129143
}
144+
145+
class CustomUser extends User
146+
{
147+
}
148+
149+
class PolicyWithDifferingCustomUserLogic implements SoftCacheable
150+
{
151+
public function view(User|CustomUser $user, TestModel $model): bool
152+
{
153+
if ($user instanceof CustomUser) {
154+
return false;
155+
}
156+
157+
return true;
158+
}
159+
}

0 commit comments

Comments
 (0)