1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AtlassianConnectBundle\Service; |
6
|
|
|
|
7
|
|
|
use AtlassianConnectBundle\Entity\TenantInterface; |
8
|
|
|
use Symfony\Component\HttpClient\DecoratorTrait; |
9
|
|
|
use Symfony\Component\HttpClient\HttpClient; |
10
|
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface; |
11
|
|
|
use Symfony\Contracts\HttpClient\ResponseInterface; |
12
|
|
|
use Symfony\Contracts\HttpClient\ResponseStreamInterface; |
13
|
|
|
|
14
|
|
|
final class AuthenticatedAtlassianClient implements HttpClientInterface |
15
|
|
|
{ |
16
|
|
|
private HttpClientInterface $client; |
17
|
|
|
|
18
|
|
|
public function __construct(HttpClientInterface $client) |
19
|
|
|
{ |
20
|
|
|
$this->client = $client; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function request(string $method, string $url, array $options = []): ResponseInterface |
24
|
|
|
{ |
25
|
|
|
/** @var TenantInterface $tenant */ |
26
|
|
|
$tenant = $options['tenant']; |
27
|
|
|
$userId = $options['user_id']; |
28
|
|
|
unset($options['tenant']); |
29
|
|
|
unset($options['user_id']); |
30
|
|
|
|
31
|
|
|
if (!$userId) { |
32
|
|
|
$options['headers']['Authorization'] = 'JWT '.JWTGenerator::generate($url, $method, $tenant->getAddonKey(), $tenant->getSharedSecret()); |
|
|
|
|
33
|
|
|
|
34
|
|
|
return $this->client->request($method, $url, $options); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
if (!$tenant->getOauthClientId()) { |
38
|
|
|
throw new \RuntimeException('Tenant is not set up as oath application. Install the app with "ACT_AS_USER" scope.'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$result = $this->client->request('POST', 'https://oauth-2-authorization-server.services.atlassian.com/oauth2/token', [ |
42
|
|
|
'body' => [ |
43
|
|
|
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', |
44
|
|
|
'assertion' => JWTGenerator::generateAssertion($tenant->getSharedSecret(), $tenant->getOauthClientId(), $tenant->getBaseUrl(), $userId), |
|
|
|
|
45
|
|
|
], |
46
|
|
|
]); |
47
|
|
|
|
48
|
|
|
$options['headers']['Authorization'] = 'Bearer '.$result->toArray()['access_token']; |
49
|
|
|
|
50
|
|
|
return $this->client->request($method, $url, $options); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* {@inheritdoc} |
55
|
|
|
*/ |
56
|
|
|
public function stream($responses, float $timeout = null): ResponseStreamInterface |
57
|
|
|
{ |
58
|
|
|
return $this->client->stream($responses, $timeout); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function withOptions(array $options): static |
62
|
|
|
{ |
63
|
|
|
$clone = clone $this; |
64
|
|
|
$clone->client = $this->client->withOptions($options); |
65
|
|
|
|
66
|
|
|
return $clone; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|