<?php
/**
* Created by PhpStorm.
* User: mitchellherrijgers
* Date: 17-10-16
* Time: 13:43
*/
namespace WebserviceBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use WmsBundle\Entity\User;
/**
* Class WmsVoter
* @package WebserviceBundle\Security
*/
class WmsVoter extends Voter
{
const WEB = 'web';
const SCANNER = 'scanner';
const BOTH = 'web_or_scanner';
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject): bool
{
return $subject === null;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
*
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
switch ($attribute) {
case self::BOTH:
return $this->hasRole($token, 'ROLE_SCANNER') || $this->hasRole($token, 'ROLE_WEB');
case self::WEB:
return $this->hasRole($token, 'ROLE_WEB');
case self::SCANNER:
return $this->hasRole($token, 'ROLE_SCANNER');
default:
return false;
}
}
/**
* @param TokenInterface $token
* @param $role
* @return bool
*/
private function hasRole(TokenInterface $token, $role): bool
{
/** @var User $user */
$user = $token->getUser();
if ($role === 'ROLE_WEB' && $user->getIsCustomer()) {
return true;
}
foreach ($token->getRoles() as $possibleRole) {
if ($possibleRole->getRole() === $role) {
return true;
}
}
return false;
}
}