<?php
namespace App\Security;
use AppBundle\Entity\CompanyAssetInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use App\Entity\User;
class BaseCrudVoter extends Voter
{
const ROLE_SUPER = 'ROLE_SUPER_ADMIN';
const ROLE_ALL = 'ROLE_DEFAULT_ALL';
const ROLE_READ = 'ROLE_DEFAULT_READ';
const ROLE_WRITE = 'ROLE_DEFAULT_WRITE';
const ROLE_DELETE = 'ROLE_DEFAULT_DELETE';
const GRANT_READ = 'read';
const GRANT_WRITE = 'write';
const GRANT_DELETE = 'delete';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::GRANT_READ, self::GRANT_WRITE, self::GRANT_DELETE))) {
return false; // abstain
}
return true; // supports
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
// ROLE_SUPER_ADMIN can do anything! The power!
if ($this->decisionManager->decide($token, array(static::ROLE_SUPER))) {
return true;
}
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute) {
case self::GRANT_READ:
return $this->canRead($subject, $user);
case self::GRANT_WRITE:
return $this->canWrite($subject, $user);
case self::GRANT_DELETE:
return $this->canDelete($subject, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canDoAll($subject, User $user)
{
if ($user->hasRole(static::ROLE_ALL)) {
return true;
}
return false;
}
private function canRead($subject, User $user)
{
// if they can do all, they can show
if ($this->canDoAll($subject, $user)) {
return true;
}
if ($user->hasRole(static::ROLE_READ)) {
return true;
}
return false;
}
private function canWrite($subject, User $user)
{
// if they can do all, they can edit
if ($this->canDoAll($subject, $user)) {
return true;
}
if ($user->hasRole(static::ROLE_WRITE)) {
return true;
}
return false;
}
private function canDelete($subject, User $user)
{
// if they can do all, they can delete
if ($this->canDoAll($subject, $user)) {
return true;
}
if ($user->hasRole(static::ROLE_DELETE)) {
return true;
}
return false;
}
}