From 3418f6492c63605fee1ba974965d75fbc19a45bd Mon Sep 17 00:00:00 2001 From: Tim Geisendoerfer Date: Thu, 3 Nov 2022 09:16:41 +0100 Subject: [PATCH] bugfixing --- src/LaravelPolicySoftCache.php | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/LaravelPolicySoftCache.php b/src/LaravelPolicySoftCache.php index 7717c5f..dc7b6c5 100644 --- a/src/LaravelPolicySoftCache.php +++ b/src/LaravelPolicySoftCache.php @@ -22,6 +22,12 @@ public static function flushCache(): void app()->make(static::class)->cache = []; } + /** + * @param mixed $user + * @param string $ability + * @param mixed $args + * @return mixed + */ public function handleGateCall(mixed $user, string $ability, mixed $args): mixed { if (! is_array($args)) { @@ -37,12 +43,16 @@ public function handleGateCall(mixed $user, string $ability, mixed $args): mixed $policy = Gate::getPolicyFor($model); if ($model && $this->shouldCache($policy)) { - return $this->callPolicyMethod($user, $model, $policy, $ability, $args); + return $this->callPolicyMethod($user, $policy, $ability, $args); } return null; } + /** + * @param object|null $policy + * @return bool + */ protected function shouldCache(?object $policy): bool { return $policy && ($policy instanceof SoftCacheable || config('policy-soft-cache.cache_all_policies', false) === true); @@ -50,29 +60,34 @@ protected function shouldCache(?object $policy): bool /** * @param Model $user - * @param Model $model * @param object $policy * @param string $ability * @param array $args * @return mixed */ - protected function callPolicyMethod(Model $user, Model $model, object $policy, string $ability, array $args): mixed + protected function callPolicyMethod(Model $user, object $policy, string $ability, array $args): mixed { - $cacheKey = $this->getCacheKey($user, $model, $ability); + $cacheKey = $this->getCacheKey($user, $policy, $args, $ability); if (isset($this->cache[$cacheKey])) { return $this->cache[$cacheKey]; } $result = $policy->{$ability}(...array_merge([$user], $args)); - $this->cache[$cacheKey] = $result; return $result; } - protected function getCacheKey(Model $user, Model $model, string $ability): string + /** + * @param Model $user + * @param object $policy + * @param array $args + * @param string $ability + * @return string + */ + protected function getCacheKey(Model $user, object $policy, array $args, string $ability): string { - return $user->{$user->getKeyName()}.'_'.$model::class.'_'.$ability; + return $user->{$user->getKeyName()}.'_'.hash_hmac('sha512', (string) json_encode($args), config('app.key')).'_'.$ability.'_'.$policy::class; } }