2016-08-01 21 views
2

用戶使用FOSUserBundle的密碼重置重置密碼後,默認情況下,他被重定向到FOSUserProfile。我想根據他們的角色重定向到不同的路線。這是可能的,如果是的話,怎麼樣? 我做這個代碼,但它重定向所有類型的用戶FOSUserBundle:根據角色重置密碼後的成功目標

namespace Acme\UserBundle\EventListener; 

use FOS\UserBundle\FOSUserEvents; 
use FOS\UserBundle\Event\FormEvent; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; 

/** 
* Listener responsible to change the redirection at the end of the password resetting 
*/ 
class PasswordResettingListener implements EventSubscriberInterface { 
    private $router; 

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

    public static function getSubscribedEvents() { 
     return [ 
      FOSUserEvents::RESETTING_RESET_SUCCESS => 'onPasswordResettingSuccess', 
     ]; 
    } 

    public function onPasswordResettingSuccess(FormEvent $event) { 
     $url = $this->router->generate('homepage'); 
     $event->setResponse(new RedirectResponse($url)); 
    } 
} 

,然後我註冊爲一個服務與

services: 
    acme_user.password_resetting: 
     class: Acme\UserBundle\EventListener\PasswordResettingListener 
     arguments: [ "@router" ] 
     tags: 
      - { name: kernel.event_subscriber } 
+0

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements – pavlovich

回答

0

根據您的Symfony的版本,你可以選擇中所描述的方法之一:http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

例如,你可以使用security.authorization_checker服務:

其注入您服務:

services: 
    acme_user.password_resetting: 
     class: Acme\UserBundle\EventListener\PasswordResettingListener 
     arguments: [ "@router", "@security.authorization_checker" ] 
     tags: 
      - { name: kernel.event_subscriber } 

然後在您的實際服務:

use Symfony\Component\Security\Core\Authorization\AuthorizationChecker; 

/** 
* Listener responsible to change the redirection at the end of the password resetting 
*/ 
class PasswordResettingListener implements EventSubscriberInterface { 
    private $router; 
    private $authorizationChecker; 

    public function __construct(UrlGeneratorInterface $router, AuthorizationChecker $authorizationChecker) { 
     $this->authorizationChecker = $authorizationChecker; 
     $this->router = $router; 
    } 

    public static function getSubscribedEvents() { 
     return [ 
      FOSUserEvents::RESETTING_RESET_SUCCESS => 'onPasswordResettingSuccess', 
     ]; 
    } 

    public function onPasswordResettingSuccess(FormEvent $event) { 

     //$url = $this->router->generate('homepage'); 
     //$event->setResponse(new RedirectResponse($url)); 

     if (false === $this->authorizationChecker->isGranted('ROLE_ADMIN')) { 
      // redirect somewhere 
     } else { 
      // redirect elsewhere 
     } 


    } 
}