<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; use App\Models\User; use Symfony\Component\HttpFoundation\RedirectResponse; class UserSwitchController extends Controller { private const redirect = '/'; public function __construct() { $this->middleware('auth'); } /** * Is the user authorised to switch to another user * * @param User $o * @return bool */ private function switch_authorised(User $o): bool { return Auth::user()->admin; } /** * Are we currently in a switch session * * @return bool */ private function switch_session(): bool { return ! Session::get('orig_user'); } /** * Switch the user to another user * * @param User $o * @return RedirectResponse */ public function user_switch_start(User $o): RedirectResponse { if ($this->switch_session() AND $this->switch_authorised($o)) { Session::put('orig_user',Auth::id()); Auth::login($o); } else { abort(404,'Not found'); } return Redirect::to(self::redirect); } /** * Return the user back to the original user * * @return RedirectResponse */ public function user_switch_stop(): RedirectResponse { if ($id = Session::pull('orig_user')) { $uo = User::find($id); Auth::login($uo); } return Redirect::to(self::redirect); } }