forked from yiisoft/yii2-authclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseOAuth.php
346 lines (313 loc) · 10.4 KB
/
BaseOAuth.php
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\authclient;
use yii\base\Exception;
use yii\base\InvalidParamException;
use Yii;
use yii\httpclient\Request;
/**
* BaseOAuth is a base class for the OAuth clients.
*
* @see http://oauth.net/
*
* @property OAuthToken $accessToken Auth token instance. Note that the type of this property differs in
* getter and setter. See [[getAccessToken()]] and [[setAccessToken()]] for details.
* @property string $returnUrl Return URL.
* @property signature\BaseMethod $signatureMethod Signature method instance. Note that the type of this
* property differs in getter and setter. See [[getSignatureMethod()]] and [[setSignatureMethod()]] for details.
*
* @author Paul Klimov <[email protected]>
* @since 2.0
*/
abstract class BaseOAuth extends BaseClient
{
/**
* @var string protocol version.
*/
public $version = '1.0';
/**
* @var string API base URL.
* This field will be used as [[\yii\httpclient\Client::baseUrl]] value of [[httpClient]].
* Note: changing this property will take no effect after [[httpClient]] is instantiated.
*/
public $apiBaseUrl;
/**
* @var string authorize URL.
*/
public $authUrl;
/**
* @var string auth request scope.
*/
public $scope;
/**
* @var bool whether to automatically perform 'refresh access token' request on expired access token.
* @since 2.0.6
*/
public $autoRefreshAccessToken = true;
/**
* @var string URL, which user will be redirected after authentication at the OAuth provider web site.
* Note: this should be absolute URL (with http:// or https:// leading).
* By default current URL will be used.
*/
private $_returnUrl;
/**
* @var OAuthToken|array access token instance or its array configuration.
*/
private $_accessToken;
/**
* @var signature\BaseMethod|array signature method instance or its array configuration.
*/
private $_signatureMethod = [];
/**
* @param string $returnUrl return URL
*/
public function setReturnUrl($returnUrl)
{
$this->_returnUrl = $returnUrl;
}
/**
* @return string return URL.
*/
public function getReturnUrl()
{
if ($this->_returnUrl === null) {
$this->_returnUrl = $this->defaultReturnUrl();
}
return $this->_returnUrl;
}
/**
* Sets access token to be used.
* @param array|OAuthToken $token access token or its configuration.
*/
public function setAccessToken($token)
{
if (!is_object($token) && $token !== null) {
$token = $this->createToken($token);
}
$this->_accessToken = $token;
$this->saveAccessToken($token);
}
/**
* @return OAuthToken auth token instance.
*/
public function getAccessToken()
{
if (!is_object($this->_accessToken)) {
$this->_accessToken = $this->restoreAccessToken();
}
return $this->_accessToken;
}
/**
* Set signature method to be used.
* @param array|signature\BaseMethod $signatureMethod signature method instance or its array configuration.
* @throws InvalidParamException on wrong argument.
*/
public function setSignatureMethod($signatureMethod)
{
if (!is_object($signatureMethod) && !is_array($signatureMethod)) {
throw new InvalidParamException('"' . get_class($this) . '::signatureMethod" should be instance of "\yii\autclient\signature\BaseMethod" or its array configuration. "' . gettype($signatureMethod) . '" has been given.');
}
$this->_signatureMethod = $signatureMethod;
}
/**
* @return signature\BaseMethod signature method instance.
*/
public function getSignatureMethod()
{
if (!is_object($this->_signatureMethod)) {
$this->_signatureMethod = $this->createSignatureMethod($this->_signatureMethod);
}
return $this->_signatureMethod;
}
/**
* @inheritdoc
*/
public function setHttpClient($httpClient)
{
if (is_object($httpClient)) {
$httpClient = clone $httpClient;
$httpClient->baseUrl = $this->apiBaseUrl;
}
parent::setHttpClient($httpClient);
}
/**
* @inheritdoc
*/
protected function createHttpClient($reference)
{
$httpClient = parent::createHttpClient($reference);
$httpClient->baseUrl = $this->apiBaseUrl;
return $httpClient;
}
/**
* Composes default [[returnUrl]] value.
* @return string return URL.
*/
protected function defaultReturnUrl()
{
return Yii::$app->getRequest()->getAbsoluteUrl();
}
/**
* @inheritdoc
*/
protected function defaultRequestOptions()
{
return [
'userAgent' => Yii::$app->name . ' OAuth ' . $this->version . ' Client',
'timeout' => 30,
'sslVerifyPeer' => false,
];
}
/**
* Creates signature method instance from its configuration.
* @param array $signatureMethodConfig signature method configuration.
* @return signature\BaseMethod signature method instance.
*/
protected function createSignatureMethod(array $signatureMethodConfig)
{
if (!array_key_exists('class', $signatureMethodConfig)) {
$signatureMethodConfig['class'] = signature\HmacSha1::className();
}
return Yii::createObject($signatureMethodConfig);
}
/**
* Creates token from its configuration.
* @param array $tokenConfig token configuration.
* @return OAuthToken token instance.
*/
protected function createToken(array $tokenConfig = [])
{
if (!array_key_exists('class', $tokenConfig)) {
$tokenConfig['class'] = OAuthToken::className();
}
return Yii::createObject($tokenConfig);
}
/**
* Sends the given HTTP request, returning response data.
* @param \yii\httpclient\Request $request HTTP request to be sent.
* @return array response data.
* @throws InvalidResponseException on invalid remote response.
* @since 2.1
*/
protected function sendRequest($request)
{
$response = $request->send();
if (!$response->getIsOk()) {
throw new InvalidResponseException($response, 'Request failed with code: ' . $response->getStatusCode() . ', message: ' . $response->getContent());
}
return $response->getData();
}
/**
* Composes URL from base URL and GET params.
* @param string $url base URL.
* @param array $params GET params.
* @return string composed URL.
*/
protected function composeUrl($url, array $params = [])
{
if (!empty($params)) {
if (strpos($url, '?') === false) {
$url .= '?';
} else {
$url .= '&';
}
$url .= http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
return $url;
}
/**
* Saves token as persistent state.
* @param OAuthToken|null $token auth token to be saved.
* @return $this the object itself.
*/
protected function saveAccessToken($token)
{
return $this->setState('token', $token);
}
/**
* Restores access token.
* @return OAuthToken auth token.
*/
protected function restoreAccessToken()
{
$token = $this->getState('token');
if (is_object($token)) {
/* @var $token OAuthToken */
if ($token->getIsExpired() && $this->autoRefreshAccessToken) {
$token = $this->refreshAccessToken($token);
}
}
return $token;
}
/**
* Creates an HTTP request for the API call.
* The created request will be automatically processed adding access token parameters and signature
* before sending. You may use [[createRequest()]] to gain full control over request composition and execution.
* @see createRequest()
* @return Request HTTP request instance.
* @since 2.1
*/
public function createApiRequest()
{
$request = $this->createRequest();
$request->on(Request::EVENT_BEFORE_SEND, [$this, 'beforeApiRequestSend']);
return $request;
}
/**
* Handles [[Request::EVENT_BEFORE_SEND]] event.
* Applies [[accessToken]] to the request.
* @param \yii\httpclient\RequestEvent $event event instance.
* @throws Exception on invalid access token.
* @since 2.1
*/
public function beforeApiRequestSend($event)
{
$accessToken = $this->getAccessToken();
if (!is_object($accessToken) || !$accessToken->getIsValid()) {
throw new Exception('Invalid access token.');
}
$this->applyAccessTokenToRequest($event->request, $accessToken);
}
/**
* Performs request to the OAuth API returning response data.
* You may use [[createApiRequest()]] method instead, gaining more control over request execution.
* @see createApiRequest()
* @param string $apiSubUrl API sub URL, which will be append to [[apiBaseUrl]], or absolute API URL.
* @param string $method request method.
* @param array|string $data request data or content.
* @param array $headers additional request headers.
* @return array API response data.
*/
public function api($apiSubUrl, $method = 'GET', $data = [], $headers = [])
{
$request = $this->createApiRequest()
->setMethod($method)
->setUrl($apiSubUrl)
->addHeaders($headers);
if (!empty($data)) {
if (is_array($data)) {
$request->setData($data);
} else {
$request->setContent($data);
}
}
return $this->sendRequest($request);
}
/**
* Gets new auth token to replace expired one.
* @param OAuthToken $token expired auth token.
* @return OAuthToken new auth token.
*/
abstract public function refreshAccessToken(OAuthToken $token);
/**
* Applies access token to the HTTP request instance.
* @param \yii\httpclient\Request $request HTTP request instance.
* @param OAuthToken $accessToken access token instance.
* @since 2.1
*/
abstract public function applyAccessTokenToRequest($request, $accessToken);
}