<?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 App\Entity\User;
use Symfony\Component\Security\Core\Security;
class UserVoter extends Voter
{
const VIEW ="ver";
const EDIT ="editar";
const DELETE = "eliminar";
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT, self::DELETE])) {
return false;
}
// only vote on `User` objects
if (!$subject instanceof User) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$admin = $token->getUser();
// if the user is anonymous, do not grant access
if (!$admin instanceof UserInterface) {
return false;
}
// ROLE_ADMIN can do anything! The power!
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::VIEW:
return $this->canView($subject, $admin);
case self::EDIT:
return $this->canEdit($subject, $admin);
case self::DELETE:
return $this->canDelete($subject, $admin);
}
return false;
}
private function canView(User $user, User $admin)
{
return $admin->getCompany() === $user->getCompany();
}
private function canEdit(User $user, User $admin)
{
// ROLE_ADMIN can do anything! The power!
if ( $admin->getRole() == 'ROLE_CHIEF' || $admin->getRole() == 'ROLE_SUPPLIER_CHIEF') {
return $admin->getCompany() === $user->getCompany();
}else{
return $admin->getId() === $user->getId();
}
}
private function canDelete(User $user, User $admin)
{
if ($admin->getId() !== $user->getId())
{
return $admin->getCompany() === $user->getCompany();
}
return false;
}
}