0

我正在听 security.authentication.success 事件。每次客户登录时,我都需要检查他是否仍然获得主要信息。如果没有,那么我想将他重定向到创建表单。它运行良好,但我可以通过哪种方式重定向事件?简单地返回一个重定向对象是行不通的。

服务:

applypie_userbundle.newuser_listener:
  class: Applypie\Bundle\UserBundle\EventListener\NewUserListener
  arguments: [@router]
  tags:
    - { name: kernel.event_listener, event: security.authentication.success, method: onLogin }

听众:

namespace Applypie\Bundle\UserBundle\EventListener;

use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;

class NewUserListener
{
    protected $context;
    protected $router;

    public function __construct(Router $router)
    {
        $this->router  = $router;
    }

    /**
     * @param AuthenticationEvent $event
     *
     * if current user neither have an applicant row or an company row, redirect him to create applicant row
     */
    public function onLogin(AuthenticationEvent $event)
    {

        $user = $event->getAuthenticationToken()->getUser();

        if(!$user->getApplicant() && !count($user->getCompanies()))
        {
            return new RedirectResponse($this->router->generate('applypie_user_applicant_create'));
        }

    }
}
4

1 回答 1

1

长话短说,是的,您正在收听正确的事件,但是...有人在等待您的方法返回吗?...不!

我现在无法对此进行测试,但这是我的想法:

安全.yml

firewalls:
    main:
        pattern: ^/
        form_login:
            success_handler: my.security.login_handler

服务.yml

services:
    my.security.login_handler:
        class:  Applypie\Bundle\UserBundle\EventListener\NewUserListener
        arguments:  [@router]

新用户监听器

namespace Applypie\Bundle\UserBundle\EventListener;

use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;


class NewUserListener implements AuthenticationSuccessHandlerInterface
{
    protected $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    protected function getResponse($name)
    {
        $url = $this->router->generate($name);
        $response = new RedirectResponse($url);

        return $response;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        $route = 'user_home';

        if(!$user->getApplicant() && empty($user->getCompanies())) {

            $route = 'applypie_user_applicant_create';

        }

        return $this->getResponse($route);
    }
}

资料来源:

http://api.symfony.com/2.3/Symfony/Component/Security/Http/Authentication/AuthenticationSuccessHandlerInterface.html

在 symfony2 登录成功之后和重定向之前做些什么?

于 2013-09-25T12:50:41.377 回答