Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix: include class in cache key to prevent incorrect cached values #15

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/LaravelPolicySoftCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,6 @@ protected function callPolicyMethod(Model $user, object $policy, string $ability
*/
protected function getCacheKey(Model $user, object $policy, array $args, string $ability): string
{
return $user->{$user->getKeyName()}.'_'.hash_hmac('sha512', (string) json_encode($args), config('app.key')).'_'.$ability.'_'.$policy::class;
return get_class($user).'_'.$user->{$user->getKeyName()}.'_'.hash_hmac('sha512', (string) json_encode($args), config('app.key')).'_'.$ability.'_'.$policy::class;
}
}
30 changes: 30 additions & 0 deletions tests/PolicySoftCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,20 @@
expect(true)->toBeTrue();
});

it('caches correct value if it depends on the user class', function () {
$user = new User();
$customUser = new CustomUser();
$testModel = new TestModel();

Gate::policy(TestModel::class, PolicyWithDifferingCustomUserLogic::class);

$userCanView = $user->can('view', $testModel);
expect($userCanView)->toBeTrue();

$customUserCanView = $customUser->can('view', $testModel);
expect($customUserCanView)->toBeFalse();
});

class PolicyWithSoftCache implements SoftCacheable
{
public static int $called = 0;
Expand Down Expand Up @@ -127,3 +141,19 @@ public function create(User $user, int $value): bool
class TestModel extends Model
{
}

class CustomUser extends User
{
}

class PolicyWithDifferingCustomUserLogic implements SoftCacheable
{
public function view(User|CustomUser $user, TestModel $model): bool
{
if ($user instanceof CustomUser) {
return false;
}

return true;
}
}
Loading