1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Components Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Silverback\ApiComponentsBundle\EventListener\Jwt; |
15
|
|
|
|
16
|
|
|
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent; |
17
|
|
|
use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Cookie\JWTCookieProvider; |
18
|
|
|
use Silverback\ApiComponentsBundle\Entity\User\AbstractUser; |
19
|
|
|
use Silverback\ApiComponentsBundle\Event\JWTRefreshedEvent; |
20
|
|
|
use Symfony\Component\HttpKernel\Event\ResponseEvent; |
21
|
|
|
use Symfony\Component\Security\Core\Role\RoleHierarchy; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @author Daniel West <[email protected]> |
25
|
|
|
* @author Vincent Chalamon <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
final class JWTEventListener |
28
|
|
|
{ |
29
|
|
|
private RoleHierarchy $roleHierarchy; |
30
|
|
|
private JWTCookieProvider $cookieProvider; |
31
|
|
|
private ?string $token = null; |
32
|
|
|
|
33
|
|
|
public function __construct(RoleHierarchy $roleHierarchy, JWTCookieProvider $cookieProvider) |
34
|
|
|
{ |
35
|
|
|
$this->cookieProvider = $cookieProvider; |
36
|
|
|
$this->roleHierarchy = $roleHierarchy; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function onJWTCreated(JWTCreatedEvent $event): void |
40
|
|
|
{ |
41
|
|
|
/** @var AbstractUser $user */ |
42
|
|
|
$user = $event->getUser(); |
43
|
|
|
$data = $event->getData(); |
44
|
|
|
$rolesAsEntities = $user->getRoles(); |
45
|
|
|
$data['roles'] = $this->roleHierarchy->getReachableRoleNames($rolesAsEntities); |
46
|
|
|
$data['id'] = $user->getId(); |
47
|
|
|
$data['emailAddress'] = $user->getEmailAddress(); |
48
|
|
|
$data['emailAddressVerified'] = $user->isEmailAddressVerified(); |
49
|
|
|
$data['newEmailAddress'] = $user->getNewEmailAddress(); |
50
|
|
|
|
51
|
|
|
$event->setData($data); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function onJWTRefreshed(JWTRefreshedEvent $event): void |
55
|
|
|
{ |
56
|
|
|
$this->token = $event->getToken(); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function onKernelResponse(ResponseEvent $event): void |
60
|
|
|
{ |
61
|
|
|
if (!empty($this->token)) { |
62
|
|
|
$event->getResponse()->headers->setCookie($this->cookieProvider->createCookie($this->token)); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|