我想添加一个按用户数据重定向的流程 例如,它是一个积分系统 如果用户没有积分,则强制重定向到静态页面。
我在脑海中想要添加构建公共BaseController函数的过程。
class BaseController extends Controller
{
public function __construct()
{
if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->container->get('security.context')->getToken()->getUser();
$manager = $this->container->get('doctrine')->getManager();
if (! $manager->getRepository('MyUserBundle:User')->hasPoints($user))
return new RedirectResponse($this->container->get('router')->generate('static_page_route'));
}
}
但我不能使用容器。
错误:在非对象上调用成员函数get()
争议点:
1.如何在构造函数中使用用户对象
2.根据用户数据的状态(如点),是否有更简单的重定向过程方法?
(虽然我仍然不知道ACL细节,但是通过用户点状态更改角色。)
public function onKernelRequest(GetResponseEvent $event){
if (!$this->securityContext->getToken()) {
return;
}
$isUser = $this->securityContext->isGranted('ROLE_USER');
if (!$isUser) {
return;
}
$user = $this->securityContext->getToken()->getUser();
$request = $event->getRequest();
$_route = $request->attributes->get('_route');
if (! $user->hasPoints() && $_route != 'static_page_route') {
// exit; <= page rendering is done even if process exit.
// Redirect process be called after rendering?
$redirectUrl = $this->router->generate('static_page_route');
$event->setResponse(new RedirectResponse($redirectUrl)); // <= `The page isn't redirecting properly` error now.
}
}
答案 0 :(得分:0)
一个解决方案:
<?php
namespace My\ExampleBundle\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
class BeforeController {
protected $securityContext;
protected $router;
public function setRouter(Router $router){
$this->router = $router;
}
public function setSecurityContext(SecurityContext $securityContext){
$this->securityContext = $securityContext;
}
public function onKernelRequest(GetResponseEvent $event){
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) { return; }
if (! $this->securityContext->getToken()) { return; }
if (! $this->securityContext->isGranted('ROLE_USER')) { return; }
$user = $this->securityContext->getToken()->getUser();
$request = $event->getRequest();
$_route = $request->attributes->get('_route');
if (! $user->hasPoints() && $_route != 'static_page_route') {
$redirectUrl = $this->router->generate('static_page_route');
$event->setResponse(new RedirectResponse($redirectUrl));
}
}
}