<?php
namespace MedBrief\MSR\Security\Voter;
use MedBrief\MSR\Entity\Firm;
use MedBrief\MSR\Entity\User;
use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class FirmVoter extends Voter
{
public const EDIT = 'EDIT';
public const VIEW = 'VIEW';
public const DELETE = 'DELETE';
public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
{
}
#[Override]
protected function supports($attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [
self::EDIT,
self::VIEW,
self::DELETE,
])
&& $subject instanceof Firm;
}
#[Override]
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
/** @var Firm $firm */
$firm = $subject;
if ($this->authorizationChecker->isGranted('ROLE_ADMIN', $user)) {
return true;
}
if ($attribute === self::VIEW) {
// A technical admin role on ONE clientArea is all that's required to view the firm.
foreach ($firm->getClientAreas() as $clientArea) {
if ($this->authorizationChecker->isGranted(sprintf('ROLE_ACCOUNT_%1$s_TECHNICAL_ADMIN', $clientArea->getId()), $clientArea) === true) {
return true;
}
}
}
return false;
}
}