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
|
|
|
/** |
20
|
|
|
* @return null|UserInterface |
21
|
|
|
*/ |
22
|
|
|
public function getUser(): ?UserInterface |
23
|
|
|
{ |
24
|
|
|
try { |
25
|
|
|
$token = $this->security->getToken(); |
26
|
|
|
} catch (\Exception $e) { |
27
|
|
|
$token = null; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if (null === $token) { |
31
|
|
|
return null; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$tokenUser = $token->getUser(); |
35
|
|
|
if (!($tokenUser instanceof BaseUserInterface)) { |
36
|
|
|
return null; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$impersonation = ''; |
40
|
|
|
if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) { |
41
|
|
|
// Symfony > 4.3 |
42
|
|
|
if ($token instanceof SwitchUserToken) { |
43
|
|
|
$impersonatorUser = $token->getOriginalToken()->getUser(); |
44
|
|
|
} else { |
45
|
|
|
$impersonatorUser = $this->getImpersonatorUser(); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if (\is_object($impersonatorUser)) { |
49
|
|
|
$id = method_exists($impersonatorUser, 'getId') ? $impersonatorUser->getId() : null; |
50
|
|
|
$username = method_exists($impersonatorUser, 'getUsername') ? $impersonatorUser->getUsername() : (string) $impersonatorUser; |
51
|
|
|
$impersonation = ' [impersonator '.$username.':'.$id.']'; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
$id = method_exists($tokenUser, 'getId') ? $tokenUser->getId() : null; |
55
|
|
|
|
56
|
|
|
return new User($id, $tokenUser->getUsername().$impersonation); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function getImpersonatorUser() |
60
|
|
|
{ |
61
|
|
|
foreach ($this->security->getToken()->getRoles() as $role) { |
|
|
|
|
62
|
|
|
if ($role instanceof SwitchUserRole) { |
63
|
|
|
return $role->getSource()->getUser(); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return null; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return null|Security |
72
|
|
|
*/ |
73
|
|
|
public function getSecurity(): ?Security |
74
|
|
|
{ |
75
|
|
|
return $this->security; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
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.