|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace DH\DoctrineAuditBundle\User; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; |
|
6
|
|
|
use Symfony\Component\Security\Core\Role\SwitchUserRole; |
|
7
|
|
|
use Symfony\Component\Security\Core\Security; |
|
8
|
|
|
use Symfony\Component\Security\Core\User\UserInterface as BaseUserInterface; |
|
9
|
|
|
|
|
10
|
|
|
class TokenStorageUserProvider implements UserProviderInterface |
|
11
|
|
|
{ |
|
12
|
|
|
private $security; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(Security $security) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->security = $security; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function getUser(): ?UserInterface |
|
20
|
|
|
{ |
|
21
|
|
|
try { |
|
22
|
|
|
$token = $this->security->getToken(); |
|
23
|
|
|
} catch (\Exception $e) { |
|
24
|
|
|
$token = null; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
if (null === $token) { |
|
28
|
|
|
return null; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
$tokenUser = $token->getUser(); |
|
32
|
|
|
if (!($tokenUser instanceof BaseUserInterface)) { |
|
33
|
|
|
return null; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
$impersonation = ''; |
|
37
|
|
|
if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) { |
|
38
|
|
|
// Symfony > 4.3 |
|
39
|
|
|
if ($token instanceof SwitchUserToken) { |
|
40
|
|
|
$impersonatorUser = $token->getOriginalToken()->getUser(); |
|
41
|
|
|
} else { |
|
42
|
|
|
$impersonatorUser = $this->getImpersonatorUser(); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
if (\is_object($impersonatorUser)) { |
|
46
|
|
|
$id = method_exists($impersonatorUser, 'getId') ? $impersonatorUser->getId() : null; |
|
47
|
|
|
$username = method_exists($impersonatorUser, 'getUsername') ? $impersonatorUser->getUsername() : (string) $impersonatorUser; |
|
48
|
|
|
$impersonation = ' [impersonator '.$username.':'.$id.']'; |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
$id = method_exists($tokenUser, 'getId') ? $tokenUser->getId() : null; |
|
52
|
|
|
|
|
53
|
|
|
return new User($id, $tokenUser->getUsername().$impersonation); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
private function getImpersonatorUser() |
|
57
|
|
|
{ |
|
58
|
|
|
foreach ($this->security->getToken()->getRoles() as $role) { |
|
|
|
|
|
|
59
|
|
|
if ($role instanceof SwitchUserRole) { |
|
60
|
|
|
return $role->getSource()->getUser(); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return null; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
This function has been deprecated. The supplier of the function has supplied an explanatory message.
The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.