src/AppBundle/Security/AppsVoter.php line 16

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security;
  3. use AppBundle\CSPro\User\User;
  4. use Symfony\Component\Security\Core\Security;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Psr\Log\LoggerInterface;
  8. /**
  9.  * Description of AppsVoter
  10.  *
  11.  * @author savy
  12.  */
  13. class AppsVoter extends Voter {
  14.     public const APPS_ALL 'apps_all';
  15.     public function __construct(Security $security, private LoggerInterface $logger) {
  16.         $this->security $security;
  17.     }
  18.     protected function supports($attribute$subject) : bool {
  19.         // if the attribute isn't one we support, return false
  20.         if (!in_array($attribute, [self::APPS_ALL])) {
  21.             return false;
  22.         }
  23.         return true;
  24.     }
  25.     protected function voteOnAttribute($attribute$subjectTokenInterface $token) : bool {
  26.         $user $token->getUser();
  27.         $this->logger->debug('user voter voteOnAttribute: ' print_r($usertrue));
  28.         if (!$user instanceof User) {
  29.             // the user must be logged in; if not, deny access
  30.             return false;
  31.         }
  32.         return match ($attribute) {
  33.             self::APPS_ALL => $this->hasAppsRole($user$attribute),
  34.             default => throw new \LogicException('This code should not be reached!'),
  35.         };
  36.     }
  37.     //built-in administrators and standard users can. For other users with any other role check permissions
  38.     private function hasAppsRole(User $user$attribute) {
  39.         $roleName 'ROLE_' strtoupper($attribute);
  40.         if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_STANDARD_USER') || $this->security->isGranted($roleName)) {
  41.             return true;
  42.         } else {
  43.             $this->logger->debug('User does not have apps_all permissions');
  44.             return false;
  45.         }
  46.     }
  47. }