1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace DH\AuditorBundle\User; |
||
6 | |||
7 | use DH\Auditor\User\User; |
||
8 | use DH\Auditor\User\UserInterface as AuditorUserInterface; |
||
9 | use DH\Auditor\User\UserProviderInterface; |
||
10 | use Exception; |
||
11 | use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
||
12 | use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; |
||
13 | use Symfony\Component\Security\Core\User\UserInterface; |
||
14 | |||
15 | class UserProvider implements UserProviderInterface |
||
16 | { |
||
17 | private TokenStorageInterface $tokenStorage; |
||
18 | |||
19 | public function __construct(TokenStorageInterface $tokenStorage) |
||
20 | { |
||
21 | $this->tokenStorage = $tokenStorage; |
||
22 | } |
||
23 | |||
24 | public function __invoke(): ?AuditorUserInterface |
||
25 | { |
||
26 | $tokenUser = $this->getTokenUser(); |
||
27 | $impersonatorUser = $this->getImpersonatorUser(); |
||
28 | |||
29 | $identifier = null; |
||
30 | $username = null; |
||
31 | |||
32 | if ($tokenUser instanceof UserInterface) { |
||
33 | if (method_exists($tokenUser, 'getId')) { |
||
34 | $identifier = $tokenUser->getId(); |
||
35 | } |
||
36 | |||
37 | $username = $this->getUsername($tokenUser); |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
38 | } |
||
39 | |||
40 | if ($impersonatorUser instanceof UserInterface) { |
||
41 | $impersonatorUsername = $this->getUsername($impersonatorUser); |
||
42 | $username .= '[impersonator '.$impersonatorUsername.']'; |
||
43 | } |
||
44 | |||
45 | if (null === $identifier && null === $username) { |
||
46 | return null; |
||
47 | } |
||
48 | |||
49 | return new User((string) $identifier, $username); |
||
50 | } |
||
51 | |||
52 | private function getUsername(UserInterface $user): string |
||
53 | { |
||
54 | if (method_exists($user, 'getUserIdentifier')) { |
||
55 | return $user->getUserIdentifier(); |
||
56 | } |
||
57 | if (method_exists($user, 'getUsername')) { |
||
58 | return $user->getUsername(); |
||
59 | } |
||
60 | |||
61 | return ''; |
||
62 | } |
||
63 | |||
64 | private function getTokenUser(): ?UserInterface |
||
65 | { |
||
66 | try { |
||
67 | $token = $this->tokenStorage->getToken(); |
||
68 | } catch (Exception $e) { |
||
69 | $token = null; |
||
70 | } |
||
71 | |||
72 | if (null === $token) { |
||
73 | return null; |
||
74 | } |
||
75 | |||
76 | $tokenUser = $token->getUser(); |
||
77 | if ($tokenUser instanceof UserInterface) { |
||
78 | return $tokenUser; |
||
79 | } |
||
80 | |||
81 | return null; |
||
82 | } |
||
83 | |||
84 | private function getImpersonatorUser(): ?UserInterface |
||
85 | { |
||
86 | $token = $this->tokenStorage->getToken(); |
||
87 | |||
88 | if (null !== $token && $token instanceof SwitchUserToken) { |
||
89 | return $token->getOriginalToken()->getUser(); |
||
90 | } |
||
91 | |||
92 | return null; |
||
93 | } |
||
94 | } |
||
95 |