leenooks/src/Controllers/SwitchUserController.php

62 lines
1.1 KiB
PHP

<?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);
}
}