When a user logged out from a perticular device I want to logout from all the device he has logged in till now . How I do it in Laravel.
I have used Redis for keeping the userId in Session by installing "predis/predis": "~1.0"
And Here is my controller for SignIn and Logout:
public function postSignIn(Request $request)
{
if (Auth::attempt(['email' => $request['email'], 'password' =>$request['password'] ]) ) {
$redis = \Redis::connection();
$userId=Session::getId();
$redis->sadd('users:sessions:'.$userId,Session::getId());
return redirect()->route('main');
}
return redirect()->back();
}
public function getLogout()
{
$redis = Redis::connection();
$userId=Session::getId();
$userSessions = $redis->smembers('user:sessions:' . $userId);
$currentSession = Session::getId();
foreach ($userSessions as $sessionId) {
if ($currentSession == $sessionId) {
continue;
}
$redis->srem('user:sessions:' . $userId, $sessionId);
$redis->del('laravel:' . $sessionId);
}
Auth::logout();
return redirect()->route('main');
}
It's successfully get logged in and also logged out but it doesn't kill all the session in other devices.
How do I solve the problem?
This method requires the user to provide their current password, which your application should accept through an input form: use Illuminate\Support\Facades\Auth; Auth::logoutOtherDevices(request('password')); When the logoutOtherDevices method is invoked, the user's other sessions will be invalidated entirely, meaning ...
Logging Out To manually log users out of your application, you may use the logout method provided by the Auth facade. This will remove the authentication information from the user's session so that subsequent requests are not authenticated.
So issue was with typo in redis key name,
for write data used
$redis->sadd('users:sessions:'.$userId,Session::getId());
where key's prefix 'users:sessions:'
and for get data used
$redis->srem('user:sessions:' . $userId, $sessionId);
where key's prefix 'user:sessions:'
Thats why code didn't work and dd()
returned empty array.
so correct code looks like this
public function postSignIn(Request $request)
{
if (Auth::attempt(['email' => $request['email'], 'password' =>$request['password'] ]) ) {
$redis = \Redis::connection();
$userId=Session::getId();
$redis->sadd('user:sessions:'.$userId,Session::getId());
return redirect()->route('main');
}
return redirect()->back();
}
public function getLogout()
{
$redis = Redis::connection();
$userId=Session::getId();
$userSessions = $redis->smembers('user:sessions:' . $userId);
$currentSession = Session::getId();
foreach ($userSessions as $sessionId) {
if ($currentSession == $sessionId) {
continue;
}
$redis->srem('user:sessions:' . $userId, $sessionId);
$redis->del('laravel:' . $sessionId);
}
Auth::logout();
return redirect()->route('main');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With