1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Facile\OAuth2\HttpClient\Authorization; |
6
|
|
|
|
7
|
|
|
use Facile\OAuth2\HttpClient\Exception\RuntimeException; |
8
|
|
|
use Facile\OAuth2\HttpClient\Request\OAuth2RequestInterface; |
9
|
|
|
use Facile\OpenIDClient\Client\ClientInterface; |
10
|
|
|
use Psr\SimpleCache\CacheInterface; |
11
|
|
|
|
12
|
|
|
class CachedProvider implements AuthorizationProvider |
13
|
|
|
{ |
14
|
|
|
/** @var CacheInterface */ |
15
|
|
|
private $cache; |
16
|
|
|
|
17
|
|
|
/** @var int */ |
18
|
|
|
private $defaultTtl; |
19
|
|
|
|
20
|
|
|
/** @var string */ |
21
|
|
|
private $hashAlg = 'sha1'; |
22
|
|
|
|
23
|
4 |
|
public function __construct(CacheInterface $cache, int $defaultTtl = 1800) |
24
|
|
|
{ |
25
|
4 |
|
$this->cache = $cache; |
26
|
4 |
|
$this->defaultTtl = $defaultTtl; |
27
|
4 |
|
} |
28
|
|
|
|
29
|
1 |
|
public function setHashAlg(string $hashAlg): void |
30
|
|
|
{ |
31
|
1 |
|
$this->hashAlg = $hashAlg; |
32
|
1 |
|
} |
33
|
|
|
|
34
|
4 |
|
private function getCacheKey(ClientInterface $client, OAuth2RequestInterface $request): string |
35
|
|
|
{ |
36
|
4 |
|
$encoded = json_encode([ |
37
|
4 |
|
'issuer' => $client->getIssuer()->getMetadata()->getIssuer(), |
38
|
4 |
|
'client_id' => $client->getMetadata()->getClientId(), |
39
|
4 |
|
'grantParams' => $request->getGrantParams(), |
40
|
|
|
]); |
41
|
|
|
|
42
|
4 |
|
if (! is_string($encoded)) { |
43
|
|
|
throw new RuntimeException('Unable to create cache key'); |
44
|
|
|
} |
45
|
|
|
|
46
|
4 |
|
return hash($this->hashAlg, $encoded); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
public function getAuthorization(ClientInterface $client, OAuth2RequestInterface $request): ?string |
50
|
|
|
{ |
51
|
1 |
|
return $this->cache->get($this->getCacheKey($client, $request)); |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
public function saveAuthorization( |
55
|
|
|
ClientInterface $client, |
56
|
|
|
OAuth2RequestInterface $request, |
57
|
|
|
string $authorization, |
58
|
|
|
?int $ttl = null |
59
|
|
|
): void { |
60
|
3 |
|
$this->cache->set($this->getCacheKey($client, $request), $authorization, $ttl ?? $this->defaultTtl); |
61
|
3 |
|
} |
62
|
|
|
} |
63
|
|
|
|