<?php
namespace App\Modules\TangibleAsset\Security;
use App\Modules\TangibleAsset\Entity\ListingDetails;
use App\Modules\TangibleAsset\Service\AssetAccessService;
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 ListingVoter extends Voter
{
const CREATE_LISTING = 'create_listing';
const UPDATE_LISTING = 'update_listing';
const DELETE_LISTING = 'delete_listing';
static $access = [
self::CREATE_LISTING,
self::UPDATE_LISTING,
self::DELETE_LISTING,
];
private $security;
/**
* @var AssetAccessService
*/
private $assetAccessService;
public function __construct(Security $security, AssetAccessService $assetAccessService)
{
$this->security = $security;
$this->assetAccessService = $assetAccessService;
}
/**
* 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;
}
$listing = $subject;
switch ($attribute) {
case self::CREATE_LISTING:
return $this->canCreate();
case self::UPDATE_LISTING:
return $this->canUpdate($listing, $loginedUser);
case self::DELETE_LISTING:
return $this->canDelete($listing, $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(ListingDetails $listing, UserContract $loginedUser)
{
$asset = $listing->getAsset();
if ($this->assetAccessService->userHasAccess($asset, $loginedUser)) {
return true;
}
return false;
}
private function canDelete(ListingDetails $listing, UserContract $loginedUser)
{
$asset = $listing->getAsset();
if ($this->security->isGranted('ROLE_ADMIN') ||
$this->assetAccessService->userHasAccess($asset, $loginedUser)
) {
return true;
}
return false;
}
}