Enable user switching

This commit is contained in:
Deon George
2021-09-27 22:50:47 +10:00
parent fa97fbb0c1
commit ca666e456a
7 changed files with 123 additions and 4 deletions

View File

@@ -0,0 +1,75 @@
<?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);
}
}

View File

@@ -8,6 +8,8 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use App\Traits\UserSwitch;
/**
* Class User
*
@@ -24,7 +26,7 @@ use Laravel\Passport\HasApiTokens;
*/
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory,Notifiable,HasApiTokens;
use HasFactory,Notifiable,HasApiTokens,UserSwitch;
/**
* The attributes that are mass assignable.

31
app/Traits/UserSwitch.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
/**
* Check if users have been switched
*/
namespace App\Traits;
use Illuminate\Support\Facades\Session;
trait UserSwitch
{
/**
* Who is the original user
*
* @return mixed
*/
public function getSwitchedAttribute()
{
return Session::get('orig_user');
}
/**
* Is this user an admin
*
* @return bool
*/
public function isAdmin(): bool
{
return (bool)$this->admin ?? FALSE;
}
}