Wednesday, June 1, 2016

PHP Laravel : How to logout a user from all devices using Redis?

laravel redis



Here is a common scenario like after password reset I/Admin want to logout the user from all device except the device which he logged in while password reset or suppose a user have logged in any many device and the admin want to logout from all of the devices for security purpose for certain reason.

In laravel we can finish the task very easy way using Redis. Lets solve the issue with the following steps.

1. First install the Predis package by composer:

In composer.json file add the following line and run update composer in your cmd.

"require": {
            ...... 
            "predis/predis": "~1.0" ,
            ...... },


2. Create a Session table in database using the following commands:

php artisan session:table
composer dump-autoload 
php artisan migrate

3. Then Download Redis in your PC from the below link and install it in your C:// drive in program files folder.


4. After Redis installed run redis-server.exe file means your server is ready. Now if you run your application.

5. Don't forget to change your .env setting for following driver :

CACHE_DRIVER=redis
SESSION_DRIVER=redis


5. Here is a sample controller code I have shared for logged in using Redis as well as logged out.


public function postSignIn(Request $request)
 { 
     if (Auth::attempt(['email' => $request['email'], 'password' =>$request['password'] ]) ) { 
    //for save session ID I use (when user login )
     $redis = \Redis::connection(); 
     $userId = Auth::user()->id;
     $redis->sadd('users:sessions:' . $userId,Session::getId()); 
     return redirect()->route('main');
   }
  return redirect()->back();
 }

 public function getLogout()
 {
   $redis = \Redis::connection();
   $userId=Auth::user()->id;
   //get all session IDs for user
   $userSessions = $redis->smembers('users:sessions:' . $userId);
   $currentSession = Session::getId();
   //for logout from all devices use loop
     foreach ($userSessions as $sessionId) {
       if ($currentSession == $sessionId) {
       continue; 
     }
   //for remove sessions ID from array of user sessions (if user logout or manually logout )
   $redis->srem('users:sessions:' . $userId, $sessionId);
   //remove Laravel session (logout user from other device)
   $redis->del('laravel:' . $sessionId);
 
   }
  Auth::logout();
  return redirect()->route('main');
 }
6. That's it! When a user logged out from a particular device it will automatically kill all the sessions and logged out from other device also.

Related Articles

0 comments:

Post a Comment