|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
/** |
|
4
|
|
|
* /src/ValueResolver/LoggedInUserValueResolver.php |
|
5
|
|
|
* |
|
6
|
|
|
* @author TLe, Tarmo Leppänen <[email protected]> |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace App\ValueResolver; |
|
10
|
|
|
|
|
11
|
|
|
use App\Entity\User; |
|
12
|
|
|
use App\Security\UserTypeIdentification; |
|
13
|
|
|
use Generator; |
|
14
|
|
|
use Lexik\Bundle\JWTAuthenticationBundle\Exception\MissingTokenException; |
|
15
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
16
|
|
|
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface; |
|
17
|
|
|
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; |
|
18
|
|
|
use Throwable; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Class LoggedInUserValueResolver |
|
22
|
|
|
* |
|
23
|
|
|
* Example how to use this within your controller; |
|
24
|
|
|
* |
|
25
|
|
|
* #[Route(path: 'some-path')] |
|
26
|
|
|
* #[IsGranted(AuthenticatedVoter::IS_AUTHENTICATED_FULLY)] |
|
27
|
|
|
* public function someMethod(\App\Entity\User $loggedInUser): Response |
|
28
|
|
|
* { |
|
29
|
|
|
* ... |
|
30
|
|
|
* } |
|
31
|
|
|
* |
|
32
|
|
|
* This will automatically convert your security user to actual User entity that |
|
33
|
|
|
* you can use within your controller as you like. |
|
34
|
|
|
* |
|
35
|
|
|
* @package App\ValueResolver |
|
36
|
|
|
* @author TLe, Tarmo Leppänen <[email protected]> |
|
37
|
|
|
*/ |
|
38
|
|
|
class LoggedInUserValueResolver implements ValueResolverInterface |
|
39
|
|
|
{ |
|
40
|
121 |
|
public function __construct( |
|
41
|
|
|
private readonly UserTypeIdentification $userService, |
|
42
|
|
|
) { |
|
43
|
121 |
|
} |
|
44
|
|
|
|
|
45
|
121 |
|
public function supports(ArgumentMetadata $argument): bool |
|
46
|
|
|
{ |
|
47
|
121 |
|
$output = false; |
|
48
|
|
|
|
|
49
|
|
|
// only security user implementations are supported |
|
50
|
121 |
|
if ($argument->getName() === 'loggedInUser' && $argument->getType() === User::class) { |
|
51
|
42 |
|
$securityUser = $this->userService->getSecurityUser(); |
|
52
|
|
|
|
|
53
|
42 |
|
if ($securityUser === null && $argument->isNullable() === false) { |
|
54
|
12 |
|
throw new MissingTokenException('JWT Token not found'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
30 |
|
$output = true; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
109 |
|
return $output; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @throws Throwable |
|
65
|
|
|
* |
|
66
|
|
|
* @return Generator<User|null> |
|
67
|
|
|
*/ |
|
68
|
114 |
|
public function resolve(Request $request, ArgumentMetadata $argument): Generator |
|
69
|
|
|
{ |
|
70
|
114 |
|
if (!$this->supports($argument)) { |
|
71
|
76 |
|
return []; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
28 |
|
yield $this->userService->getUser(); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|