<?php
namespace App\Modules\Chat\Security;
use App\Modules\Chat\Entity\Chat;
use App\Modules\User\Entity\UserContract;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ChatVoter extends Voter
{
const GET_ACCESS = 'get_access';
static $access = [
self::GET_ACCESS
];
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* 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 (!in_array($attribute, self::$access)) {
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)
{
$user = $token->getUser();
if (!$user instanceof UserContract) {
// the user must be logged in; if not, deny access
return false;
}
$chat = $subject;
switch ($attribute) {
case self::GET_ACCESS:
return $this->canAccess($chat, $user);
}
}
private function canAccess(Chat $chat, UserContract $user)
{
if ($chat->hasParticipant($user)) {
return true;
}
return false;
}
}