<?php
namespace Nellapp\Bundle\SDKBundle\Permission\Security\Voter;
use Nellapp\Bundle\SDKBundle\Auth\Entity\UserInterface;
use Nellapp\Bundle\SDKBundle\Permission\ChannelUserPermissionService;
use Nellapp\Bundle\SDKBundle\Permission\Entity\ChannelResourceInterface;
use Nellapp\Bundle\SDKBundle\Permission\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ChannelUserPermissionResourceVoter extends Voter
{
public function __construct(
private ChannelUserPermissionService $channelUserPermissionService,
private AuthorizationHelper $authorizationHelper,
)
{
}
public function supportsAttribute(string $attribute): bool
{
return str_starts_with($attribute, 'CHANNEL_USER_PERM');
}
public function supportsType(string $subjectType): bool
{
return is_subclass_of($subjectType, ChannelResourceInterface::class);
}
protected function supports(string $attribute, $subject): bool
{
return $this->supportsType($subject::class) && $this->supportsAttribute($attribute);
}
/**
* @param string $attribute
* @param ChannelResourceInterface $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
$channel = $subject->getOwnerChannel();
$channelUserData = $user->getChannelUserDataByChannel($channel);
if ($channelUserData === null) {
return false;
}
if ($this->authorizationHelper->isUserGranted($user, $attribute, $channel)) {
return true;
}
return $this->channelUserPermissionService->hasAccess($channelUserData, $subject, $attribute);
}
}