Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony: how to display a success message after logout

In Symfony, after a user successfully log out, how to display a success message like "you have successfully logged out" ?

like image 836
Francesco Borzi Avatar asked Dec 09 '16 14:12

Francesco Borzi


1 Answers

1) Create a new service to handle the logout success event.

In services.yml add the service:

logout_success_handler:
    class: Path\To\YourBundle\Services\LogoutSuccessHandler
    arguments: ['@security.http_utils']

And add the class, replacing /path/to/your/login with the url of your login page (in the last line of the controller):

<?php

namespace Path\To\YourBundle\Services;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;

class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
    protected $httpUtils;
    protected $targetUrl;

    /**
     * @param HttpUtils $httpUtils
     */
    public function __construct(HttpUtils $httpUtils)
    {
        $this->httpUtils = $httpUtils;

        $this->targetUrl = '/path/to/your/login?logout=success';
    }

    /**
     * {@inheritdoc}
     */
    public function onLogoutSuccess(Request $request)
    {
        $response = $this->httpUtils->createRedirectResponse($request, $this->targetUrl);

        return $response;
    }
}

2) Configure your security.yml to use the custom LogoutSuccessHandler just created:

firewalls:
    # ...
    your_firewall:
        # ...
        logout:
            # ...
            success_handler: logout_success_handler

3) In the twig template of your login page add:

{% if app.request.get('logout') == "success" %}
    <p>You have successfully logged out!</p>
{% endif %}
like image 156
Francesco Borzi Avatar answered Sep 18 '22 11:09

Francesco Borzi