<?php
namespace App\Security;
use App\Entity\User;
use App\Entity\TripEntities;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class TripVoter extends Voter
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
const NEW = 'create';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT, self::NEW])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof TripEntities) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if ($this->security->isGranted('KOBEN_1_SUPER ADMIN')) {
return true;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var User $user */
$user = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($user, $loggedUser);
case self::EDIT:
return $this->canEdit($user, $loggedUser);
case self::NEW:
return $this->canCreate($loggedUser);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(User $user, User $loggedUser): bool
{
// if they can edit, they can view
if ($this->canEdit($user, $loggedUser)) {
return true;
}
return true;
}
private function canEdit(User $company, User $loggedUser): bool
{
if ($this->security->isGranted('KOBEN_2_MANAGEMENT')
||$this->security->isGranted('KOBEN_4_HR')
||$this->security->isGranted('KOBEN_3_MANAGER')
||$this->security->isGranted('KOBEN_2_MANAGEMENT')
||$this->security->isGranted('CLIENT_3_HR')
||$this->security->isGranted('CLIENT_2_MANAGEMENT')
||$this->security->isGranted('CLIENT_1_ADMIN')) {
return true;
}
return false;
}
private function canCreate(User $loggedUser): bool
{
if ($this->security->isGranted('KOBEN_2_MANAGEMENT')
||$this->security->isGranted('KOBEN_4_HR')
||$this->security->isGranted('KOBEN_3_MANAGER')
||$this->security->isGranted('KOBEN_2_MANAGEMENT')
||$this->security->isGranted('CLIENT_3_HR')
||$this->security->isGranted('CLIENT_2_MANAGEMENT')
||$this->security->isGranted('CLIENT_1_ADMIN')) {
return true;
}
return false;
}
}