Service.php
6.83 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
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
<?php
/**
* OAuth2 Service 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 Yii;
use yii\helpers\Url;
use OAuth\Common\Exception\Exception as OAuthException;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Consumer\Credentials;
use OAuth\OAuth2\Service\ServiceInterface;
use nodge\eauth\EAuth;
use nodge\eauth\ErrorException;
use nodge\eauth\IAuthService;
use nodge\eauth\oauth\ServiceBase;
/**
* EOAuthService is a base class for all OAuth providers.
*
* @package application.extensions.eauth
*/
abstract class Service extends ServiceBase implements IAuthService
{
/**
* @var string OAuth2 client id.
*/
protected $clientId;
/**
* @var string OAuth2 client secret key.
*/
protected $clientSecret;
/**
* @var array OAuth scopes.
*/
protected $scopes = [];
/**
* @var string
*/
protected $scopeSeparator = ' ';
/**
* @var array Provider options. Must contain the keys: authorize, access_token.
*/
protected $providerOptions = [
'authorize' => '',
'access_token' => '',
];
/**
* @var string Error key name in _GET options.
*/
protected $errorParam = 'error';
/**
* @var string Error description key name in _GET options.
*/
protected $errorDescriptionParam = 'error_description';
/**
* @var string Error code for access_denied response.
*/
protected $errorAccessDeniedCode = 'access_denied';
/**
* @var string The display name for popup window. False to disable display mode.
*/
protected $popupDisplayName = 'popup';
/**
* @var bool Whether to use the State param to improve security.
*/
protected $validateState = true;
/**
* @var ServiceProxy
*/
private $_proxy;
/**
* Initialize the component.
*
* @param EAuth $component the component instance.
* @param array $options properties initialization.
*/
// public function init($component, $options = []) {
// parent::init($component, $options);
// }
/**
* @param string $id
*/
public function setClientId($id)
{
$this->clientId = $id;
}
/**
* @param string $secret
*/
public function setClientSecret($secret)
{
$this->clientSecret = $secret;
}
/**
* @param string|array $scopes
*/
public function setScope($scopes)
{
if (!is_array($scopes)) {
$scopes = [$scopes];
}
$resolvedScopes = [];
$reflClass = new \ReflectionClass($this);
$constants = $reflClass->getConstants();
foreach ($scopes as $scope) {
$key = strtoupper('SCOPE_' . $scope);
// try to find a class constant with this name
if (array_key_exists($key, $constants)) {
$resolvedScopes[] = $constants[$key];
} else {
$resolvedScopes[] = $scope;
}
}
$this->scopes = $resolvedScopes;
}
/**
* @param bool $validate
*/
public function setValidateState($validate)
{
$this->validateState = $validate;
}
/**
* @return bool
*/
public function getValidateState()
{
return $this->validateState;
}
/**
* @return ServiceProxy
*/
protected function getProxy()
{
if (!isset($this->_proxy)) {
$tokenStorage = $this->getTokenStorage();
$httpClient = $this->getHttpClient();
$credentials = new Credentials($this->clientId, $this->clientSecret, $this->getCallbackUrl());
$this->_proxy = new ServiceProxy($credentials, $httpClient, $tokenStorage, $this->scopes, null, $this);
}
return $this->_proxy;
}
/**
* @return string the current url
*/
protected function getCallbackUrl()
{
if (isset($_GET['redirect_uri'])) {
$url = $_GET['redirect_uri'];
}
else {
$route = Yii::$app->getRequest()->getQueryParams();
array_unshift($route, '');
// Can not use these params in OAuth2 callbacks
foreach (['code', 'state', 'redirect_uri'] as $param) {
if (isset($route[$param])) {
unset($route[$param]);
}
}
$url = Url::to($route, true);
}
return $url;
}
/**
* Authenticate the user.
*
* @return boolean whether user was successfuly authenticated.
* @throws ErrorException
*/
public function authenticate()
{
if (!$this->checkError()) {
return false;
}
try {
$proxy = $this->getProxy();
if (!empty($_GET['code'])) {
// This was a callback request from a service, get the token
$proxy->requestAccessToken($_GET['code']);
$this->authenticated = true;
} else if ($proxy->hasValidAccessToken()) {
$this->authenticated = true;
} else {
/** @var $url Uri */
$url = $proxy->getAuthorizationUri();
Yii::$app->getResponse()->redirect($url->getAbsoluteUri())->send();
}
} catch (OAuthException $e) {
throw new ErrorException($e->getMessage(), $e->getCode(), 1, $e->getFile(), $e->getLine(), $e);
}
return $this->getIsAuthenticated();
}
/**
* Check request params for error code and message.
*
* @return bool
* @throws ErrorException
*/
protected function checkError()
{
if (isset($_GET[$this->errorParam])) {
$error_code = $_GET[$this->errorParam];
if ($error_code === $this->errorAccessDeniedCode) {
// access_denied error (user canceled)
$this->cancel();
} else {
$error = $error_code;
if (isset($_GET[$this->errorDescriptionParam])) {
$error = $_GET[$this->errorDescriptionParam] . ' (' . $error . ')';
}
throw new ErrorException($error);
}
return false;
}
return true;
}
/**
* @return string
*/
public function getAuthorizationEndpoint()
{
$url = $this->providerOptions['authorize'];
if ($this->popupDisplayName !== false && $this->getIsInsidePopup()) {
$url = new Uri($url);
$url->addToQuery('display', $this->popupDisplayName);
$url = $url->getAbsoluteUri();
}
return $url;
}
/**
* @return string
*/
public function getAccessTokenEndpoint()
{
return $this->providerOptions['access_token'];
}
/**
* @param string $response
* @return array
*/
public function parseAccessTokenResponse($response)
{
return json_decode($response, true);
}
/**
* @return array
*/
public function getAccessTokenArgumentNames()
{
return [
'access_token' => 'access_token',
'expires_in' => 'expires_in',
'refresh_token' => 'refresh_token',
];
}
/**
* Return any additional headers always needed for this service implementation's OAuth calls.
*
* @return array
*/
public function getExtraOAuthHeaders()
{
return [];
}
/**
* Return any additional headers always needed for this service implementation's API calls.
*
* @return array
*/
public function getExtraApiHeaders()
{
return [];
}
/**
* Returns a class constant from ServiceInterface defining the authorization method used for the API
* Header is the sane default.
*
* @return int
*/
public function getAuthorizationMethod()
{
return ServiceInterface::AUTHORIZATION_METHOD_HEADER_OAUTH;
}
/**
* @return string
*/
public function getScopeSeparator()
{
return $this->scopeSeparator;
}
}