Home > Blockchain >  How to automatically logout multiple devices with Laravel
How to automatically logout multiple devices with Laravel

Time:08-15

I am using Laravel 9 and I want to log a user out automatically (without refresh) if they try to log in through multiple devices. I am using the the following code (inside the loginController.php) and it works but the user needs to refresh in order to get logged out:

protected function authenticated()
    {
        Auth::logoutOtherDevices(request('password'));
    }

Is there any way to automaticall log the user out at multiple login (without refresh) ? .. I am thinking about Ajax ? events ? .

Thanks

CodePudding user response:

If you already have a websockets infrastructure set up on this site, then I agree that's the easiest method. Otherwise it's overkill for such a simple task.

Set up a route like this:

Route::get("/auth/check", fn () => Auth::check ? response("ok") : response("fail", 401))->name("auth.check");

This will return a 401 error code is the user isn't authenticated.

Then on the client side (I'm assuming you're in a Blade template here) do something like this:

const authCheck = function() {
    $.ajax({
        url: @json(route("auth.check")),
        error: function(xhr) {
            if (xhr.status === 401) {
                location.reload();
            }
        }
    });
}

// run it every 60 seconds
setInterval(authCheck, 60000);

This just defines a function that calls your new route. If it fails due to an authentication error, it reloads the page. This will allow Laravel to redirect the user to the login page.


If you're not using jQuery, your script might look like this:

const authCheck = function() {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 401) {
            location.reload();
        }
    }
    xhr.open("GET", @json(route("auth.check")));
    xhr.send();
}

setInterval(authCheck, 60000);

No, none of this will work if the client has Javascript disabled; nor will websockets. If you want to work on the client side, you are at the mercy of the client.

CodePudding user response:

You would have to do this using websockets. You can use Laravel Echo for this, and create a broadcast event called something like RefreshBrowser.

Then in your Javascript, you'd listen for the event and trigger a browser refresh via JS when that event is called.

  • Related