clrghouz/app/Http/Controllers/UserSwitchController.php

75 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2021-09-27 12:50:47 +00:00
<?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);
}
}