<?php
namespace App\Security\Voter;
use App\Entity\User;
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 UserVoter extends Voter
{
public const USER_VIEW = 'user_view';
public const USER_CREATE = 'user_create';
public const USER_EDIT = 'user_edit';
public const USER_DELETE = 'user_delete';
public const USER_RECOVERY = 'user_recovery';
public const USER_CHANGE_PASSWORD = 'user_change_password';
public const USERS_MANAGE = 'users_manage';
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [
self::USER_VIEW,
self::USER_CREATE,
self::USER_EDIT,
self::USER_DELETE,
self::USER_RECOVERY,
self::USER_CHANGE_PASSWORD,
self::USERS_MANAGE,
]);
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
* @return bool
*/
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;
}
/** @var User $userSubject*/
$userSubject = $subject;
// ROLE_SUPER_ADMIN can do anything!
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
switch ($attribute) {
case self::USER_VIEW:
case self::USER_DELETE:
case self::USER_RECOVERY:
case self::USER_CREATE:
case self::USERS_MANAGE:
return false;
case self::USER_EDIT:
case self::USER_CHANGE_PASSWORD:
return $user->getUsername() === $userSubject->getEmail();
}
throw new \LogicException('This code should not be reached!');
}
}