Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Dynamic Logout Target?

Tags:

php

symfony

I have a working Symfony2 application that properly logs users in and out, and when logging out it properly redirects the user to the home page.

I'd like to keep them on their current page when the log out, only without their logged-in privileges.

My question is:

Can I dynamically set the page the user is directed to when they log out?

like image 204
Pat Zabawa Avatar asked Dec 09 '13 01:12

Pat Zabawa


2 Answers

What you need is a logout success handler.

Define the logout handler in the security.yml:

security:
    firewalls:
        admin_area:
            logout:
                success_handler: acme.security.logout_success_handler

And the handler goes like this:

namespace Acme\Bundle\SecurityBundle\Handler;

use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerAware;

class LogoutSuccessHandler extends ContainerAware implements LogoutSuccessHandlerInterface
    {
    public function onLogoutSuccess(Request $request)
    {
        // dynamic route logic

        return new RedirectResponse($this->container->get('router')->generate('dynamic_route_name'));
    }
}

Btw... Please remove the unwanted imports and Hope this helps! :D

Here is the services.yml

services:
    acme.security.logout_success_handler:
        class: Acme\Bundle\SecurityBundle\Handler\LogoutSuccessHandler
        calls:
            - [ setContainer, [ @service_container ] ]
like image 98
Chathushka Avatar answered Nov 18 '22 14:11

Chathushka


I needed a Logout Success Handler, and this is how I implemented it:

security.yml:

logout:
    success_handler: acme.security.logout_success_handler

config.yml:

services:
    acme.security.logout_success_handler:
        class: Acme\DefaultBundle\Handler\LogoutSuccessHandler

Symfony/src/Acme/DefaultBundle/Handler/LogoutSuccessHandler.php:

<?php

namespace Acme\DefaultBundle\Handler;

use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerAware;

class LogoutSuccessHandler extends ContainerAware implements LogoutSuccessHandlerInterface
{
    public function onLogoutSuccess(Request $request)
    {
        $target_url = $request->query->get('target_url')
                      ? $request->query->get('target_url')
                      : "/";
        return new RedirectResponse($target_url);
    }
}
like image 33
Pat Zabawa Avatar answered Nov 18 '22 15:11

Pat Zabawa