Saturday, 18 June 2016

Temporary User Switching Using Sentry Authentication Laravel

Today we are going to learn how we can achieve switching the users in Laravel.

I recently learned this If we are using Sentry Authentication for your Laravel project.

First we need to register the routes for the admin to navigate from "admin to registered user" & "registered user to admin"

Route::get('user/switch/start/{id}',array('as' => 'user.startswitch', 'uses'=>'UserController@user_switch_start')); 
Route::get('user/switch/stop',array('as' => 'user.stopswitch', 'uses'=>'UserController@user_switch_stop'));

Declare methods in your controller for registered routes:
 /*
  * Assign ther user id that we wants to switch.
  * It will store current admin user id and it will be use to switch back to admin user
  *
  * @param $new_user
  */
  public function user_switch_start( $new_user )
  {
      $admin_id = Sentry::getUser()->id;
      $new_user = User::find( $new_user );
   
      $this->switch_user($new_user->id);
      Session::put('admin_id', $admin_id);
      return Redirect::route('dashboard');
  }
 /*
  * Switch back to the admin user & forget the previous user.  
  */
  public function user_switch_stop()
  {
      $admin_id = Session::get('admin_id');
      $admin_user = User::find( $admin_id );
   
      $this->switch_user($admin_user->id); // back to admin login
      Session::forget('admin_id'); // destroy session
      return Redirect::route('user.index');
  } 

/*
  * Authenticate the user based on passed user_id to this.
  * Gives an error message if necessary.
  *
  * @param $user_id
  */
  public function switch_user($user_id)
  {
    try
    {
      $user = Sentry::findUserById($user_id); // Find the user using the user id
      Sentry::login($user, false); // Log the user in
    }
    catch (Cartalyst\Sentry\Users\LoginRequiredException $e)
    {
        echo 'Login is required.'; exit;
    }
    catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
    {
        echo 'User not found.'; exit;
    }
    catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
    {
        echo 'User not activated.'; exit;
    }
    // Following is only needed if throttle is enabled
    catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
    {
        $time = $throttle->getSuspensionTime();
        echo "User is suspended for [$time] minutes."; exit;
    }
    catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
    {
        echo 'User is banned.'; exit;
    }
  }
Create a link for start and stop launching users:
<a href="http://localhost/myapp/user/switch/start/1">Start</a>
<a href="http://localhost/myapp/user/switch/stop>Stop</a>

That's it!

Happy Coding.

Enjoy :)

No comments:

Post a Comment