FOSUserBundle:根据角色重置密码后的成功目标

时间:2016-08-01 14:13:43

标签: fosuserbundle symfony

用户使用FOSUserBundle的密码重设重置密码后,默认情况下会重定向到FOSUserProfile。我想根据他们的角色重定向到不同的路线。这是可能的,如果可以,怎么样?  我执行此代码,但它重定向所有类型的用户

SOMEDATA .test 01/45/12 2500 THIS IS DATA

然后我将其注册为

服务
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));
    }
}

1 个答案:

答案 0 :(得分: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
        }


    }
}