1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Rest\Action; |
6
|
|
|
|
7
|
|
|
use Cake\Chronos\Chronos; |
8
|
|
|
use Laminas\Diactoros\Response\JsonResponse; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use Shlinkio\Shlink\Common\Mercure\JwtProviderInterface; |
13
|
|
|
use Shlinkio\Shlink\Rest\Exception\MercureException; |
14
|
|
|
use Throwable; |
15
|
|
|
|
16
|
|
|
use function sprintf; |
17
|
|
|
|
18
|
|
|
class MercureInfoAction extends AbstractRestAction |
19
|
|
|
{ |
20
|
|
|
protected const ROUTE_PATH = '/mercure-info'; |
21
|
|
|
protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET]; |
22
|
|
|
|
23
|
|
|
private JwtProviderInterface $jwtProvider; |
24
|
|
|
private array $mercureConfig; |
25
|
|
|
|
26
|
6 |
|
public function __construct( |
27
|
|
|
JwtProviderInterface $jwtProvider, |
28
|
|
|
array $mercureConfig, |
29
|
|
|
?LoggerInterface $logger = null |
30
|
|
|
) { |
31
|
6 |
|
parent::__construct($logger); |
32
|
6 |
|
$this->jwtProvider = $jwtProvider; |
33
|
6 |
|
$this->mercureConfig = $mercureConfig; |
34
|
|
|
} |
35
|
|
|
|
36
|
6 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
37
|
|
|
{ |
38
|
6 |
|
$hubUrl = $this->mercureConfig['public_hub_url'] ?? null; |
39
|
6 |
|
if ($hubUrl === null) { |
40
|
2 |
|
throw MercureException::mercureNotConfigured(); |
41
|
|
|
} |
42
|
|
|
|
43
|
4 |
|
$days = $this->mercureConfig['jwt_days_duration'] ?? 3; |
44
|
4 |
|
$expiresAt = Chronos::now()->addDays($days); |
45
|
|
|
|
46
|
|
|
try { |
47
|
4 |
|
$jwt = $this->jwtProvider->buildSubscriptionToken($expiresAt); |
48
|
2 |
|
} catch (Throwable $e) { |
49
|
2 |
|
throw MercureException::mercureNotConfigured($e); |
50
|
|
|
} |
51
|
|
|
|
52
|
2 |
|
return new JsonResponse([ |
53
|
2 |
|
'mercureHubUrl' => sprintf('%s/.well-known/mercure', $hubUrl), |
54
|
2 |
|
'token' => $jwt, |
55
|
2 |
|
'jwtExpiration' => $expiresAt->toAtomString(), |
56
|
|
|
]); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|