<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Security\Core\Security;
class DomainVoter extends Voter
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject) : bool
{
// NEW actions don't yet have objects
if(in_array($attribute, ['NEW_DOMAIN'])) {
return true;
}
return in_array($attribute, ['EDIT', 'DELETE'])
&& $subject instanceof \App\Model\Domain;
}
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;
}
switch ($attribute) {
case 'EDIT':
case 'DELETE':
if($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
if($this->security->isGranted('ROLE_POSTMASTER')) {
if(in_array($subject->getDomain(), $user->getDomains())) {
return true;
}
}
break;
case 'NEW_DOMAIN':
if($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
break;
}
return false;
}
}