|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Lab404\Impersonate\Controllers; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\RedirectResponse; |
|
6
|
|
|
use Illuminate\Http\Request; |
|
7
|
|
|
use Illuminate\Routing\Controller; |
|
8
|
|
|
use Lab404\Impersonate\Services\ImpersonateManager; |
|
9
|
|
|
|
|
10
|
|
|
class ImpersonateController extends Controller |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var ImpersonateManager */ |
|
13
|
|
|
protected $manager; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* ImpersonateController constructor. |
|
17
|
|
|
*/ |
|
18
|
|
|
public function __construct() |
|
19
|
|
|
{ |
|
20
|
|
|
$this->middleware('auth'); |
|
21
|
|
|
|
|
22
|
|
|
$this->manager = app()->make(ImpersonateManager::class); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param int $id |
|
27
|
|
|
* @return RedirectResponse |
|
28
|
|
|
*/ |
|
29
|
|
|
public function take(Request $request, $id) |
|
30
|
|
|
{ |
|
31
|
|
|
// Cannot impersonate yourself |
|
32
|
|
|
if ($id == $request->user()->getKey()) { |
|
33
|
|
|
abort(403); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
// Cannot impersonate again if you're already impersonate a user |
|
37
|
|
|
if ($this->manager->isImpersonating()) { |
|
38
|
|
|
abort(403); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
if (!$request->user()->canImpersonate()) { |
|
42
|
|
|
abort(403); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
// save the origin when set in config |
|
46
|
|
|
if ($this->manager->getLeaveRedirectTo() === 'origin') { |
|
47
|
|
|
session()->put('impersonate_origin', $request->header('referer')); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$user_to_impersonate = $this->manager->findUserById($id); |
|
51
|
|
|
|
|
52
|
|
|
if ($user_to_impersonate->canBeImpersonated()) { |
|
53
|
|
|
if ($this->manager->take($request->user(), $user_to_impersonate)) { |
|
54
|
|
|
$takeRedirect = $this->manager->getTakeRedirectTo(); |
|
55
|
|
|
if ($takeRedirect !== 'back') { |
|
56
|
|
|
return redirect()->to($takeRedirect); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return redirect()->back(); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/* |
|
65
|
|
|
* @return RedirectResponse |
|
66
|
|
|
*/ |
|
67
|
|
|
public function leave() |
|
68
|
|
|
{ |
|
69
|
|
|
if (!$this->manager->isImpersonating()) { |
|
70
|
|
|
abort(403); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
$this->manager->leave(); |
|
74
|
|
|
|
|
75
|
|
|
$leaveRedirect = $this->manager->getLeaveRedirectTo(); |
|
76
|
|
|
|
|
77
|
|
|
// redirect back to origin when set and when session available |
|
78
|
|
|
if ($leaveRedirect === 'origin' && session()->get('impersonate_origin')) { |
|
79
|
|
|
return redirect()->to(session()->get('impersonate_origin')); |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
if ($leaveRedirect !== 'back') { |
|
83
|
|
|
return redirect()->to($leaveRedirect); |
|
84
|
|
|
} |
|
85
|
|
|
return redirect()->back(); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|