<?php
namespace Bidcoz\Bundle\CoreBundle\Security\Authorization\Voter;
use Bidcoz\Bundle\CoreBundle\Entity\Organization;
use Bidcoz\Bundle\CoreBundle\Services\OrganizationManager;
use Bidcoz\Bundle\CoreBundle\Services\PermissionManager;
use RS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @DI\Service
* @DI\Tag("security.voter")
*/
class OrganizationVoter extends Voter
{
const VIEW = 'VIEW';
const MANAGE = 'MANAGE';
const EMAIL = 'EMAIL';
const CONTACTS = 'CONTACTS';
const ADMIN = 'ADMIN';
protected OrganizationManager $organizationManager;
protected PermissionManager $permissionManager;
private RequestStack $requestStack;
/**
* @DI\InjectParams({
* "organizationManager" = @DI\Inject("organization_manager"),
* "permissionManager" = @DI\Inject("permission_manager"),
* "requestStack" = @DI\Inject("request_stack")
* })
*/
public function __construct(
OrganizationManager $organizationManager,
PermissionManager $permissionManager,
RequestStack $requestStack
)
{
$this->organizationManager = $organizationManager;
$this->permissionManager = $permissionManager;
$this->requestStack = $requestStack;
}
protected function supports($attribute, $subject)
{
return $subject instanceof Organization && in_array($attribute, [self::VIEW, self::MANAGE, self::EMAIL, self::CONTACTS, self::ADMIN]);
}
protected function voteOnAttribute($attribute, $organization, TokenInterface $token)
{
if (self::VIEW === $attribute && $organization->isActive() && ($organization->isApproved() || $organization->isDirectoryOnly())) {
return true;
}
$route = $this->requestStack->getMainRequest() ? $this->requestStack->getMainRequest()->get('_route') : null;
if ('organization_register_user' === $route) {
return true;
}
// make sure there is a user object (i.e. that the user is logged in)
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($this->organizationManager->isOrganizationAdmin($organization, $user)) {
return true;
}
// If not an org admin, no access to any manage resources
if (self::MANAGE === $attribute) {
return false;
}
// User is logged in, not an admin, see if they have the ability to view any of the orgs campaigns
if (count($this->permissionManager->getUserGroupMembershipForOrganization($organization, $user))) {
return true;
}
return false;
}
}