src/AppBundle/Security/UserVoter.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 UserVoter
  10.  *
  11.  * @author savy
  12.  */
  13. class UserVoter extends Voter {
  14.     public const USERS_ALL 'users_all';
  15.     public const ADD 'users_add';
  16.     public const DELETE 'users_delete';
  17.     public const VIEW 'users_view';
  18.     public const MODIFY 'users_modify';
  19.     public const IMPORT 'users_import';
  20.     public function __construct(Security $security, private LoggerInterface $logger) {
  21.         $this->security $security;
  22.     }
  23.     protected function supports($attribute$subject) : bool {
  24.         // if the attribute isn't one we support, return false
  25.         if (!in_array($attribute, [self::USERS_ALL])) {
  26.             return false;
  27.         }
  28.         return true;
  29.     }
  30.     protected function voteOnAttribute($attribute$subjectTokenInterface $token) : bool {
  31.         $user $token->getUser();
  32.         $this->logger->debug('user voter voteOnAttribute: ' print_r($usertrue));
  33.         if (!$user instanceof User) {
  34.             // the user must be logged in; if not, deny access
  35.             return false;
  36.         }
  37.         return match ($attribute) {
  38.             self::USERS_ALL => $this->hasUserRole($user$attribute),
  39.             default => throw new \LogicException('This code should not be reached!'),
  40.         };
  41.     }
  42.     //built-in administrators can add  and standard users cannot. For other users with any other role check permissions
  43.     private function hasUserRole(User $user$attribute) {
  44.         $roleName 'ROLE_' strtoupper($attribute);
  45.         if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted($roleName)) {
  46.             return true;
  47.         } else {
  48.             $this->logger->debug('User does not have users_all permissions');
  49.             return false;
  50.         }
  51.     }
  52. }