<?php
namespace App\Modules\Contract\Security;
use App\Modules\Contract\Entity\Contract;
use App\Modules\Contract\Service\ContractAccessService;
use App\Modules\User\Entity\User;
use App\Modules\User\Entity\UserContract;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ContractVoter extends Voter
{
const CREATE_CONTRACT = 'create_contract';
const UPDATE_CONTRACT = 'update_contract';
const GET_CONTRACT = 'get_contract';
static $access = [
self::CREATE_CONTRACT,
self::UPDATE_CONTRACT,
self::GET_CONTRACT,
];
private $security;
/**
* @var ContractAccessService
*/
private $contractAccessService;
public function __construct(Security $security, ContractAccessService $contractAccessService)
{
$this->security = $security;
$this->contractAccessService = $contractAccessService;
}
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
if (!in_array($attribute, self::$access)) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
*
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$loginedUser = $token->getUser();
if (!$loginedUser instanceof UserContract) {
// the user must be logged in; if not, deny access
return false;
}
$contract = $subject;
switch ($attribute) {
case self::CREATE_CONTRACT:
return $this->canCreate();
case self::UPDATE_CONTRACT:
return $this->canUpdate($contract, $loginedUser);
case self::GET_CONTRACT:
return $this->canGet($contract, $loginedUser);
}
}
private function canCreate()
{
if ($this->security->isGranted('ROLE_CIRCLE_MEMBER_ADMINISTRATOR') ||
$this->security->isGranted('ROLE_PARTNER_ADMINISTRATOR')
) {
return true;
}
return false;
}
private function canUpdate(Contract $contract, User $loggedInUser)
{
if ($this->contractAccessService->userHasAccess($contract, $loggedInUser)) {
return true;
}
return false;
}
private function canGet(Contract $contract, User $loggedInUser)
{
if ($this->security->isGranted('ROLE_ADMIN') ||
$this->contractAccessService->userHasAccess($contract, $loggedInUser)
) {
return true;
}
return false;
}
}