src/AppBundle/Security/PortalVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security;
  3. use AppBundle\Entity\ContactPortalUser;
  4. use Symfony\Component\HttpFoundation\RequestStack;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. /**
  8.  * This class handle security access of portal API.
  9.  */
  10. class PortalVoter extends Voter
  11. {
  12.     /**
  13.      * Most API need an access to a LawFirm, so use the PORTAL_ACCESS_LAW_FIRM attribute
  14.      *
  15.      * In API we must provide the query law_firm_id
  16.      *      With annotation @Security('PORTAL_ACCESS_LAW_FIRM')
  17.      * In other cases (command, consumer, ...) we must provide the subject
  18.      *      With Security or AuthorizationChecker service ->isGranted('PORTAL_ACCESS_LAW_FIRM', $lawFirmId)
  19.      */
  20.     const PORTAL_ACCESS_LAW_FIRM 'PORTAL_ACCESS_LAW_FIRM';
  21.     /**
  22.      * @var RequestStack
  23.      */
  24.     private $requestStack;
  25.     /**
  26.      * PortalVoter constructor.
  27.      * @param RequestStack $requestStack
  28.      */
  29.     public function __construct(RequestStack $requestStack)
  30.     {
  31.         $this->requestStack $requestStack;
  32.     }
  33.     /**
  34.      * {@inheritdoc}
  35.      */
  36.     protected function supports($attribute$subject)
  37.     {
  38.         if (self::PORTAL_ACCESS_LAW_FIRM === $attribute) {
  39.             return true;
  40.         }
  41.         return false;
  42.     }
  43.     /**
  44.      * {@inheritdoc}
  45.      */
  46.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  47.     {
  48.         $user $token->getUser();
  49.         if (!$user instanceof ContactPortalUser) {
  50.             return false;
  51.         }
  52.         switch ($attribute) {
  53.             case self::PORTAL_ACCESS_LAW_FIRM:
  54.                 $request $this->requestStack->getCurrentRequest();
  55.                 if (null === $request && null === $subject) {
  56.                     throw new \LogicException('No request found, the subject must be a law firm id');
  57.                 }
  58.                 // We can check this attribute with the law_firm_id as subject,
  59.                 // otherwise we take the law_firm_id in request
  60.                 $lawFirmId $subject ?? $request->query->getInt('law_firm_id');
  61.                 if (null === $lawFirmId || !is_int($lawFirmId)) {
  62.                     return false;
  63.                 }
  64.                 return $user->hasAccessToLawFirm($lawFirmId);
  65.             default:
  66.                 throw new \LogicException('This code should not be reached');
  67.         }
  68.     }
  69. }