PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, September 3, 2022

[FIXED] How to automatically logout multiple devices with Laravel

 September 03, 2022     authentication, laravel, logout, php     No comments   

Issue

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


Solution

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.



Answered By - miken32
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing