FOSUserBundle: Registration redirect if logged in

前端 未结 1 1544
南旧
南旧 2020-12-21 12:21

I was wondering what would be the best method to redirect a user who is ALREADY LOGGED IN if they try and access the registration page.

I would prefer a method that

相关标签:
1条回答
  • 2020-12-21 13:10

    I use something like the following..

    namespace Acme\UserBundle\EventSubscriber;
    
    use FOS\UserBundle\Event\GetResponseUserEvent;
    use FOS\UserBundle\FOSUserEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    use Symfony\Component\Security\Core\SecurityContextInterface;
    
    class FOSUserSubscriber implements EventSubscriberInterface
    {
        protected $router;
    
        protected $securityContext;
    
        public function __construct(
            UrlGeneratorInterface $router,
            SecurityContextInterface $securityContext
        )
        {
            $this->router = $router;
            $this->securityContext = $securityContext;
        }
    
        public static function getSubscribedEvents()
        {
            return array(
                FOSUserEvents::REGISTRATION_INITIALIZE  => 'forwardToRouteIfUser',
            );
        }
    
        public function forwardToRouteIfUser(GetResponseUserEvent $event)
        {
            if (!$this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
                return;
            }
    
            $url = $this->router->generate('acme_the_route_to_redirect_to');
    
            $response = new RedirectResponse($url);
    
            $event->setResponse($response);
        }
    } 
    

    With

    parameters:
        acme_user.subscriber.fos_user.class: 
                Acme\UserBundle\EventSubscriber\FOSUserSubscriber
    
    services:
        acme_user.subscriber.fos_user:
            class: %acme_user.subscriber.fos_user.class%
            arguments:
                - @router
                - @security.context
            tags:
                - { name: kernel.event_subscriber 
    
    0 讨论(0)
提交回复
热议问题