<?php
namespace MedBrief\MSR\Security\Voter;
use MedBrief\MSR\Entity\HelpArticle;
use MedBrief\MSR\Entity\User;
use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class HelpArticleVoter extends Voter
{
public const CREATE = 'CREATE';
public const UPDATE = 'UPDATE';
public const VIEW = 'VIEW';
public const DELETE = 'DELETE';
public const ADMINISTRATION = 'ADMINISTRATION';
public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
{
}
#[Override]
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [
self::CREATE,
self::UPDATE,
self::VIEW,
self::DELETE,
self::ADMINISTRATION,
])
&& $subject instanceof HelpArticle;
}
#[Override]
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
/** @var HelpArticle $helpArticle */
$helpArticle = $subject;
// ... (check conditions and return true to grant permission) ...
return match ($attribute) {
self::CREATE, self::UPDATE, self::DELETE => $this->canCreate($user),
self::VIEW => $this->canView($user, $helpArticle),
self::ADMINISTRATION => $this->isAdministration(),
default => false,
};
}
protected function canCreate(User $user)
{
// MEDBRIEF HELP ADMIN
return $this->authorizationChecker->isGranted('ROLE_HELP_ADMIN');
}
protected function canView(User $user, HelpArticle $helpArticle)
{
// MEDBRIEF ADMIN
if ($this->isAdministration()) {
return true;
}
// No one except admins should see hidden articles
if ($helpArticle->getHidden() === true) {
return false;
}
// If the user is a client level user...
// they should only ever see client content types.
if ($user->isAccountAdministrator()
|| $user->isAccountProjectManager()
|| $user->isAccountTechnicalAdmin()
|| $user->isProjectManager()
|| $user->isAccountSorter()
) {
// If the user has both a client level and matter level access, we use their client level access to determine which
// articles they see.
return $helpArticle->isClientContentType();
}
// Third Party Articles can be seen by everyone else
return $helpArticle->isThirdPartyContentType();
}
/**
* Returns true if the user has an admin related role
*
* @return bool
*/
protected function isAdministration()
{
// MEDBRIEF ADMIN
return $this->authorizationChecker->isGranted('ROLE_ADMIN');
}
}