<?php
namespace App\Security\Voter;
use App\Entity\Client\Client;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ClientVoter extends Voter
{
private const VIEW = 'view';
private const EDIT = 'edit';
private const SELECT = 'select';
private const DELETE = 'delete';
/**
* @var Security
*/
private Security $security;
/**
* ClientVoter constructor.
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @inheritDoc
*/
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT, self::DELETE, self::SELECT], true)) {
return false;
}
// only vote on `Client` objects
if ($subject instanceof Client === false) {
return false;
}
return true;
}
/**
* @inheritDoc
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute) {
case self::VIEW:
return $this->canSee($subject, $loggedUser);
case self::EDIT:
case self::DELETE:
return $this->canEdit($subject, $loggedUser);
case self::SELECT:
return $this->canSelect($subject, $loggedUser);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param Client $client
* @param User $loggedUser
* @return bool
*/
private function canSee(Client $client, User $loggedUser): bool
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
if ($this->security->isGranted('ROLE_CAN_SEE_ALL_CLIENTS')) {
return true;
}
if ($this->security->isGranted('ROLE_ADMIN_MANAGER')) {
if ($loggedUser->getClient()->getId() === $client->getId()) {
return true;
}
if ($loggedUser->getClientGroup() !== null && $client->getClientGroup() !== null) {
if ($loggedUser->getClientGroup() === $client->getClientGroup()) {
// client is from allowed group of clients of logged user
return true;
}
}
}
if ($this->security->isGranted('ROLE_CAN_SEE_CLIENT_DETAIL') && $loggedUser->getClient()->getId() === $client->getId()) {
return true;
}
return false;
}
/**
* @param Client $client
* @param User $loggedUser
* @return bool
*/
private function canEdit(Client $client, User $loggedUser): bool
{
if ($this->canSee($client, $loggedUser) && $this->security->isGranted('ROLE_CAN_EDIT_CLIENT')) {
return true;
}
return false;
}
/**
* @param Client $client
* @param User $loggedUser
* @return bool
*/
private function canSelect(Client $client, User $loggedUser): bool
{
if (!$this->security->isGranted('ROLE_CAN_ASSIGN_CLIENT')
|| !$this->canSee($client, $loggedUser)
) {
return false;
}
return true;
}
}