1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Audiens\DoubleclickClient\authentication; |
4
|
|
|
|
5
|
|
|
use Audiens\DoubleclickClient\CachableTrait; |
6
|
|
|
use Audiens\DoubleclickClient\CacheableInterface; |
7
|
|
|
use Audiens\DoubleclickClient\entity\BearerToken; |
8
|
|
|
use Doctrine\Common\Cache\Cache; |
9
|
|
|
use GuzzleHttp\ClientInterface; |
10
|
|
|
|
11
|
|
|
class Oauth2ServiceAccountStrategy implements AuthStrategyInterface, CacheableInterface |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
use CachableTrait; |
15
|
|
|
|
16
|
|
|
public const NAME = 'oauth2_service_account'; |
17
|
|
|
|
18
|
|
|
public const BASE_URL = 'https://www.googleapis.com/oauth2/v4/token'; |
19
|
|
|
|
20
|
|
|
public const CACHE_NAMESPACE = 'oauth2_service_account'; |
21
|
|
|
public const CACHE_EXPIRATION = 1800; |
22
|
|
|
|
23
|
|
|
public const SCOPE = 'https://ddp.googleapis.com/api/ddp/'; |
24
|
|
|
|
25
|
|
|
/** @var Cache */ |
26
|
|
|
protected $cache; |
27
|
|
|
|
28
|
|
|
/** @var JwtFactoryInterface */ |
29
|
|
|
protected $jwtFactory; |
30
|
|
|
|
31
|
|
|
/** @var ClientInterface */ |
32
|
|
|
protected $client; |
33
|
|
|
|
34
|
|
|
public function __construct(ClientInterface $clientInterface, Cache $cache, JwtFactoryInterface $jwtFactory) |
35
|
|
|
{ |
36
|
|
|
$this->cache = $cache; |
37
|
|
|
$this->client = $clientInterface; |
38
|
|
|
$this->jwtFactory = $jwtFactory; |
39
|
|
|
|
40
|
|
|
$this->cacheEnabled = $cache instanceof Cache; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function authenticate(bool $cache = true): BearerToken |
44
|
|
|
{ |
45
|
|
|
$cacheKey = self::CACHE_NAMESPACE.sha1($this->jwtFactory->getHash().self::BASE_URL); |
46
|
|
|
|
47
|
|
|
if ($cache) { |
48
|
|
|
if ($this->cache->contains($cacheKey)) { |
49
|
|
|
return $this->cache->fetch($cacheKey); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$token = $this->jwtFactory->build(); |
54
|
|
|
|
55
|
|
|
$body = 'grant_type='.urlencode('urn:ietf:params:oauth:grant-type:jwt-bearer').'&assertion='.$token; |
56
|
|
|
|
57
|
|
|
$response = $this->client->request( |
58
|
|
|
'POST', |
59
|
|
|
self::BASE_URL, |
60
|
|
|
[ |
61
|
|
|
'body' => $body, |
62
|
|
|
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], |
63
|
|
|
] |
64
|
|
|
); |
65
|
|
|
|
66
|
|
|
$bearerToken = BearerToken::fromArray(json_decode($response->getBody()->getContents(), true)); |
67
|
|
|
|
68
|
|
|
$response->getBody()->rewind(); |
69
|
|
|
|
70
|
|
|
if ($this->isCacheEnabled()) { |
71
|
|
|
$this->cache->save($cacheKey, $bearerToken, self::CACHE_EXPIRATION); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $bearerToken; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
public function getSlug(): string |
78
|
|
|
{ |
79
|
|
|
return self::NAME; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|