1010use CraftCms \Cms \Http \RespondsWithFlash ;
1111use CraftCms \Cms \Support \Flash ;
1212use CraftCms \Cms \User \Actions \GetImpersonationUrlAction ;
13- use CraftCms \Cms \User \Models \User as UserModel ;
1413use Illuminate \Http \JsonResponse ;
1514use Illuminate \Http \Request ;
1615use Illuminate \Support \Facades \Auth ;
@@ -48,7 +47,7 @@ public function impersonate(): Response
4847 Craft::$ app ->getUser ()->setImpersonatorId ($ this ->request ->user ()->id );
4948
5049 try {
51- Auth::login (UserModel:: findOrFail ( $ userId ) );
50+ Auth::login ($ user );
5251 } catch (Throwable ) {
5352 Flash::fail (t ('There was a problem impersonating this user. ' ));
5453
@@ -76,7 +75,7 @@ public function getUrl(GetImpersonationUrlAction $getImpersonationUrlAction): Js
7675
7776 $ this ->enforceImpersonatePermission ($ user );
7877
79- $ url = $ getImpersonationUrlAction (UserModel:: findOrFail ( $ user-> id ) );
78+ $ url = $ getImpersonationUrlAction ($ user );
8079
8180 abort_if ($ url === false , 500 , 'Unable to generate impersonation URL. ' );
8281
@@ -93,19 +92,20 @@ public function withToken(): Response
9392 $ userId = $ this ->request ->integer ('userId ' );
9493 $ prevUserId = $ this ->request ->integer ('prevUserId ' );
9594
96- $ user = UserModel::findOrFail ($ userId );
95+ /** @var User $user */
96+ $ user = Craft::$ app ->getUsers ()->getUserById ($ userId );
9797
9898 Craft::$ app ->getUser ()->setImpersonatorId ($ prevUserId );
9999
100100 try {
101- Auth::login (UserModel:: findOrFail ( $ userId ) );
101+ Auth::login ($ user );
102102 } catch (Throwable ) {
103103 Flash::fail (t ('There was a problem impersonating this user. ' ));
104104
105105 return back ();
106106 }
107107
108- return $ this ->handleSuccessfulLogin (Craft:: $ app -> getUsers ()-> getUserById ( $ user-> id ) );
108+ return $ this ->handleSuccessfulLogin ($ user );
109109 }
110110
111111 private function handleSuccessfulLogin (User $ user ): Response
@@ -132,10 +132,11 @@ private function handleSuccessfulLogin(User $user): Response
132132
133133 private function enforceImpersonatePermission (User $ user ): void
134134 {
135- $ yiiCurrentUser = Craft::$ app ->getUsers ()->getUserById ($ this ->request ->user ()->id );
135+ /** @var ?\craft\elements\User $currentUser */
136+ $ currentUser = $ this ->request ->user ();
136137
137138 abort_unless (
138- Craft::$ app ->getUsers ()->canImpersonate ($ yiiCurrentUser , $ user ),
139+ Craft::$ app ->getUsers ()->canImpersonate ($ currentUser , $ user ),
139140 403 ,
140141 t ('You do not have sufficient permissions to impersonate this user ' ),
141142 );
0 commit comments