<?php
namespace App\Security;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use App\Entity\Admin;
use Doctrine\ORM\EntityManagerInterface;
class AdminUserVoter extends Voter
{
public function __construct(
protected EntityManagerInterface $entityManager,
) {}
protected function supports(string $attribute, mixed $subject):bool
{
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token):bool
{
$user = $token->getUser();
if(!($user instanceof Admin)){
return false;
}
return $this->isAuth($subject,$user,$attribute);
throw new \LogicException('this code should not be reached');
}
private function isAuth($auth, $user, $router)
{
$roles = $user->getRoles();
if(in_array('ROLE_SUPER_ADMIN',$roles)) return true;
$menus = [];
$role = $user->getRole();
$role->getName(); //如果不调用下 role里只有id 没有其他关联属性
$menus = $role->getAdminRoleMenus(); //所有菜单
foreach($menus as $menu){
$action = $menu->getAdminRoleMenuActions();
foreach($action as $v){
if($router == $v->getAction()->getRouterName()) return true;
}
}
return false;
}
}