Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Logout a user from all of his devices

A user is logged in. And he's also already logged in in 3 different computers. Now user changes his password.

I want to do something to log him out from all of his devices. By default if we change password in one device, nothing happens on other devices.

The first thing that comes in mind is to check password in a middle-ware (every request) which is not good and decreases performance significantly.

How can I do this in Laravel 5?

AND what is the best way to do this? How does big sites logout a user from all devices?

like image 876
Sky Avatar asked Jun 16 '15 18:06

Sky


2 Answers

In the latest version of Laravel 5.6

You can do this from

auth()->logoutOtherDevices();

logoutOtherDevices

More Info

like image 188
DsRaj Avatar answered Sep 18 '22 11:09

DsRaj


I did something similar. At first I save sessions in Redis. For each login I save session ID after success auth and relate it with user ID (it's array). If user change password you can remove all user sessions except current (using sessions IDs). If user logout you can remove session id from array of user's sessions. (I think you can use MySQL or other storage for saving relation between user and session ID)

for save session ID I use (when user login )

$redis = \LRedis::connection();
$redis->sadd('user:sessions:' . $userId, Session::getId());

for remove sessions ID from array of user sessions (if user logout or manually logout )

$redis->srem('user:sessions:' . $userId, $sessionId);

remove Laravel session (logout user from other device)

$redis->del('laravel:' . $sessionId);

get all session IDs for user

$redis->smembers('user:sessions:' . $userId);

for logout from all devices use loop

$userSessions = $redis->smembers('user:sessions:' . $userId);
$currentSession = Session::getId()
foreach ($userSessions as $sessionId) {
    if ($currentSession == $sessionId) {
        continue;  //if you want don't remove current session
    }

    $redis->del('laravel:' . $sessionId);
    $redis->srem('user:sessions:' . $userId, $sessionId);
}
like image 44
dyachenko Avatar answered Sep 17 '22 11:09

dyachenko