opnform/app/Http/Controllers/Admin/ImpersonationController.php

64 lines
1.7 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Forms\Form;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ImpersonationController extends Controller
{
public function __construct()
{
$this->middleware('moderator');
}
public function impersonate($identifier) {
$user = null;
if (is_numeric($identifier)) {
$user = User::find($identifier);
} elseif (filter_var($identifier, FILTER_VALIDATE_EMAIL)) {
$user = User::whereEmail($identifier)->first();
} else {
// Find by form slug
$form = Form::whereSlug($identifier)->first();
if ($form) {
$user = $form->creator;
}
}
if (!$user) {
return $this->error([
'message'=> 'User not found.'
]);
} else if ($user->admin) {
return $this->error([
'message' => 'You cannot impersonate an admin.',
]);
}
\Log::warning('Impersonation started',[
'from_id' => auth()->id(),
'from_email' => auth()->user()->email,
'target_id' => $user->id,
'target_email' => $user->id,
]);
// Be this user
if (auth()->user()->moderator) {
$token = auth()->claims([
'impersonating' => true,
'impersonator_id' => auth()->id(),
])->login($user);
} else {
$token = auth()->login($user);
}
return $this->success([
'token' => $token
]);
}
}