ServiceProxy.php
5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<?php
/**
* OAuth2 ServiceProxy class file.
*
* @author Maxim Zemskov <nodge@yandex.ru>
* @link http://github.com/Nodge/yii2-eauth/
* @license http://www.opensource.org/licenses/bsd-license.php
*/
namespace nodge\eauth\oauth2;
use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Token\TokenInterface;
use OAuth\OAuth2\Service\AbstractService;
use OAuth\OAuth2\Token\StdOAuth2Token;
class ServiceProxy extends AbstractService
{
/**
* @var Service the currently used service class
*/
protected $service;
/**
* @param CredentialsInterface $credentials
* @param ClientInterface $httpClient
* @param TokenStorageInterface $storage
* @param array $scopes
* @param UriInterface $baseApiUri
* @param Service $service
*/
public function __construct(
CredentialsInterface $credentials,
ClientInterface $httpClient,
TokenStorageInterface $storage,
$scopes = [],
UriInterface $baseApiUri = null,
Service $service
)
{
$this->service = $service;
parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, $service->getValidateState());
}
/**
* @return string
*/
public function service()
{
return $this->service->getServiceName();
}
/**
* Validate scope
*
* @param string $scope
* @return bool
*/
public function isValidScope($scope)
{
$reflectionClass = new \ReflectionClass(get_class($this->service));
return in_array($scope, $reflectionClass->getConstants(), true);
}
/**
* @return bool
*/
public function hasValidAccessToken()
{
$serviceName = $this->service();
if (!$this->storage->hasAccessToken($serviceName)) {
return false;
}
/** @var $token StdOAuth2Token */
$token = $this->storage->retrieveAccessToken($serviceName);
$valid = $this->checkTokenLifetime($token);
if (!$valid) {
$refreshToken = $token->getRefreshToken();
if (isset($refreshToken)) {
$token = $this->refreshAccessToken($token);
return $this->checkTokenLifetime($token);
}
}
return $valid;
}
/**
* @param TokenInterface $token
* @return bool
*/
protected function checkTokenLifetime($token)
{
// assume that we have at least a minute to execute a queries.
return $token->getEndOfLife() - 60 > time()
|| $token->getEndOfLife() === TokenInterface::EOL_NEVER_EXPIRES
|| $token->getEndOfLife() === TokenInterface::EOL_UNKNOWN;
}
/**
* @return null|TokenInterface
*/
public function getAccessToken()
{
if (!$this->hasValidAccessToken()) {
return null;
}
$serviceName = $this->service();
return $this->storage->retrieveAccessToken($serviceName);
}
/**
* @return UriInterface
*/
public function getAuthorizationEndpoint()
{
return new Uri($this->service->getAuthorizationEndpoint());
}
/**
* @return UriInterface
*/
public function getAccessTokenEndpoint()
{
return new Uri($this->service->getAccessTokenEndpoint());
}
/**
* @param string $responseBody
* @return StdOAuth2Token
* @throws TokenResponseException
*/
protected function parseAccessTokenResponse($responseBody)
{
$data = $this->service->parseAccessTokenResponse($responseBody);
if (!isset($data) || !is_array($data)) {
throw new TokenResponseException('Unable to parse response.');
}
$error = $this->service->getAccessTokenResponseError($data);
if (isset($error)) {
throw new TokenResponseException('Error in retrieving token: "' . $error . '"');
}
$token = new StdOAuth2Token();
$names = $this->service->getAccessTokenArgumentNames();
$token->setAccessToken($data[$names['access_token']]);
unset($data[$names['access_token']]);
if (isset($data[$names['expires_in']])) {
$token->setLifeTime($data[$names['expires_in']]);
unset($data[$names['expires_in']]);
} else {
$token->setLifetime($this->service->getTokenDefaultLifetime());
}
if (isset($data[$names['refresh_token']])) {
$token->setRefreshToken($data[$names['refresh_token']]);
unset($data[$names['refresh_token']]);
}
$token->setExtraParams($data);
return $token;
}
/**
* Return any additional headers always needed for this service implementation's OAuth calls.
*
* @return array
*/
protected function getExtraOAuthHeaders()
{
return $this->service->getExtraOAuthHeaders();
}
/**
* Return any additional headers always needed for this service implementation's API calls.
*
* @return array
*/
protected function getExtraApiHeaders()
{
return $this->service->getExtraApiHeaders();
}
/**
* Returns a class constant from ServiceInterface defining the authorization method used for the API
* Header is the sane default.
*
* @return int
*/
protected function getAuthorizationMethod()
{
return $this->service->getAuthorizationMethod();
}
/**
* Returns the url to redirect to for authorization purposes.
*
* @param array $additionalParameters
* @return Uri
*/
public function getAuthorizationUri(array $additionalParameters = [])
{
$parameters = array_merge($additionalParameters, [
'type' => 'web_server',
'client_id' => $this->credentials->getConsumerId(),
'redirect_uri' => $this->credentials->getCallbackUrl(),
'response_type' => 'code',
]);
$parameters['scope'] = implode($this->service->getScopeSeparator(), $this->scopes);
if ($this->needsStateParameterInAuthUrl()) {
if (!isset($parameters['state'])) {
$parameters['state'] = $this->generateAuthorizationState();
}
$this->storeAuthorizationState($parameters['state']);
}
// Build the url
$url = clone $this->getAuthorizationEndpoint();
foreach ($parameters as $key => $val) {
$url->addToQuery($key, $val);
}
return $url;
}
}