src/Security/AdminUserVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use App\Entity\Admin;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. class AdminUserVoter extends Voter
  8. {
  9.     public function __construct(
  10.         protected EntityManagerInterface $entityManager,
  11.     ) {}
  12.     protected function supports(string $attributemixed $subject):bool
  13.     {       
  14.         return true;
  15.     }
  16.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token):bool
  17.     {
  18.         $user $token->getUser();
  19.         if(!($user instanceof Admin)){
  20.             return false;
  21.         }   
  22.       
  23.         return $this->isAuth($subject,$user,$attribute);
  24.         throw new \LogicException('this code should not be reached');
  25.     }
  26.     private function isAuth($auth$user$router)
  27.     {       
  28.         $roles $user->getRoles();
  29.         if(in_array('ROLE_SUPER_ADMIN',$roles)) return true;
  30.         $menus = [];
  31.         $role $user->getRole(); 
  32.         $role->getName(); //如果不调用下 role里只有id 没有其他关联属性
  33.         
  34.         $menus $role->getAdminRoleMenus(); //所有菜单
  35.         
  36.         foreach($menus as $menu){
  37.             $action $menu->getAdminRoleMenuActions();   
  38.             foreach($action as $v){                
  39.                 if($router == $v->getAction()->getRouterName()) return true;
  40.             } 
  41.         }       
  42.         return false;
  43.     }
  44. }