BaseOAuth.php 16.4 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\authclient;
9 10 11 12 13 14 15

use yii\base\Exception;
use yii\base\InvalidParamException;
use Yii;
use yii\helpers\Json;

/**
16
 * BaseOAuth is a base class for the OAuth clients.
17 18 19
 *
 * @see http://oauth.net/
 *
Qiang Xue committed
20 21 22 23
 * @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 array $curlOptions CURL options. This property is read-only.
 * @property string $returnUrl Return URL.
Carsten Brandt committed
24 25
 * @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.
Qiang Xue committed
26
 *
27 28 29
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
30
abstract class BaseOAuth extends BaseClient implements ClientInterface
31
{
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    const CONTENT_TYPE_JSON = 'json'; // JSON format
    const CONTENT_TYPE_URLENCODED = 'urlencoded'; // urlencoded query string, like name1=value1&name2=value2
    const CONTENT_TYPE_XML = 'xml'; // XML format
    const CONTENT_TYPE_AUTO = 'auto'; // attempts to determine format automatically

    /**
     * @var string protocol version.
     */
    public $version = '1.0';
    /**
     * @var string API base URL.
     */
    public $apiBaseUrl;
    /**
     * @var string authorize URL.
     */
    public $authUrl;
    /**
     * @var string auth request scope.
     */
    public $scope;
53 54 55 56 57 58 59

    /**
     * @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;
60 61
    /**
     * @var array cURL request options. Option values from this field will overwrite corresponding
62
     * values from [[defaultCurlOptions()]].
63 64 65 66 67 68 69 70 71 72 73
     */
    private $_curlOptions = [];
    /**
     * @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 = [];

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
    /**
     * @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;
    }

    /**
     * @param array $curlOptions cURL options.
     */
    public function setCurlOptions(array $curlOptions)
    {
        $this->_curlOptions = $curlOptions;
    }

    /**
     * @return array cURL options.
     */
    public function getCurlOptions()
    {
        return $this->_curlOptions;
    }

    /**
     * @param array|OAuthToken $token
     */
    public function setAccessToken($token)
    {
        if (!is_object($token)) {
            $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;
    }

    /**
135 136
     * @param array|signature\BaseMethod $signatureMethod signature method instance or its array configuration.
     * @throws InvalidParamException on wrong argument.
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
     */
    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;
    }

    /**
159
     * Composes default [[returnUrl]] value.
160 161 162 163 164 165 166 167 168
     * @return string return URL.
     */
    protected function defaultReturnUrl()
    {
        return Yii::$app->getRequest()->getAbsoluteUrl();
    }

    /**
     * Sends HTTP request.
169 170 171
     * @param string $method request type.
     * @param string $url request URL.
     * @param array $params request params.
172
     * @param array $headers additional request headers.
173
     * @return array response.
174 175
     * @throws Exception on failure.
     */
176
    protected function sendRequest($method, $url, array $params = [], array $headers = [])
177 178 179 180 181
    {
        $curlOptions = $this->mergeCurlOptions(
            $this->defaultCurlOptions(),
            $this->getCurlOptions(),
            [
182
                CURLOPT_HTTPHEADER => $headers,
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_URL => $url,
            ],
            $this->composeRequestCurlOptions(strtoupper($method), $url, $params)
        );
        $curlResource = curl_init();
        foreach ($curlOptions as $option => $value) {
            curl_setopt($curlResource, $option, $value);
        }
        $response = curl_exec($curlResource);
        $responseHeaders = curl_getinfo($curlResource);

        // check cURL error
        $errorNumber = curl_errno($curlResource);
        $errorMessage = curl_error($curlResource);

        curl_close($curlResource);

        if ($errorNumber > 0) {
            throw new Exception('Curl error requesting "' .  $url . '": #' . $errorNumber . ' - ' . $errorMessage);
        }
204
        if (strncmp($responseHeaders['http_code'], '20', 2) !== 0) {
205
            throw new InvalidResponseException($responseHeaders, $response, 'Request failed with code: ' . $responseHeaders['http_code'] . ', message: ' . $response);
206 207 208 209 210 211 212 213 214
        }

        return $this->processResponse($response, $this->determineContentTypeByHeaders($responseHeaders));
    }

    /**
     * Merge CUrl options.
     * If each options array has an element with the same key value, the latter
     * will overwrite the former.
215 216 217
     * @param array $options1 options to be merged to.
     * @param array $options2 options to be merged from. You can specify additional
     * arrays via third argument, fourth argument etc.
218 219 220 221 222 223 224 225 226
     * @return array merged options (the original options are not changed.)
     */
    protected function mergeCurlOptions($options1, $options2)
    {
        $args = func_get_args();
        $res = array_shift($args);
        while (!empty($args)) {
            $next = array_shift($args);
            foreach ($next as $k => $v) {
227 228 229 230 231
                if (is_array($v) && !empty($res[$k]) && is_array($res[$k])) {
                    $res[$k] = array_merge($res[$k], $v);
                } else {
                    $res[$k] = $v;
                }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
            }
        }
        return $res;
    }

    /**
     * Returns default cURL options.
     * @return array cURL options.
     */
    protected function defaultCurlOptions()
    {
        return [
            CURLOPT_USERAGENT => Yii::$app->name . ' OAuth ' . $this->version . ' Client',
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ];
    }

    /**
     * Processes raw response converting it to actual data.
253 254
     * @param string $rawResponse raw response.
     * @param string $contentType response content type.
255
     * @throws Exception on failure.
256
     * @return array actual response.
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
     */
    protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO)
    {
        if (empty($rawResponse)) {
            return [];
        }
        switch ($contentType) {
            case self::CONTENT_TYPE_AUTO: {
                $contentType = $this->determineContentTypeByRaw($rawResponse);
                if ($contentType == self::CONTENT_TYPE_AUTO) {
                    throw new Exception('Unable to determine response content type automatically.');
                }
                $response = $this->processResponse($rawResponse, $contentType);
                break;
            }
            case self::CONTENT_TYPE_JSON: {
                $response = Json::decode($rawResponse, true);
                if (isset($response['error'])) {
                    throw new Exception('Response error: ' . $response['error']);
                }
                break;
            }
            case self::CONTENT_TYPE_URLENCODED: {
                $response = [];
                parse_str($rawResponse, $response);
                break;
            }
            case self::CONTENT_TYPE_XML: {
                $response = $this->convertXmlToArray($rawResponse);
                break;
            }
            default: {
                throw new Exception('Unknown response type "' . $contentType . '".');
            }
        }
        return $response;
    }

    /**
     * Converts XML document to array.
297 298
     * @param string|\SimpleXMLElement $xml xml to process.
     * @return array XML array representation.
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
     */
    protected function convertXmlToArray($xml)
    {
        if (!is_object($xml)) {
            $xml = simplexml_load_string($xml);
        }
        $result = (array) $xml;
        foreach ($result as $key => $value) {
            if (is_object($value)) {
                $result[$key] = $this->convertXmlToArray($value);
            }
        }
        return $result;
    }

    /**
     * Attempts to determine HTTP request content type by headers.
316
     * @param array $headers request headers.
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
     * @return string content type.
     */
    protected function determineContentTypeByHeaders(array $headers)
    {
        if (isset($headers['content_type'])) {
            if (stripos($headers['content_type'], 'json') !== false) {
                return self::CONTENT_TYPE_JSON;
            }
            if (stripos($headers['content_type'], 'urlencoded') !== false) {
                return self::CONTENT_TYPE_URLENCODED;
            }
            if (stripos($headers['content_type'], 'xml') !== false) {
                return self::CONTENT_TYPE_XML;
            }
        }
        return self::CONTENT_TYPE_AUTO;
    }

    /**
     * Attempts to determine the content type from raw content.
337
     * @param string $rawContent raw response content.
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
     * @return string response type.
     */
    protected function determineContentTypeByRaw($rawContent)
    {
        if (preg_match('/^\\{.*\\}$/is', $rawContent)) {
            return self::CONTENT_TYPE_JSON;
        }
        if (preg_match('/^[^=|^&]+=[^=|^&]+(&[^=|^&]+=[^=|^&]+)*$/is', $rawContent)) {
            return self::CONTENT_TYPE_URLENCODED;
        }
        if (preg_match('/^<.*>$/is', $rawContent)) {
            return self::CONTENT_TYPE_XML;
        }
        return self::CONTENT_TYPE_AUTO;
    }

    /**
     * Creates signature method instance from its configuration.
356
     * @param array $signatureMethodConfig signature method configuration.
357 358 359 360 361 362 363 364 365 366 367 368
     * @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.
369
     * @param array $tokenConfig token configuration.
370 371 372 373 374 375 376 377 378 379 380 381
     * @return OAuthToken token instance.
     */
    protected function createToken(array $tokenConfig = [])
    {
        if (!array_key_exists('class', $tokenConfig)) {
            $tokenConfig['class'] = OAuthToken::className();
        }
        return Yii::createObject($tokenConfig);
    }

    /**
     * Composes URL from base URL and GET params.
382 383
     * @param string $url base URL.
     * @param array $params GET params.
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
     * @return string composed URL.
     */
    protected function composeUrl($url, array $params = [])
    {
        if (strpos($url, '?') === false) {
            $url .= '?';
        } else {
            $url .= '&';
        }
        $url .= http_build_query($params, '', '&', PHP_QUERY_RFC3986);
        return $url;
    }

    /**
     * Saves token as persistent state.
399 400
     * @param OAuthToken $token auth token
     * @return static self reference.
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
     */
    protected function saveAccessToken(OAuthToken $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()) {
                $token = $this->refreshAccessToken($token);
            }
        }
        return $token;
    }

    /**
     * Sets persistent state.
425 426
     * @param string $key state key.
     * @param mixed $value state value
427 428 429 430 431 432 433 434 435 436 437 438
     * @return static self reference.
     */
    protected function setState($key, $value)
    {
        $session = Yii::$app->getSession();
        $key = $this->getStateKeyPrefix() . $key;
        $session->set($key, $value);
        return $this;
    }

    /**
     * Returns persistent state value.
439 440
     * @param string $key state key.
     * @return mixed state value.
441 442 443 444 445 446 447 448 449 450 451
     */
    protected function getState($key)
    {
        $session = Yii::$app->getSession();
        $key = $this->getStateKeyPrefix() . $key;
        $value = $session->get($key);
        return $value;
    }

    /**
     * Removes persistent state value.
452
     * @param string $key state key.
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
     * @return boolean success.
     */
    protected function removeState($key)
    {
        $session = Yii::$app->getSession();
        $key = $this->getStateKeyPrefix() . $key;
        $session->remove($key);
        return true;
    }

    /**
     * Returns session key prefix, which is used to store internal states.
     * @return string session key prefix.
     */
    protected function getStateKeyPrefix()
    {
        return get_class($this) . '_' . sha1($this->authUrl) . '_';
    }

    /**
     * Performs request to the OAuth API.
474 475 476
     * @param string $apiSubUrl API sub URL, which will be append to [[apiBaseUrl]], or absolute API URL.
     * @param string $method request method.
     * @param array $params request parameters.
477
     * @param array $headers additional request headers.
478
     * @return array API response
479 480
     * @throws Exception on failure.
     */
481
    public function api($apiSubUrl, $method = 'GET', array $params = [], array $headers = [])
482 483 484 485 486 487 488 489 490 491
    {
        if (preg_match('/^https?:\\/\\//is', $apiSubUrl)) {
            $url = $apiSubUrl;
        } else {
            $url = $this->apiBaseUrl . '/' . $apiSubUrl;
        }
        $accessToken = $this->getAccessToken();
        if (!is_object($accessToken) || !$accessToken->getIsValid()) {
            throw new Exception('Invalid access token.');
        }
492
        return $this->apiInternal($accessToken, $url, $method, $params, $headers);
493 494 495 496
    }

    /**
     * Composes HTTP request CUrl options, which will be merged with the default ones.
497 498 499 500
     * @param string $method request type.
     * @param string $url request URL.
     * @param array $params request params.
     * @return array CUrl options.
501 502 503 504 505 506
     * @throws Exception on failure.
     */
    abstract protected function composeRequestCurlOptions($method, $url, array $params);

    /**
     * Gets new auth token to replace expired one.
507
     * @param OAuthToken $token expired auth token.
508 509 510 511 512 513
     * @return OAuthToken new auth token.
     */
    abstract public function refreshAccessToken(OAuthToken $token);

    /**
     * Performs request to the OAuth API.
514 515 516 517
     * @param OAuthToken $accessToken actual access token.
     * @param string $url absolute API URL.
     * @param string $method request method.
     * @param array $params request parameters.
518
     * @param array $headers additional request headers.
519 520
     * @return array API response.
     * @throws Exception on failure.
521
     */
522
    abstract protected function apiInternal($accessToken, $url, $method, array $params, array $headers);
Luciano Baraglia committed
523
}