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

58 lines
1.5 KiB
PHP
Raw Normal View History

2022-09-20 19:59:52 +00:00
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Forms\Form;
use App\Models\User;
class ImpersonationController extends Controller
{
public function __construct()
{
2024-01-19 13:27:04 +00:00
$this->middleware('moderator');
2022-09-20 19:59:52 +00:00
}
2024-02-23 10:54:12 +00:00
public function impersonate($identifier)
{
2022-09-20 19:59:52 +00:00
$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;
}
}
2024-02-23 10:54:12 +00:00
if (! $user) {
2024-01-19 13:27:04 +00:00
return $this->error([
2024-02-23 10:54:12 +00:00
'message' => 'User not found.',
2024-01-19 13:27:04 +00:00
]);
2024-02-23 10:54:12 +00:00
} elseif ($user->admin) {
2024-01-19 13:27:04 +00:00
return $this->error([
'message' => 'You cannot impersonate an admin.',
]);
}
2024-02-23 10:54:12 +00:00
\Log::warning('Impersonation started', [
2024-01-19 13:27:04 +00:00
'from_id' => auth()->id(),
'from_email' => auth()->user()->email,
'target_id' => $user->id,
'target_email' => $user->id,
2022-09-20 19:59:52 +00:00
]);
2024-01-24 16:45:29 +00:00
$token = auth()->claims(auth()->user()->admin ? [] : [
'impersonating' => true,
'impersonator_id' => auth()->id(),
])->login($user);
2022-09-20 19:59:52 +00:00
return $this->success([
2024-02-23 10:54:12 +00:00
'token' => $token,
2022-09-20 19:59:52 +00:00
]);
}
}