3
votes

I'm trying to add some logic to the logout function of our existing laravel site (laravel 5.2) but It's not quite as cut and dry as logging in.

The existing logout for the client side works fine, but all I want to do is add a call to my Cognito instance to log the user out of their cognito session. Basically, when the user clicks logout then I want to log them out of the website as it already does but also hit my logout endpoint for cognito

My confusion comes from the fact that the existing routes and controller for auth don't quite match up.

routes.api.php

Route::get('logout', 'API\Auth\AuthController@getLogout');

routes.auth.php

Route::get('logout', 'Auth\AuthController@getLogout')
    ->name('auth.logout');

Auth/AuthController.php (in my constructor)

$this->middleware('guest', ['except' => 'getLogout']);

My logout link hits site/logout and it's definitely logging the user out but I want to put my call to the endpoint in the right place. I also want to make sure I flush or destroy the session on successful logout

I've been told recently I could possibly (and likely should) add a listener for the logout event and do my call there.

How exactly would I do that in this instance, and where exactly would it go?

1

1 Answers

9
votes

In your EventServiceProvider you can attach a listener to the logout event and handle all the logout logic in your listener.

protected $listen = [
    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],
];

Then you can create your LogSuccessfulLogout listener inside App\Listeners:

    namespace App\Listeners;
    use Illuminate\Auth\Events\Logout;

    class LogSuccessfulLogout
    {
        /**
         * Create the event listener.
         *
         * @return void
         */
        public function __construct()
        {
            //
        }

        /**
         * Handle the event.
         *
         * @param  Logout  $event
         * @return void
         */
        public function handle(Logout $event)
        {
            // Do your logic
        }
    }

Source: https://laravel.com/docs/5.2/authentication#events