<?php
/**
* Created by SAWIT Mateusz Miklewski.
* User: Mateusz
* Date: 2018-03-13
* Time: 13:10
*/
namespace AppBundle\Security\Voters;
use AppBundle\Entity\Policy\Proposal;
use AppBundle\Entity\User\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ProposalVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
/**
* 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)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::VIEW, self::EDIT))) {
return false;
}
// only vote on Post objects inside this voter
if (!$subject instanceof Proposal) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if ($this->decisionManager->decide($token, ['ROLE_AGENCY_LIMITED'])) {
return true;
}
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Proposal object, thanks to supports
/** @var Proposal $proposal */
$proposal = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($proposal, $token);
case self::EDIT:
return $this->canEdit($proposal, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Proposal $proposal, TokenInterface $token) {
if ($this->decisionManager->decide($token, ['ROLE_AGENT'])) {
if($proposal->getInsurer()->getCustomer()->getAgent()->getUser()->getId() == $token->getUser()->getId()) {
return true;
}
}
if($proposal->getInsurer()->getCustomer()->getUser()->getId() == $token->getUser()->getId()) {
return true;
}
return false;
}
private function canEdit(Proposal $proposal, TokenInterface $token) {
return false;
}
}