<?php
namespace DW\GingerBundle\Security;
use DW\GingerBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
class UserVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
const CREATE = 'create';
const DELETE = 'delete';
private AccessDecisionManagerInterface $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::VIEW, self::EDIT, self::CREATE, self::DELETE))) {
return false;
}
// only vote on user objects inside this voter
if (!$subject instanceof User) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
$user = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($user, $token);
case self::EDIT:
return $this->canEdit($user, $token);
case self::CREATE:
return $this->canCreate($user, $token);
case self::DELETE:
return $this->canDelete($user, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canCreate(User $user, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, ['ROLE_GINGER_USER_CREATE'])) {
return true;
}
return false;
}
private function canView(User $user, TokenInterface $token): bool
{
// if they can edit, they can view
if ($this->canEdit($tag, $token)) {
return true;
}
return false;
}
private function canEdit(User $user, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, ['ROLE_GINGER_USER_EDIT'])) {
return true;
}
return false;
}
private function canDelete(User $user, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, ['ROLE_GINGER_USER_DELETE'])) {
return true;
}
return false;
}
}