Skip to content

Commit

Permalink
fix(Realms): Fixed realm cache-key user awareness
Browse files Browse the repository at this point in the history
  • Loading branch information
ambroisemaupate committed Mar 7, 2024
1 parent 4c46346 commit ce71706
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions lib/RoadizCoreBundle/src/Realm/RealmResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,15 @@
use RZ\Roadiz\CoreBundle\Security\Authorization\Voter\RealmVoter;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\String\Slugger\AsciiSlugger;

final class RealmResolver implements RealmResolverInterface
{
private ManagerRegistry $managerRegistry;
private Security $security;
private CacheItemPoolInterface $cache;

public function __construct(ManagerRegistry $managerRegistry, Security $security, CacheItemPoolInterface $cache)
{
$this->managerRegistry = $managerRegistry;
$this->security = $security;
$this->cache = $cache;
public function __construct(
private readonly ManagerRegistry $managerRegistry,
private readonly Security $security,
private readonly CacheItemPoolInterface $cache
) {
}

public function getRealms(?Node $node): array
Expand All @@ -49,9 +46,16 @@ public function denyUnlessGranted(RealmInterface $realm): void
}
}

private function getUserCacheKey(): string
{
return (new AsciiSlugger())
->slug($this->security->getUser()?->getUserIdentifier() ?? 'anonymous')
->__toString();
}

public function getGrantedRealms(): array
{
$cacheItem = $this->cache->getItem('granted_realms');
$cacheItem = $this->cache->getItem('granted_realms_' . $this->getUserCacheKey());
if (!$cacheItem->isHit()) {
$allRealms = $this->managerRegistry->getRepository(Realm::class)->findBy([]);
$cacheItem->set(array_filter($allRealms, fn(RealmInterface $realm) => $this->isGranted($realm)));
Expand All @@ -63,7 +67,7 @@ public function getGrantedRealms(): array

public function getDeniedRealms(): array
{
$cacheItem = $this->cache->getItem('denied_realms');
$cacheItem = $this->cache->getItem('denied_realms_' . $this->getUserCacheKey());
if (!$cacheItem->isHit()) {
$allRealms = $this->managerRegistry->getRepository(Realm::class)->findBy([]);
$cacheItem->set(array_filter($allRealms, fn(RealmInterface $realm) => !$this->isGranted($realm)));
Expand Down

0 comments on commit ce71706

Please sign in to comment.