Rename AdminController to SwitchUserController with some optimisations

This commit is contained in:
Deon George 2022-06-28 21:40:13 +10:00
parent b3471f31a0
commit c9cd560b36
3 changed files with 76 additions and 55 deletions

View File

@ -1,54 +0,0 @@
<?php
namespace Leenooks\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Redirect;
use Session;
use App\Models\User;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function switch_authorised($id)
{
return (method_exists(Auth::user(),'isAdmin') && Auth::user()->isAdmin($id)) ? TRUE : FALSE;
}
public function switch_session()
{
return ! Session::get('orig_user');
}
public function user_switch_start($id)
{
if ($this->switch_session() AND $this->switch_authorised($id))
{
$uo = User::find($id);
if (! $uo)
abort(404,'User not found');
Session::put('orig_user',Auth::id());
Auth::login($uo);
}
return Redirect::to('/home');
}
public function user_switch_stop()
{
if ($id = Session::pull('orig_user')) {
$uo = User::find($id);
Auth::login($uo);
}
return Redirect::to('/home');
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace Leenooks\Controllers;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Redirect;
use Session;
use App\Models\User;
class SwitchUserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Determine if the user is authorised to switch to another user
*
* @param User $user
* @return bool
*/
public function switch_authorised(User $user): bool
{
return (method_exists(Auth::user(),'isAdmin') && Auth::user()->isAdmin($user)) ? TRUE : FALSE;
}
/**
* Switch to a different user
*
* @param User $user
* @return mixed
*/
public function switch_start(User $user)
{
if ($user->switched)
abort(403,'User already switched');
if ($this->switch_authorised($user)) {
Session::put('orig_user',Auth::user());
Auth::login($user);
}
return Redirect::to('/home');
}
/**
* Return back from the switch users
*
* @return mixed
*/
public function switch_stop()
{
if ($user = Session::pull('orig_user'))
Auth::login($user);
return Redirect::to(RouteServiceProvider::HOME);
}
}

View File

@ -7,14 +7,27 @@ namespace Leenooks\Traits;
use Session; use Session;
use App\Models\User;
trait UserSwitch trait UserSwitch
{ {
/**
* Return if this is a switched user
*
* @return mixed
*/
public function getSwitchedAttribute() public function getSwitchedAttribute()
{ {
return Session::get('orig_user'); return Session::get('orig_user');
} }
public function isAdmin($id) /**
* If the user record has an admin attribute, we'll return that
*
* @param User|null $user
* @return false|mixed
*/
public function isAdmin(User $user=NULL)
{ {
return isset($this->admin) ? $this->admin : FALSE; return isset($this->admin) ? $this->admin : FALSE;
} }