<?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 Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use App\Entity\User as User;
class UserVoter extends Voter
{
const EDIT = 'ROLE_USER_EDIT';
const DELETE = 'ROLE_USER_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, [self::EDIT, self::DELETE])) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$userLogged = $token->getUser();
if (!$userLogged instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
if ($this->decisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) {
return true;
}
// you know $subject is a Post object, thanks to supports
$user = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($user, $userLogged);
case self::DELETE:
return $this->canDelete($user, $userLogged);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit($user, $userLogged)
{
// if they can edit, they can view
if ($this->canDelete($user, $userLogged)) {
return true;
}
return false;
}
private function canDelete($user, $userLogged)
{
// this assumes that the data object has a getOwner() method
// to get the entity of the user who owns this data object
if ($user->getId() == $userLogged->getId()) {
return true;
}
if ($userLogged->hasRole('ROLE_ADMIN') && $user->hasRole('ROLE_USER')) {
return true;
}
return false;
}
}