<?php
namespace App\Security\Voter\Ajustes;
use App\Entity\Ajustes\Usuario;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class UsuarioVoter extends Voter
{
const VIEW = 'USER_VIEW';
const EDIT = 'USER_EDIT';
const DELETE = 'USER_DELETE';
const DUPLICATE = 'USER_DUPLICATE';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW, self::DELETE, self::DUPLICATE])
&& $subject instanceof Usuario;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
// logic to determine if the user can EDIT
// return true or false
return $this->canEdit($subject, $user);
case self::VIEW:
// logic to determine if the user can VIEW
// return true or false
return $this->canView($subject, $user);
case self::DELETE:
// logic to determine if the user can DELETE
// return true or false
return $this->canDelete($subject, $user);
case self::DUPLICATE:
// logic to determine if the user can DUPLICATE
// return true or false
return $this->canDuplicate($subject, $user);
}
return false;
}
private function canView(Usuario $subject,Usuario $user){
if ($this->security->isGranted('ROLE_USR_VIEW'))
return true;
if($subject == $user)
return true;
return false;
}
private function canEdit(Usuario $subject,Usuario $user){
if ($this->security->isGranted('ROLE_USR_EDIT'))
return true;
if($subject == $user)
return true;
return false;
}
private function canDelete(Usuario $subject,Usuario $user){
if ($this->security->isGranted('ROLE_USR_DELETE'))
return true;
return false;
}
private function canDuplicate(Usuario $subject,Usuario $user){
if ($this->security->isGranted('ROLE_USR_DUPLICATE'))
return true;
return false;
}
}