diff --git a/src/Controllers/AdminController.php b/src/Controllers/AdminController.php deleted file mode 100644 index 5f3f115..0000000 --- a/src/Controllers/AdminController.php +++ /dev/null @@ -1,54 +0,0 @@ -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'); - } -} \ No newline at end of file diff --git a/src/Controllers/SwitchUserController.php b/src/Controllers/SwitchUserController.php new file mode 100644 index 0000000..d89c901 --- /dev/null +++ b/src/Controllers/SwitchUserController.php @@ -0,0 +1,62 @@ +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); + } +} \ No newline at end of file diff --git a/src/Traits/UserSwitch.php b/src/Traits/UserSwitch.php index 5d7a917..ad5b8e2 100644 --- a/src/Traits/UserSwitch.php +++ b/src/Traits/UserSwitch.php @@ -7,14 +7,27 @@ namespace Leenooks\Traits; use Session; +use App\Models\User; + trait UserSwitch { + /** + * Return if this is a switched user + * + * @return mixed + */ public function getSwitchedAttribute() { 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; }