Temporary User Switching

Submitted by dawiyo - 9 years ago

Temporarily log in as another user, but switch back to the original user at any time. Inspired by the User Switching plugin for WordPress. I use this for testing data being shown based on user role.

// The simplest implementation to express the concept.


// Routes
Route::get( 'admin/user/switch/start/{id}', 'UserController@user_switch_start' );
Route::get( 'admin/user/switch/stop', 'UserController@user_switch_stop' );


// Inside User Controller
public function user_switch_start( $new_user )
{
  $new_user = User::find( $new_user );
  Session::put( 'orig_user', Auth::id() );
  Auth::login( $new_user );
  return Redirect::back();
}

public function user_switch_stop()
{
  $id = Session::pull( 'orig_user' );
  $orig_user = User::find( $id );
  Auth::login( $orig_user );
  return Redirect::back();
}


// Inside View
<a href="admin/user/switch/start/2">Login as 2</a>

@if( Session::has('orig_user') )
<a href="admin/user/switch/stop">Switch back to 1</a>
@endif


// Simple Test inside View
@if( Auth::id() == 1 )
User 1
@endif

@if( Auth::id() == 2 )
User 2
@endif