update 1.0.8.0

Commits for version update
This commit is contained in:
Manish Verma
2016-10-17 12:02:27 +05:30
parent dec927987b
commit 76e85db070
9674 changed files with 495757 additions and 58922 deletions

View File

@@ -0,0 +1,29 @@
<?php
namespace League\OAuth1\Client\Credentials;
class ClientCredentials extends Credentials implements ClientCredentialsInterface
{
/**
* The credentials callback URI.
*
* @var string
*/
protected $callbackUri;
/**
* {@inheritDoc}
*/
public function getCallbackUri()
{
return $this->callbackUri;
}
/**
* {@inheritDoc}
*/
public function setCallbackUri($callbackUri)
{
$this->callbackUri = $callbackUri;
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace League\OAuth1\Client\Credentials;
interface ClientCredentialsInterface extends CredentialsInterface
{
/**
* Get the credentials callback URI.
*
* @return string
*/
public function getCallbackUri();
/**
* Set the credentials callback URI.
*
* @return string
*/
public function setCallbackUri($callbackUri);
}

View File

@@ -0,0 +1,52 @@
<?php
namespace League\OAuth1\Client\Credentials;
abstract class Credentials implements CredentialsInterface
{
/**
* The credentials identifier.
*
* @var string
*/
protected $identifier;
/**
* The credentials secret.
*
* @var string
*/
protected $secret;
/**
* {@inheritDoc}
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* {@inheritDoc}
*/
public function setIdentifier($identifier)
{
$this->identifier = $identifier;
}
/**
* {@inheritDoc}
*/
public function getSecret()
{
return $this->secret;
}
/**
* {@inheritDoc}
*/
public function setSecret($secret)
{
$this->secret = $secret;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace League\OAuth1\Client\Credentials;
use Exception;
class CredentialsException extends Exception
{
}

View File

@@ -0,0 +1,34 @@
<?php
namespace League\OAuth1\Client\Credentials;
interface CredentialsInterface
{
/**
* Get the credentials identifier.
*
* @return string
*/
public function getIdentifier();
/**
* Set the credentials identifier.
*
* @param string $identifier
*/
public function setIdentifier($identifier);
/**
* Get the credentials secret.
*
* @return string
*/
public function getSecret();
/**
* Set the credentials secret.
*
* @param string $secret
*/
public function setSecret($secret);
}

View File

@@ -0,0 +1,7 @@
<?php
namespace League\OAuth1\Client\Credentials;
class TemporaryCredentials extends Credentials implements CredentialsInterface
{
}

View File

@@ -0,0 +1,7 @@
<?php
namespace League\OAuth1\Client\Credentials;
class TokenCredentials extends Credentials implements CredentialsInterface
{
}

View File

@@ -0,0 +1,96 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Bitbucket extends Server
{
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return 'https://bitbucket.org/api/1.0/oauth/request_token';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return 'https://bitbucket.org/api/1.0/oauth/authenticate';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return 'https://bitbucket.org/api/1.0/oauth/access_token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return 'https://bitbucket.org/api/1.0/user';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User();
$user->uid = $data['user']['username'];
$user->nickname = $data['user']['username'];
$user->name = $data['user']['display_name'];
$user->firstName = $data['user']['first_name'];
$user->lastName = $data['user']['last_name'];
$user->imageUrl = $data['user']['avatar'];
$used = array('username', 'display_name', 'avatar');
foreach ($data as $key => $value) {
if (strpos($key, 'url') !== false) {
if (!in_array($key, $used)) {
$used[] = $key;
}
$user->urls[$key] = $value;
}
}
// Save all extra data
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['user']['username'];
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['user']['display_name'];
}
}

View File

@@ -0,0 +1,212 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;
/**
* Magento OAuth 1.0a.
*
* This class reflects two Magento oddities:
* - Magento expects the oauth_verifier to be located in the header instead of
* the post body.
* - Magento expects the Accept to be located in the header
*
* Additionally, this is initialized with two additional parameters:
* - Boolean 'admin' to use the admin vs customer
* - String 'host' with the path to the magento host
*/
class Magento extends Server
{
/**
* Admin url.
*
* @var string
*/
protected $adminUrl;
/**
* Base uri.
*
* @var string
*/
protected $baseUri;
/**
* Server is admin.
*
* @var bool
*/
protected $isAdmin = false;
/**
* oauth_verifier stored for use with.
*
* @var string
*/
private $verifier;
/**
* {@inheritDoc}
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
parent::__construct($clientCredentials, $signature);
if (is_array($clientCredentials)) {
$this->parseConfigurationArray($clientCredentials);
}
}
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return $this->baseUri.'/oauth/initiate';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return $this->isAdmin
? $this->adminUrl
: $this->baseUri.'/oauth/authorize';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return $this->baseUri.'/oauth/token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return $this->baseUri.'/api/rest/customers';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
if (!is_array($data) || !count($data)) {
throw new \Exception('Not possible to get user info');
}
$id = key($data);
$data = current($data);
$user = new User();
$user->uid = $id;
$mapping = array(
'email' => 'email',
'firstName' => 'firstname',
'lastName' => 'lastname',
);
foreach ($mapping as $userKey => $dataKey) {
if (!isset($data[$dataKey])) {
continue;
}
$user->{$userKey} = $data[$dataKey];
}
$user->extra = array_diff_key($data, array_flip($mapping));
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return key($data);
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
$data = current($data);
if (!isset($data['email'])) {
return;
}
return $data['email'];
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return;
}
/**
* {@inheritDoc}
*/
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier)
{
$this->verifier = $verifier;
return parent::getTokenCredentials($temporaryCredentials, $temporaryIdentifier, $verifier);
}
/**
* {@inheritDoc}
*/
protected function additionalProtocolParameters()
{
return array(
'oauth_verifier' => $this->verifier,
);
}
protected function getHttpClientDefaultHeaders()
{
$defaultHeaders = parent::getHttpClientDefaultHeaders();
// Accept header is required, @see Mage_Api2_Model_Renderer::factory
$defaultHeaders['Accept'] = 'application/json';
return $defaultHeaders;
}
/**
* Parse configuration array to set attributes.
*
* @param array $configuration
* @throws \Exception
*/
private function parseConfigurationArray(array $configuration = array())
{
if (!isset($configuration['host'])) {
throw new \Exception('Missing Magento Host');
}
$url = parse_url($configuration['host']);
$this->baseUri = sprintf('%s://%s', $url['scheme'], $url['host']);
if (isset($url['port'])) {
$this->baseUri .= ':'.$url['port'];
}
if (isset($url['path'])) {
$this->baseUri .= '/'.trim($url['path'], '/');
}
$this->isAdmin = !empty($configuration['admin']);
if (!empty($configuration['adminUrl'])) {
$this->adminUrl = $configuration['adminUrl'].'/oauth_authorize';
} else {
$this->adminUrl = $this->baseUri.'/admin/oauth_authorize';
}
}
}

View File

@@ -0,0 +1,695 @@
<?php
namespace League\OAuth1\Client\Server;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\BadResponseException;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\ClientCredentials;
use League\OAuth1\Client\Credentials\CredentialsInterface;
use League\OAuth1\Client\Credentials\CredentialsException;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\HmacSha1Signature;
use League\OAuth1\Client\Signature\SignatureInterface;
abstract class Server
{
/**
* Client credentials.
*
* @var ClientCredentials
*/
protected $clientCredentials;
/**
* Signature.
*
* @var SignatureInterface
*/
protected $signature;
/**
* The response type for data returned from API calls.
*
* @var string
*/
protected $responseType = 'json';
/**
* Cached user details response.
*
* @var unknown
*/
protected $cachedUserDetailsResponse;
/**
* Optional user agent.
*
* @var string
*/
protected $userAgent;
/**
* Create a new server instance.
*
* @param ClientCredentialsInterface|array $clientCredentials
* @param SignatureInterface $signature
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
// Pass through an array or client credentials, we don't care
if (is_array($clientCredentials)) {
$clientCredentials = $this->createClientCredentials($clientCredentials);
} elseif (!$clientCredentials instanceof ClientCredentialsInterface) {
throw new \InvalidArgumentException('Client credentials must be an array or valid object.');
}
$this->clientCredentials = $clientCredentials;
$this->signature = $signature ?: new HmacSha1Signature($clientCredentials);
}
/**
* Gets temporary credentials by performing a request to
* the server.
*
* @return TemporaryCredentials
*/
public function getTemporaryCredentials()
{
$uri = $this->urlTemporaryCredentials();
$client = $this->createHttpClient();
$header = $this->temporaryCredentialsProtocolHeader($uri);
$authorizationHeader = array('Authorization' => $header);
$headers = $this->buildHttpClientHeaders($authorizationHeader);
try {
$response = $client->post($uri, [
'headers' => $headers,
]);
} catch (BadResponseException $e) {
return $this->handleTemporaryCredentialsBadResponse($e);
}
return $this->createTemporaryCredentials((string) $response->getBody());
}
/**
* Get the authorization URL by passing in the temporary credentials
* identifier or an object instance.
*
* @param TemporaryCredentials|string $temporaryIdentifier
*
* @return string
*/
public function getAuthorizationUrl($temporaryIdentifier)
{
// Somebody can pass through an instance of temporary
// credentials and we'll extract the identifier from there.
if ($temporaryIdentifier instanceof TemporaryCredentials) {
$temporaryIdentifier = $temporaryIdentifier->getIdentifier();
}
$parameters = array('oauth_token' => $temporaryIdentifier);
$url = $this->urlAuthorization();
$queryString = http_build_query($parameters);
return $this->buildUrl($url, $queryString);
}
/**
* Redirect the client to the authorization URL.
*
* @param TemporaryCredentials|string $temporaryIdentifier
*/
public function authorize($temporaryIdentifier)
{
$url = $this->getAuthorizationUrl($temporaryIdentifier);
header('Location: '.$url);
return;
}
/**
* Retrieves token credentials by passing in the temporary credentials,
* the temporary credentials identifier as passed back by the server
* and finally the verifier code.
*
* @param TemporaryCredentials $temporaryCredentials
* @param string $temporaryIdentifier
* @param string $verifier
*
* @return TokenCredentials
*/
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier)
{
if ($temporaryIdentifier !== $temporaryCredentials->getIdentifier()) {
throw new \InvalidArgumentException(
'Temporary identifier passed back by server does not match that of stored temporary credentials.
Potential man-in-the-middle.'
);
}
$uri = $this->urlTokenCredentials();
$bodyParameters = array('oauth_verifier' => $verifier);
$client = $this->createHttpClient();
$headers = $this->getHeaders($temporaryCredentials, 'POST', $uri, $bodyParameters);
try {
$response = $client->post($uri, [
'headers' => $headers,
'form_params' => $bodyParameters,
]);
} catch (BadResponseException $e) {
return $this->handleTokenCredentialsBadResponse($e);
}
return $this->createTokenCredentials((string) $response->getBody());
}
/**
* Get user details by providing valid token credentials.
*
* @param TokenCredentials $tokenCredentials
* @param bool $force
*
* @return \League\OAuth1\Client\Server\User
*/
public function getUserDetails(TokenCredentials $tokenCredentials, $force = false)
{
$data = $this->fetchUserDetails($tokenCredentials, $force);
return $this->userDetails($data, $tokenCredentials);
}
/**
* Get the user's unique identifier (primary key).
*
* @param TokenCredentials $tokenCredentials
* @param bool $force
*
* @return string|int
*/
public function getUserUid(TokenCredentials $tokenCredentials, $force = false)
{
$data = $this->fetchUserDetails($tokenCredentials, $force);
return $this->userUid($data, $tokenCredentials);
}
/**
* Get the user's email, if available.
*
* @param TokenCredentials $tokenCredentials
* @param bool $force
*
* @return string|null
*/
public function getUserEmail(TokenCredentials $tokenCredentials, $force = false)
{
$data = $this->fetchUserDetails($tokenCredentials, $force);
return $this->userEmail($data, $tokenCredentials);
}
/**
* Get the user's screen name (username), if available.
*
* @param TokenCredentials $tokenCredentials
* @param bool $force
*
* @return string
*/
public function getUserScreenName(TokenCredentials $tokenCredentials, $force = false)
{
$data = $this->fetchUserDetails($tokenCredentials, $force);
return $this->userScreenName($data, $tokenCredentials);
}
/**
* Fetch user details from the remote service.
*
* @param TokenCredentials $tokenCredentials
* @param bool $force
*
* @return array HTTP client response
*/
protected function fetchUserDetails(TokenCredentials $tokenCredentials, $force = true)
{
if (!$this->cachedUserDetailsResponse || $force) {
$url = $this->urlUserDetails();
$client = $this->createHttpClient();
$headers = $this->getHeaders($tokenCredentials, 'GET', $url);
try {
$response = $client->get($url, [
'headers' => $headers,
]);
} catch (BadResponseException $e) {
$response = $e->getResponse();
$body = $response->getBody();
$statusCode = $response->getStatusCode();
throw new \Exception(
"Received error [$body] with status code [$statusCode] when retrieving token credentials."
);
}
switch ($this->responseType) {
case 'json':
$this->cachedUserDetailsResponse = json_decode((string) $response->getBody(), true);
break;
case 'xml':
$this->cachedUserDetailsResponse = simplexml_load_string((string) $response->getBody());
break;
case 'string':
parse_str((string) $response->getBody(), $this->cachedUserDetailsResponse);
break;
default:
throw new \InvalidArgumentException("Invalid response type [{$this->responseType}].");
}
}
return $this->cachedUserDetailsResponse;
}
/**
* Get the client credentials associated with the server.
*
* @return ClientCredentialsInterface
*/
public function getClientCredentials()
{
return $this->clientCredentials;
}
/**
* Get the signature associated with the server.
*
* @return SignatureInterface
*/
public function getSignature()
{
return $this->signature;
}
/**
* Creates a Guzzle HTTP client for the given URL.
*
* @return GuzzleHttpClient
*/
public function createHttpClient()
{
return new GuzzleHttpClient();
}
/**
* Set the user agent value.
*
* @param string $userAgent
*
* @return Server
*/
public function setUserAgent($userAgent = null)
{
$this->userAgent = $userAgent;
return $this;
}
/**
* Get all headers required to created an authenticated request.
*
* @param CredentialsInterface $credentials
* @param string $method
* @param string $url
* @param array $bodyParameters
*
* @return array
*/
public function getHeaders(CredentialsInterface $credentials, $method, $url, array $bodyParameters = array())
{
$header = $this->protocolHeader(strtoupper($method), $url, $credentials, $bodyParameters);
$authorizationHeader = array('Authorization' => $header);
$headers = $this->buildHttpClientHeaders($authorizationHeader);
return $headers;
}
/**
* Get Guzzle HTTP client default headers.
*
* @return array
*/
protected function getHttpClientDefaultHeaders()
{
$defaultHeaders = array();
if (!empty($this->userAgent)) {
$defaultHeaders['User-Agent'] = $this->userAgent;
}
return $defaultHeaders;
}
/**
* Build Guzzle HTTP client headers.
*
* @return array
*/
protected function buildHttpClientHeaders($headers = array())
{
$defaultHeaders = $this->getHttpClientDefaultHeaders();
return array_merge($headers, $defaultHeaders);
}
/**
* Creates a client credentials instance from an array of credentials.
*
* @param array $clientCredentials
*
* @return ClientCredentials
*/
protected function createClientCredentials(array $clientCredentials)
{
$keys = array('identifier', 'secret');
foreach ($keys as $key) {
if (!isset($clientCredentials[$key])) {
throw new \InvalidArgumentException("Missing client credentials key [$key] from options.");
}
}
$_clientCredentials = new ClientCredentials();
$_clientCredentials->setIdentifier($clientCredentials['identifier']);
$_clientCredentials->setSecret($clientCredentials['secret']);
if (isset($clientCredentials['callback_uri'])) {
$_clientCredentials->setCallbackUri($clientCredentials['callback_uri']);
}
return $_clientCredentials;
}
/**
* Handle a bad response coming back when getting temporary credentials.
*
* @param BadResponseException $e
*
* @throws CredentialsException
*/
protected function handleTemporaryCredentialsBadResponse(BadResponseException $e)
{
$response = $e->getResponse();
$body = $response->getBody();
$statusCode = $response->getStatusCode();
throw new CredentialsException(
"Received HTTP status code [$statusCode] with message \"$body\" when getting temporary credentials."
);
}
/**
* Creates temporary credentials from the body response.
*
* @param string $body
*
* @return TemporaryCredentials
*/
protected function createTemporaryCredentials($body)
{
parse_str($body, $data);
if (!$data || !is_array($data)) {
throw new CredentialsException('Unable to parse temporary credentials response.');
}
if (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] != 'true') {
throw new CredentialsException('Error in retrieving temporary credentials.');
}
$temporaryCredentials = new TemporaryCredentials();
$temporaryCredentials->setIdentifier($data['oauth_token']);
$temporaryCredentials->setSecret($data['oauth_token_secret']);
return $temporaryCredentials;
}
/**
* Handle a bad response coming back when getting token credentials.
*
* @param BadResponseException $e
*
* @throws CredentialsException
*/
protected function handleTokenCredentialsBadResponse(BadResponseException $e)
{
$response = $e->getResponse();
$body = $response->getBody();
$statusCode = $response->getStatusCode();
throw new CredentialsException(
"Received HTTP status code [$statusCode] with message \"$body\" when getting token credentials."
);
}
/**
* Creates token credentials from the body response.
*
* @param string $body
*
* @return TokenCredentials
*/
protected function createTokenCredentials($body)
{
parse_str($body, $data);
if (!$data || !is_array($data)) {
throw new CredentialsException('Unable to parse token credentials response.');
}
if (isset($data['error'])) {
throw new CredentialsException("Error [{$data['error']}] in retrieving token credentials.");
}
$tokenCredentials = new TokenCredentials();
$tokenCredentials->setIdentifier($data['oauth_token']);
$tokenCredentials->setSecret($data['oauth_token_secret']);
return $tokenCredentials;
}
/**
* Get the base protocol parameters for an OAuth request.
* Each request builds on these parameters.
*
* @return array
*
* @see OAuth 1.0 RFC 5849 Section 3.1
*/
protected function baseProtocolParameters()
{
$dateTime = new \DateTime();
return array(
'oauth_consumer_key' => $this->clientCredentials->getIdentifier(),
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => $this->signature->method(),
'oauth_timestamp' => $dateTime->format('U'),
'oauth_version' => '1.0',
);
}
/**
* Any additional required protocol parameters for an
* OAuth request.
*
* @return array
*/
protected function additionalProtocolParameters()
{
return array();
}
/**
* Generate the OAuth protocol header for a temporary credentials
* request, based on the URI.
*
* @param string $uri
*
* @return string
*/
protected function temporaryCredentialsProtocolHeader($uri)
{
$parameters = array_merge($this->baseProtocolParameters(), array(
'oauth_callback' => $this->clientCredentials->getCallbackUri(),
));
$parameters['oauth_signature'] = $this->signature->sign($uri, $parameters, 'POST');
return $this->normalizeProtocolParameters($parameters);
}
/**
* Generate the OAuth protocol header for requests other than temporary
* credentials, based on the URI, method, given credentials & body query
* string.
*
* @param string $method
* @param string $uri
* @param CredentialsInterface $credentials
* @param array $bodyParameters
*
* @return string
*/
protected function protocolHeader($method, $uri, CredentialsInterface $credentials, array $bodyParameters = array())
{
$parameters = array_merge(
$this->baseProtocolParameters(),
$this->additionalProtocolParameters(),
array(
'oauth_token' => $credentials->getIdentifier(),
)
);
$this->signature->setCredentials($credentials);
$parameters['oauth_signature'] = $this->signature->sign(
$uri,
array_merge($parameters, $bodyParameters),
$method
);
return $this->normalizeProtocolParameters($parameters);
}
/**
* Takes an array of protocol parameters and normalizes them
* to be used as a HTTP header.
*
* @param array $parameters
*
* @return string
*/
protected function normalizeProtocolParameters(array $parameters)
{
array_walk($parameters, function (&$value, $key) {
$value = rawurlencode($key).'="'.rawurlencode($value).'"';
});
return 'OAuth '.implode(', ', $parameters);
}
/**
* Generate a random string.
*
* @param int $length
*
* @return string
*
* @see OAuth 1.0 RFC 5849 Section 3.3
*/
protected function nonce($length = 32)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}
/**
* Build a url by combining hostname and query string after checking for
* exisiting '?' character in host.
*
* @param string $host
* @param string $queryString
*
* @return string
*/
protected function buildUrl($host, $queryString)
{
return $host.(strpos($host, '?') !== false ? '&' : '?').$queryString;
}
/**
* Get the URL for retrieving temporary credentials.
*
* @return string
*/
abstract public function urlTemporaryCredentials();
/**
* Get the URL for redirecting the resource owner to authorize the client.
*
* @return string
*/
abstract public function urlAuthorization();
/**
* Get the URL retrieving token credentials.
*
* @return string
*/
abstract public function urlTokenCredentials();
/**
* Get the URL for retrieving user details.
*
* @return string
*/
abstract public function urlUserDetails();
/**
* Take the decoded data from the user details URL and convert
* it to a User object.
*
* @param mixed $data
* @param TokenCredentials $tokenCredentials
*
* @return User
*/
abstract public function userDetails($data, TokenCredentials $tokenCredentials);
/**
* Take the decoded data from the user details URL and extract
* the user's UID.
*
* @param mixed $data
* @param TokenCredentials $tokenCredentials
*
* @return string|int
*/
abstract public function userUid($data, TokenCredentials $tokenCredentials);
/**
* Take the decoded data from the user details URL and extract
* the user's email.
*
* @param mixed $data
* @param TokenCredentials $tokenCredentials
*
* @return string
*/
abstract public function userEmail($data, TokenCredentials $tokenCredentials);
/**
* Take the decoded data from the user details URL and extract
* the user's screen name.
*
* @param mixed $data
* @param TokenCredentials $tokenCredentials
*
* @return string
*/
abstract public function userScreenName($data, TokenCredentials $tokenCredentials);
}

View File

@@ -0,0 +1,252 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Trello extends Server
{
/**
* Access token.
*
* @var string
*/
protected $accessToken;
/**
* Application expiration.
*
* @var string
*/
protected $applicationExpiration;
/**
* Application key.
*
* @var string
*/
protected $applicationKey;
/**
* Application name.
*
* @var string
*/
protected $applicationName;
/**
* Application scope.
*
* @var string
*/
protected $applicationScope;
/**
* {@inheritDoc}
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
parent::__construct($clientCredentials, $signature);
if (is_array($clientCredentials)) {
$this->parseConfiguration($clientCredentials);
}
}
/**
* Set the access token.
*
* @param string $accessToken
*
* @return Trello
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* Set the application expiration.
*
* @param string $applicationExpiration
*
* @return Trello
*/
public function setApplicationExpiration($applicationExpiration)
{
$this->applicationExpiration = $applicationExpiration;
return $this;
}
/**
* Get application expiration.
*
* @return string
*/
public function getApplicationExpiration()
{
return $this->applicationExpiration ?: '1day';
}
/**
* Set the application name.
*
* @param string $applicationName
*
* @return Trello
*/
public function setApplicationName($applicationName)
{
$this->applicationName = $applicationName;
return $this;
}
/**
* Get application name.
*
* @return string|null
*/
public function getApplicationName()
{
return $this->applicationName ?: null;
}
/**
* Set the application scope.
*
* @param string $applicationScope
*
* @return Trello
*/
public function setApplicationScope($applicationScope)
{
$this->applicationScope = $applicationScope;
return $this;
}
/**
* Get application scope.
*
* @return string
*/
public function getApplicationScope()
{
return $this->applicationScope ?: 'read';
}
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return 'https://trello.com/1/OAuthGetRequestToken';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return 'https://trello.com/1/OAuthAuthorizeToken?'.
$this->buildAuthorizationQueryParameters();
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return 'https://trello.com/1/OAuthGetAccessToken';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return 'https://trello.com/1/members/me?key='.$this->applicationKey.'&token='.$this->accessToken;
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User();
$user->nickname = $data['username'];
$user->name = $data['fullName'];
$user->imageUrl = null;
$user->extra = (array) $data;
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['id'];
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['username'];
}
/**
* Build authorization query parameters.
*
* @return string
*/
private function buildAuthorizationQueryParameters()
{
$params = array(
'response_type' => 'fragment',
'scope' => $this->getApplicationScope(),
'expiration' => $this->getApplicationExpiration(),
'name' => $this->getApplicationName(),
);
return http_build_query($params);
}
/**
* Parse configuration array to set attributes.
*
* @param array $configuration
*/
private function parseConfiguration(array $configuration = array())
{
$configToPropertyMap = array(
'identifier' => 'applicationKey',
'expiration' => 'applicationExpiration',
'name' => 'applicationName',
'scope' => 'applicationScope',
);
foreach ($configToPropertyMap as $config => $property) {
if (isset($configuration[$config])) {
$this->$property = $configuration[$config];
}
}
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Tumblr extends Server
{
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return 'https://www.tumblr.com/oauth/request_token';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return 'https://www.tumblr.com/oauth/authorize';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return 'https://www.tumblr.com/oauth/access_token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return 'https://api.tumblr.com/v2/user/info';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
// If the API has broke, return nothing
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
}
$data = $data['response']['user'];
$user = new User();
$user->nickname = $data['name'];
// Save all extra data
$used = array('name');
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
}
$data = $data['response']['user'];
return $data['name'];
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
}
$data = $data['response']['user'];
return $data['name'];
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Twitter extends Server
{
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return 'https://api.twitter.com/oauth/request_token';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return 'https://api.twitter.com/oauth/authenticate';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return 'https://api.twitter.com/oauth/access_token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User();
$user->uid = $data['id_str'];
$user->nickname = $data['screen_name'];
$user->name = $data['name'];
$user->location = $data['location'];
$user->description = $data['description'];
$user->imageUrl = $data['profile_image_url'];
$user->email = null;
if (isset($data['email'])) {
$user->email = $data['email'];
}
$used = array('id', 'screen_name', 'name', 'location', 'description', 'profile_image_url', 'email');
foreach ($data as $key => $value) {
if (strpos($key, 'url') !== false) {
if (!in_array($key, $used)) {
$used[] = $key;
}
$user->urls[$key] = $value;
}
}
// Save all extra data
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['id'];
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['name'];
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace League\OAuth1\Client\Server;
class User implements \IteratorAggregate
{
/**
* The user's unique ID.
*
* @var mixed
*/
public $uid = null;
/**
* The user's nickname (screen name, username etc).
*
* @var mixed
*/
public $nickname = null;
/**
* The user's name.
*
* @var mixed
*/
public $name = null;
/**
* The user's first name.
*
* @var string
*/
public $firstName = null;
/**
* The user's last name.
*
* @var string
*/
public $lastName = null;
/**
* The user's email.
*
* @var string
*/
public $email = null;
/**
* The user's location.
*
* @var string|array
*/
public $location = null;
/**
* The user's description.
*
* @var string
*/
public $description = null;
/**
* The user's image URL.
*
* @var string
*/
public $imageUrl = null;
/**
* The users' URLs.
*
* @var string|array
*/
public $urls = array();
/**
* Any extra data.
*
* @var array
*/
public $extra = array();
/**
* Set a property on the user.
*
* @param string $key
* @param mixed $value
*/
public function __set($key, $value)
{
if (isset($this->{$key})) {
$this->{$key} = $value;
}
}
/**
* Get a property from the user.
*
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
if (isset($this->{$key})) {
return $this->{$key};
}
}
/**
* {@inheritDoc}
*/
public function getIterator()
{
return new \ArrayIterator($this);
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace League\OAuth1\Client\Server;
use InvalidArgumentException;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
class Uservoice extends Server
{
/**
* The base URL, used to generate the auth endpoints.
*
* @var string
*/
protected $base;
/**
* {@inheritDoc}
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
parent::__construct($clientCredentials, $signature);
if (is_array($clientCredentials)) {
$this->parseConfigurationArray($clientCredentials);
}
}
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return $this->base.'/oauth/request_token';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return $this->base.'/oauth/authorize';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return $this->base.'/oauth/access_token';
}
/**
* {@inheritdoc}
*/
public function urlUserDetails()
{
return $this->base.'/api/v1/users/current.json';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User();
$user->uid = $data['user']['id'];
$user->name = $data['user']['name'];
$user->imageUrl = $data['user']['avatar_url'];
$user->email = $data['user']['email'];
if ($data['user']['name']) {
$parts = explode(' ', $data['user']['name']);
if (count($parts) > 0) {
$user->firstName = $parts[0];
}
if (count($parts) > 1) {
$user->lastName = $parts[1];
}
}
$user->urls[] = $data['user']['url'];
return $user;
}
/**
* {@inheritdoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['user']['id'];
}
/**
* {@inheritdoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return $data['user']['email'];
}
/**
* {@inheritdoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['user']['name'];
}
/**
* Parse configuration array to set attributes.
*
* @param array $configuration
*
* @throws InvalidArgumentException
*/
private function parseConfigurationArray(array $configuration = array())
{
if (isset($configuration['host'])) {
throw new InvalidArgumentException('Missing host');
}
$this->base = trim($configuration['host'], '/');
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Xing extends Server
{
const XING_API_ENDPOINT = 'https://api.xing.com';
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return self::XING_API_ENDPOINT . '/v1/request_token';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return self::XING_API_ENDPOINT . '/v1/authorize';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return self::XING_API_ENDPOINT . '/v1/access_token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return self::XING_API_ENDPOINT . '/v1/users/me';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['users'][0])) {
throw new \Exception('Not possible to get user info');
}
$data = $data['users'][0];
$user = new User();
$user->uid = $data['id'];
$user->nickname = $data['display_name'];
$user->name = $data['display_name'];
$user->firstName = $data['first_name'];
$user->lastName = $data['last_name'];
$user->location = $data['private_address']['country'];
if ($user->location == '') {
$user->location = $data['business_address']['country'];
}
$user->description = $data['employment_status'];
$user->imageUrl = $data['photo_urls']['maxi_thumb'];
$user->email = $data['active_email'];
$user->urls['permalink'] = $data['permalink'];
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
$data = $data['users'][0];
return $data['id'];
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
$data = $data['users'][0];
return $data['active_email'];
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
$data = $data['users'][0];
return $data['display_name'];
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace League\OAuth1\Client\Signature;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Uri;
class HmacSha1Signature extends Signature implements SignatureInterface
{
/**
* {@inheritDoc}
*/
public function method()
{
return 'HMAC-SHA1';
}
/**
* {@inheritDoc}
*/
public function sign($uri, array $parameters = array(), $method = 'POST')
{
$url = $this->createUrl($uri);
$baseString = $this->baseString($url, $method, $parameters);
return base64_encode($this->hash($baseString));
}
/**
* Create a Guzzle url for the given URI.
*
* @param string $uri
*
* @return Url
*/
protected function createUrl($uri)
{
return Psr7\uri_for($uri);
}
/**
* Generate a base string for a HMAC-SHA1 signature
* based on the given a url, method, and any parameters.
*
* @param Url $url
* @param string $method
* @param array $parameters
*
* @return string
*/
protected function baseString(Uri $url, $method = 'POST', array $parameters = array())
{
$baseString = rawurlencode($method).'&';
$schemeHostPath = Uri::fromParts(array(
'scheme' => $url->getScheme(),
'host' => $url->getHost(),
'path' => $url->getPath(),
));
$baseString .= rawurlencode($schemeHostPath).'&';
$data = array();
parse_str($url->getQuery(), $query);
$data = array_merge($query, $parameters);
// normalize data key/values
array_walk_recursive($data, function (&$key, &$value) {
$key = rawurlencode(rawurldecode($key));
$value = rawurlencode(rawurldecode($value));
});
ksort($data);
$baseString .= $this->queryStringFromData($data);
return $baseString;
}
/**
* Creates an array of rawurlencoded strings out of each array key/value pair
* Handles multi-demensional arrays recursively.
*
* @param array $data Array of parameters to convert.
* @param array $queryParams Array to extend. False by default.
* @param string $prevKey Optional Array key to append
*
* @return string rawurlencoded string version of data
*/
protected function queryStringFromData($data, $queryParams = false, $prevKey = '')
{
if ($initial = (false === $queryParams)) {
$queryParams = array();
}
foreach ($data as $key => $value) {
if ($prevKey) {
$key = $prevKey.'['.$key.']'; // Handle multi-dimensional array
}
if (is_array($value)) {
$queryParams = $this->queryStringFromData($value, $queryParams, $key);
} else {
$queryParams[] = rawurlencode($key.'='.$value); // join with equals sign
}
}
if ($initial) {
return implode('%26', $queryParams); // join with ampersand
}
return $queryParams;
}
/**
* Hashes a string with the signature's key.
*
* @param string $string
*
* @return string
*/
protected function hash($string)
{
return hash_hmac('sha1', $string, $this->key(), true);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace League\OAuth1\Client\Signature;
class PlainTextSignature extends Signature implements SignatureInterface
{
/**
* {@inheritDoc}
*/
public function method()
{
return 'PLAINTEXT';
}
/**
* {@inheritDoc}
*/
public function sign($uri, array $parameters = array(), $method = 'POST')
{
return $this->key();
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace League\OAuth1\Client\Signature;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\CredentialsInterface;
abstract class Signature implements SignatureInterface
{
/**
* The client credentials.
*
* @var ClientCredentialsInterface
*/
protected $clientCredentials;
/**
* The (temporary or token) credentials.
*
* @var CredentialsInterface
*/
protected $credentials;
/**
* {@inheritDoc}
*/
public function __construct(ClientCredentialsInterface $clientCredentials)
{
$this->clientCredentials = $clientCredentials;
}
/**
* {@inheritDoc}
*/
public function setCredentials(CredentialsInterface $credentials)
{
$this->credentials = $credentials;
}
/**
* Generate a signing key.
*
* @return string
*/
protected function key()
{
$key = rawurlencode($this->clientCredentials->getSecret()).'&';
if ($this->credentials !== null) {
$key .= rawurlencode($this->credentials->getSecret());
}
return $key;
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace League\OAuth1\Client\Signature;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\CredentialsInterface;
interface SignatureInterface
{
/**
* Create a new signature instance.
*
* @param ClientCredentialsInterface $clientCredentials
*/
public function __construct(ClientCredentialsInterface $clientCredentials);
/**
* Set the credentials used in the signature. These can be temporary
* credentials when getting token credentials during the OAuth
* authentication process, or token credentials when querying
* the API.
*
* @param CredentialsInterface $credentials
*/
public function setCredentials(CredentialsInterface $credentials);
/**
* Get the OAuth signature method.
*
* @return string
*/
public function method();
/**
* Sign the given request for the client.
*
* @param string $uri
* @param array $parameters
* @param string $method
*
* @return string
*/
public function sign($uri, array $parameters = array(), $method = 'POST');
}