1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Eljam\GuzzleJwt\Manager; |
4
|
|
|
|
5
|
|
|
use Eljam\GuzzleJwt\JwtToken; |
6
|
|
|
use Eljam\GuzzleJwt\Strategy\Auth\AuthStrategyInterface; |
7
|
|
|
use GuzzleHttp\ClientInterface; |
8
|
|
|
use GuzzleHttp\request; |
9
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @author Guillaume Cavana <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class JwtManager |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* $client Guzzle Client. |
18
|
|
|
* |
19
|
|
|
* @var ClientInterface |
20
|
|
|
*/ |
21
|
|
|
protected $client; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* $auth Authentication Strategy. |
25
|
|
|
* |
26
|
|
|
* @var AuthStrategyInterface |
27
|
|
|
*/ |
28
|
|
|
protected $auth; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* $options. |
32
|
|
|
* |
33
|
|
|
* @var array |
34
|
|
|
*/ |
35
|
|
|
protected $options; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Constructor. |
39
|
|
|
* |
40
|
|
|
* @param ClientInterface $client |
41
|
|
|
* @param AuthStrategyInterface $auth |
42
|
|
|
* @param array $options |
43
|
|
|
*/ |
44
|
|
|
public function __construct( |
45
|
|
|
ClientInterface $client, |
46
|
|
|
AuthStrategyInterface $auth, |
47
|
|
|
array $options = [] |
48
|
|
|
) { |
49
|
|
|
$this->client = $client; |
50
|
|
|
$this->auth = $auth; |
51
|
|
|
|
52
|
|
|
$resolver = new OptionsResolver(); |
53
|
|
|
$resolver->setDefaults([ |
54
|
|
|
'token_url' => '/token', |
55
|
|
|
'timeout' => 1, |
56
|
|
|
]); |
57
|
|
|
|
58
|
|
|
$resolver->setRequired(['token_url', 'timeout']); |
59
|
|
|
|
60
|
|
|
$this->options = $resolver->resolve($options); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* getToken. |
65
|
|
|
* |
66
|
|
|
* @return JwtToken |
67
|
|
|
*/ |
68
|
|
|
public function getJwtToken() |
69
|
|
|
{ |
70
|
|
|
$url = $this->options['token_url']; |
71
|
|
|
|
72
|
|
|
$requestOptions = array_merge( |
73
|
|
|
$this->getDefautHeaders(), |
74
|
|
|
$this->auth->getRequestOptions() |
75
|
|
|
); |
76
|
|
|
|
77
|
|
|
$response = $this->client->request('POST', $url, $requestOptions); |
78
|
|
|
$body = json_decode($response->getBody(), true); |
79
|
|
|
|
80
|
|
|
return new JwtToken($body['token']); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* getHeaders. Return defaults header. |
85
|
|
|
* |
86
|
|
|
* @return array |
87
|
|
|
*/ |
88
|
|
|
private function getDefautHeaders() |
89
|
|
|
{ |
90
|
|
|
return [ |
91
|
|
|
\GuzzleHttp\RequestOptions::HEADERS => [ |
92
|
|
|
'timeout' => $this->options['timeout'], |
93
|
|
|
], |
94
|
|
|
]; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|