一直以来使用其他框架如TP何CI都做过如题的需求,也轻松就可以实现。最近也想在SF2上实现出来,写一个adminBundle自动化创建后台提供常用功能。不过遇上了问题如下:
由于要全局后台检测用户访问的权限,我便监听了controller .在每个controller触发之前获取request 的信息,检测该用户是否给予了相应权限。代码如下:
class RunActListener {
protected $securityContext;
public function __construct(SecurityContextInterface $securityContext)
$this->securityContext = $securityContext;
}
public function onRunAct(FilterControllerEvent $event) {
$request = $event->getRequest();
$ajax = $request->isXmlHttpRequest();
if (preg_match('/^\/admin/', $request->getRequestUri())) {
$routeName = $request->get('_route');
if ($this->securityContext->isGranted(array($routeName))) {
} else {
$reffeer = $request->server->get('HTTP_REFERER');
$data['info'] = '您没有权限操作!';
$data['status'] = false;
if ($ajax) {
$event->setController(
function() use ($data) {
return new JsonResponse($data);
});
} else {
$event->setController(
function() use ($data) {
return new Response('<b>您没有足够的访问权限!</b><script>setTimeout("window.history.back(-1)",2000)</script>');
});
//。。。。。
然后我在后台layout都引入了2个render ,菜单和面包屑代码如下:
<nav id="navigation" class="collapse">
<ul>
{{ render(controller( 'CwpUtilBundle:Menu:showMenu')) }}
</ul>
</nav>
</aside>
<p id="sidebar-separator"></p>
<section id="main" class="clearfix">
<p id="main-header" class="page-header">
{{ render(controller( 'CwpUtilBundle:Menu:showCrumb')) }}
</p>
<p id="main-content">
{% block main %}
{% endblock %}
</p>
</section>
这样了发起了2个sub_request ,但我的需求要在sub_request 里获取parent request的url 来实现我的面包屑和菜单。在SF当中有些麻烦,有大神建议用get request stack 在sub action 中
/**
* 显示面包屑
* @return type
*/
public function showCrumbAction() {
$request = $this->container->get('request');
$path = $request->server->get('REDIRECT_URL');
$path_arr = explode('/', $path);
$path_len = count($path_arr);
$top_index = (int) ($path_len - 2);
$path_top = $path_arr[$top_index];
$route_arr = $this->get('router')->match($path);
$route = $route_arr['_route'];
$em = $this->getDoctrine()->getManager();
//获取菜单结果集
$top_menu = $em->getRepository('CwpUtilBundle:Menu')->findOneByNode($path_top);
$sec_menu = $em->getRepository('CwpUtilBundle:Menu')->findOneByNode($route);
return $this->render('CwpUtilBundle:Layout:crumb.html.twig', array(
'top_menu' => $top_menu,
'sec_menu' => $sec_menu,
));
}
我尝试在以上action get request_stack ,但是一旦我get,似乎就在这个action 发起了request ,我的listener就被触发,然后执行了else ,跳转到提示 你的权限不足。我表示很茫然,不知道什么原因。
伊谢尔伦2017-05-16 16:46:27
监听kernel.controller的那个listener,加个判断,仅在主请求时才检查权限就可以了:
if ($event->isMasterRequest()) {
// 才做检查
}
2.3的FilterControllerEvent没这个方法,参考这个逻辑自己写就可以了:
https://github.com/symfony/symfony/blob/2.7/src/Symfony/Component/HttpKernel/Event/KernelEvent.php#L100