BaseOAuth.php 13.8 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 16 17 18 19

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

/**
 * BaseClient is a base class for the OAuth clients.
 *
 * @see http://oauth.net/
 *
Qiang Xue committed
20 21 22 23 24 25 26
 * @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.
 * @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.
 *
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
{
	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 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.
	 */
Paul Klimov committed
46
	private $_returnUrl;
47 48 49
	/**
	 * @var string API base URL.
	 */
Paul Klimov committed
50
	public $apiBaseUrl;
51 52 53
	/**
	 * @var string authorize URL.
	 */
Paul Klimov committed
54
	public $authUrl;
55 56 57
	/**
	 * @var string auth request scope.
	 */
Paul Klimov committed
58
	public $scope;
59 60 61 62 63 64
	/**
	 * @var array cURL request options. Option values from this field will overwrite corresponding
	 * values from {@link defaultCurlOptions()}.
	 */
	private $_curlOptions = [];
	/**
65
	 * @var OAuthToken|array access token instance or its array configuration.
66
	 */
Paul Klimov committed
67
	private $_accessToken;
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	/**
	 * @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()
	{
Paul Klimov committed
86
		if ($this->_returnUrl === null) {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
			$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;
	}

	/**
109
	 * @param array|OAuthToken $token
110 111 112 113 114 115 116 117 118 119 120
	 */
	public function setAccessToken($token)
	{
		if (!is_object($token)) {
			$token = $this->createToken($token);
		}
		$this->_accessToken = $token;
		$this->saveAccessToken($token);
	}

	/**
121
	 * @return OAuthToken auth token instance.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	 */
	public function getAccessToken()
	{
		if (!is_object($this->_accessToken)) {
			$this->_accessToken = $this->restoreAccessToken();
		}
		return $this->_accessToken;
	}

	/**
	 * @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)) {
138
			throw new InvalidParamException('"' . get_class($this) . '::signatureMethod" should be instance of "\yii\autclient\signature\BaseMethod" or its array configuration. "' . gettype($signatureMethod) . '" has been given.');
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
		}
		$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;
	}

	/**
	 * Composes default {@link returnUrl} value.
	 * @return string return URL.
	 */
	protected function defaultReturnUrl()
	{
		return Yii::$app->getRequest()->getAbsoluteUrl();
	}

	/**
	 * Sends HTTP request.
	 * @param string $method request type.
	 * @param string $url request URL.
	 * @param array $params request params.
	 * @return array response.
	 * @throws Exception on failure.
	 */
	protected function sendRequest($method, $url, array $params = [])
	{
		$curlOptions = $this->mergeCurlOptions(
			$this->defaultCurlOptions(),
			$this->getCurlOptions(),
			array(
				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);
		}
		if ($responseHeaders['http_code'] != 200) {
			throw new Exception('Request failed with code: ' . $responseHeaders['http_code'] . ', message: ' . $response);
		}
		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.
	 * @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.
	 * @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) {
				$res[$k]=$v;
			}
		}
		return $res;
	}

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

	/**
	 * Processes raw response converting it to actual data.
	 * @param string $rawResponse raw response.
	 * @param string $contentType response content type.
	 * @throws Exception on failure.
	 * @return array actual response.
	 */
	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 = [];
270
				parse_str($rawResponse, $response);
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 347 348 349 350 351 352 353 354 355 356 357 358
				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.
	 * @param string|\SimpleXMLElement $xml xml to process.
	 * @return array XML array representation.
	 */
	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.
	 * @param array $headers request headers.
	 * @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.
	 * @param string $rawContent raw response content.
	 * @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.
	 * @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.
359
	 * @return OAuthToken token instance.
360 361 362 363
	 */
	protected function createToken(array $tokenConfig = [])
	{
		if (!array_key_exists('class', $tokenConfig)) {
364
			$tokenConfig['class'] = OAuthToken::className();
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
		}
		return Yii::createObject($tokenConfig);
	}

	/**
	 * 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 (strpos($url, '?') === false) {
			$url .= '?';
		} else {
			$url .= '&';
		}
		$url .= http_build_query($params, '', '&', PHP_QUERY_RFC3986);
		return $url;
	}

	/**
	 * Saves token as persistent state.
388
	 * @param OAuthToken $token auth token
389 390
	 * @return static self reference.
	 */
391
	protected function saveAccessToken(OAuthToken $token)
392 393 394 395 396 397
	{
		return $this->setState('token', $token);
	}

	/**
	 * Restores access token.
398
	 * @return OAuthToken auth token.
399 400 401 402 403
	 */
	protected function restoreAccessToken()
	{
		$token = $this->getState('token');
		if (is_object($token)) {
404
			/* @var $token OAuthToken */
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
			if ($token->getIsExpired()) {
				$token = $this->refreshAccessToken($token);
			}
		}
		return $token;
	}

	/**
	 * Sets persistent state.
	 * @param string $key state key.
	 * @param mixed $value state value
	 * @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.
	 * @param string $key state key.
	 * @return mixed state value.
	 */
	protected function getState($key)
	{
		$session = Yii::$app->getSession();
		$key = $this->getStateKeyPrefix() . $key;
		$value = $session->get($key);
		return $value;
	}

	/**
	 * Removes persistent state value.
	 * @param string $key state key.
	 * @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.
	 * @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.
	 * @return array API response
	 * @throws Exception on failure.
	 */
	public function api($apiSubUrl, $method = 'GET', array $params = [])
	{
		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.');
		}
		return $this->apiInternal($accessToken, $url, $method, $params);
	}

	/**
	 * Composes HTTP request CUrl options, which will be merged with the default ones.
	 * @param string $method request type.
	 * @param string $url request URL.
	 * @param array $params request params.
	 * @return array CUrl options.
	 * @throws Exception on failure.
	 */
	abstract protected function composeRequestCurlOptions($method, $url, array $params);

	/**
	 * Gets new auth token to replace expired one.
495 496
	 * @param OAuthToken $token expired auth token.
	 * @return OAuthToken new auth token.
497
	 */
498
	abstract public function refreshAccessToken(OAuthToken $token);
499 500 501

	/**
	 * Performs request to the OAuth API.
502
	 * @param OAuthToken $accessToken actual access token.
503 504 505 506 507 508 509 510
	 * @param string $url absolute API URL.
	 * @param string $method request method.
	 * @param array $params request parameters.
	 * @return array API response.
	 * @throws Exception on failure.
	 */
	abstract protected function apiInternal($accessToken, $url, $method, array $params);
}