Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
18 / 18 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| AddAuthenticationCookie | |
100.00% |
18 / 18 |
|
100.00% |
2 / 2 |
3 | |
100.00% |
1 / 1 |
| getSubscribedEvents | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| onApieResponseCreated | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | namespace Apie\Common\Events; |
| 3 | |
| 4 | use Apie\Common\ValueObjects\DecryptedAuthenticatedUser; |
| 5 | use Apie\Common\Wrappers\TextEncrypter; |
| 6 | use HttpSoft\Cookie\CookieCreator; |
| 7 | use HttpSoft\Cookie\CookieManager; |
| 8 | use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 9 | |
| 10 | /** |
| 11 | * Adds an authentication cookie to the response. |
| 12 | */ |
| 13 | class AddAuthenticationCookie implements EventSubscriberInterface |
| 14 | { |
| 15 | public const COOKIE_NAME = '_apie_auth'; |
| 16 | |
| 17 | public static function getSubscribedEvents(): array |
| 18 | { |
| 19 | return [ApieResponseCreated::class => 'onApieResponseCreated']; |
| 20 | } |
| 21 | |
| 22 | public function onApieResponseCreated(ApieResponseCreated $event): void |
| 23 | { |
| 24 | $auth = $event->context->getContext(DecryptedAuthenticatedUser::class, false); |
| 25 | if ($auth instanceof DecryptedAuthenticatedUser) { |
| 26 | $textEncrypter = $event->context->getContext(TextEncrypter::class); |
| 27 | assert($textEncrypter instanceof TextEncrypter); |
| 28 | $manager = new CookieManager(); |
| 29 | $auth = $auth->refresh(time() + 3600); |
| 30 | $value = $textEncrypter->encrypt( |
| 31 | $auth->toNative() |
| 32 | ); |
| 33 | |
| 34 | $manager->set( |
| 35 | CookieCreator::create( |
| 36 | self::COOKIE_NAME, |
| 37 | $value, |
| 38 | $auth->getExpireTime() |
| 39 | ) |
| 40 | ); |
| 41 | $event->response = $manager->send($event->response); |
| 42 | } |
| 43 | } |
| 44 | } |