1 | <?php declare(strict_types=1); |
||
15 | class Impersonator |
||
16 | { |
||
17 | /** @var Guard $guard */ |
||
18 | protected $guard; |
||
19 | |||
20 | /** @var Repository $config */ |
||
21 | protected $config; |
||
22 | |||
23 | /** @var UserProvider */ |
||
24 | protected $userProvider; |
||
25 | |||
26 | /** @var Store $session */ |
||
27 | protected $session; |
||
28 | |||
29 | /** @var Dispatcher $eventDispatcher */ |
||
30 | protected $eventDispatcher; |
||
31 | |||
32 | /** @var Authenticatable */ |
||
33 | protected $realUser; |
||
34 | |||
35 | /** @var Authenticatable */ |
||
36 | protected $impersonationUser; |
||
37 | |||
38 | /** @var bool */ |
||
39 | protected $isForbidden; |
||
40 | |||
41 | const SESSION_NAME = 'pretend:_switch_user'; |
||
42 | |||
43 | 4 | public function __construct(AuthManager $auth, Repository $config, UserProvider $userProvider, Store $session, Dispatcher $eventDispatcher) |
|
53 | |||
54 | 1 | public function exitImpersonation() |
|
55 | { |
||
56 | 1 | $username = $this->session->get(static::SESSION_NAME); |
|
57 | |||
58 | 1 | if (null === $username) { |
|
59 | return; |
||
60 | } |
||
61 | |||
62 | 1 | $this->session->remove(static::SESSION_NAME); |
|
63 | |||
64 | 1 | $user = $this->retrieveUser($username); |
|
65 | 1 | $realUser = $this->guard->user(); |
|
66 | |||
67 | 1 | $event = new Unimprersonated($realUser, $user); |
|
|
|||
68 | 1 | $this->eventDispatcher->fire($event); |
|
69 | 1 | } |
|
70 | |||
71 | /** |
||
72 | * @throws \HttpException Throw 403 exception if cannot find user |
||
73 | * |
||
74 | * @param string $username |
||
75 | * |
||
76 | * @return Authenticatable |
||
77 | */ |
||
78 | 3 | protected function retrieveUser(string $username): Authenticatable |
|
79 | { |
||
80 | $conditions = [ |
||
81 | 3 | $this->config->get('pretend.impersonate.user_identifier') => $username, |
|
82 | ]; |
||
83 | |||
84 | 3 | $user = $this->userProvider->retrieveByCredentials($conditions); |
|
85 | |||
86 | 3 | if (null === $user) { |
|
87 | 1 | abort(403, 'Cannot find user by this credentials'); |
|
88 | } |
||
89 | |||
90 | 2 | return $user; |
|
91 | } |
||
92 | |||
93 | /** |
||
94 | * @throws \HttpException Throw 403 exception if you try to impersonate yourself |
||
95 | * |
||
96 | * @param string $username Username of user you want to enter impersonate |
||
97 | */ |
||
98 | 3 | public function enterImpersonation(string $username) |
|
117 | |||
118 | 3 | public function isImpersonated(): bool |
|
122 | |||
123 | /** |
||
124 | * @throws \HttpException Throw 403 exception if cannot find data in session |
||
125 | */ |
||
126 | 1 | public function continueImpersonation() |
|
136 | |||
137 | 1 | public function getImpersonatingIdentifier(): string |
|
141 | } |
||
142 |
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: