allow vendord
All checks were successful
Build, Push and Deploy / build-and-push (push) Successful in 3m3s
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 16s
Build, Push and Deploy / deploy-staging (push) Successful in 32s
Build, Push and Deploy / deploy-production (push) Has been skipped
Build, Push and Deploy / cleanup (push) Successful in 1s

This commit is contained in:
2026-03-30 14:54:57 +07:00
parent 66aed7c4e8
commit b5e3a778ce
21316 changed files with 2777892 additions and 13 deletions

21
vendor/league/oauth1-client/LICENSE vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013 Ben Corlett <bencorlett@me.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

265
vendor/league/oauth1-client/README.md vendored Normal file
View File

@@ -0,0 +1,265 @@
# OAuth 1.0 Client
[![Latest Stable Version](https://img.shields.io/github/release/thephpleague/oauth1-client.svg?style=flat-square)](https://github.com/thephpleague/oauth1-client/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Build Status](https://img.shields.io/travis/thephpleague/oauth1-client/master.svg?style=flat-square&1)](https://travis-ci.org/thephpleague/oauth1-client)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/oauth1-client.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth1-client/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/oauth1-client.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth1-client)
[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth1-client.svg?style=flat-square)](https://packagist.org/packages/thephpleague/oauth1-client)
OAuth 1 Client is an OAuth [RFC 5849 standards-compliant](http://tools.ietf.org/html/rfc5849) library for authenticating against OAuth 1 servers.
It has built in support for:
- Bitbucket
- Magento
- Trello
- Tumblr
- Twitter
- Uservoice
- Xing
Adding support for other providers is trivial. The library requires PHP 7.1+ and is PSR-2 compatible.
### Third-Party Providers
If you would like to support other providers, please make them available as a Composer package, then link to them
below.
These providers allow integration with other providers not supported by `oauth1-client`. They may require an older version
so please help them out with a pull request if you notice this.
- [Intuit](https://packagist.org/packages/wheniwork/oauth1-intuit)
- [500px](https://packagist.org/packages/mechant/oauth1-500px)
- [Etsy](https://packagist.org/packages/y0lk/oauth1-etsy)
- [Xero](https://packagist.org/packages/Invoiced/oauth1-xero)
- [Garmin](https://packagist.org/packages/techgyani/garmin-wellness)
- [Goodreads](https://packagist.org/packages/netgalley/oauth1-goodreads)
#### Terminology (as per the RFC 5849 specification):
client
An HTTP client (per [RFC2616]) capable of making OAuth-
authenticated requests (Section 3).
server
An HTTP server (per [RFC2616]) capable of accepting OAuth-
authenticated requests (Section 3).
protected resource
An access-restricted resource that can be obtained from the
server using an OAuth-authenticated request (Section 3).
resource owner
An entity capable of accessing and controlling protected
resources by using credentials to authenticate with the server.
credentials
Credentials are a pair of a unique identifier and a matching
shared secret. OAuth defines three classes of credentials:
client, temporary, and token, used to identify and authenticate
the client making the request, the authorization request, and
the access grant, respectively.
token
A unique identifier issued by the server and used by the client
to associate authenticated requests with the resource owner
whose authorization is requested or has been obtained by the
client. Tokens have a matching shared-secret that is used by
the client to establish its ownership of the token, and its
authority to represent the resource owner.
The original community specification used a somewhat different
terminology that maps to this specifications as follows (original
community terms provided on left):
Consumer: client
Service Provider: server
User: resource owner
Consumer Key and Secret: client credentials
Request Token and Secret: temporary credentials
Access Token and Secret: token credentials
## Install
Via Composer
```shell
$ composer require league/oauth1-client
```
## Usage
### Bitbucket
```php
$server = new League\OAuth1\Client\Server\Bitbucket([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
]);
```
### Trello
```php
$server = new League\OAuth1\Client\Server\Trello([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => 'http://your-callback-uri/',
'name' => 'your-application-name', // optional, defaults to null
'expiration' => 'your-application-expiration', // optional ('never', '1day', '2days'), defaults to '1day'
'scope' => 'your-application-scope' // optional ('read', 'read,write'), defaults to 'read'
]);
```
### Tumblr
```php
$server = new League\OAuth1\Client\Server\Tumblr([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
]);
```
### Twitter
```php
$server = new League\OAuth1\Client\Server\Twitter([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
'scope' => 'your-application-scope' // optional ('read', 'write'), empty by default
]);
```
### Xing
```php
$server = new League\OAuth1\Client\Server\Xing([
'identifier' => 'your-consumer-key',
'secret' => 'your-consumer-secret',
'callback_uri' => "http://your-callback-uri/",
]);
```
### Showing a Login Button
To begin, it's advisable that you include a login button on your website. Most servers (Twitter, Tumblr etc) have resources available for making buttons that are familiar to users. Some servers actually require you use their buttons as part of their terms.
```html
<a href="authenticate.php">Login With Twitter</a>
```
### Retrieving Temporary Credentials
The first step to authenticating with OAuth 1 is to retrieve temporary credentials. These have been referred to as **request tokens** in earlier versions of OAuth 1.
To do this, we'll retrieve and store temporary credentials in the session, and redirect the user to the server:
```php
// Retrieve temporary credentials
$temporaryCredentials = $server->getTemporaryCredentials();
// Store credentials in the session, we'll need them later
$_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
session_write_close();
// Second part of OAuth 1.0 authentication is to redirect the
// resource owner to the login screen on the server.
$server->authorize($temporaryCredentials);
```
The user will be redirected to the familiar login screen on the server, where they will login to their account and authorise your app to access their data.
### Retrieving Token Credentials
Once the user has authenticated (or denied) your application, they will be redirected to the `callback_uri` which you specified when creating the server.
> Note, some servers (such as Twitter) require that the callback URI you specify when authenticating matches what you registered with their app. This is to stop a potential third party impersonating you. This is actually part of the protocol however some servers choose to ignore this.
>
> Because of this, we actually require you specify a callback URI for all servers, regardless of whether the server requires it or not. This is good practice.
You'll need to handle when the user is redirected back. This will involve retrieving token credentials, which you may then use to make calls to the server on behalf of the user. These have been referred to as **access tokens** in earlier versions of OAuth 1.
```php
if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
// Retrieve the temporary credentials we saved before
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
// We will now retrieve token credentials from the server
$tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
}
```
Now, you may choose to do what you need with the token credentials. You may store them in a database, in the session, or use them as one-off and then forget about them.
All credentials, (`client credentials`, `temporary credentials` and `token credentials`) all implement `League\OAuth1\Client\Credentials\CredentialsInterface` and have two sets of setters and getters exposed:
```php
var_dump($tokenCredentials->getIdentifier());
var_dump($tokenCredentials->getSecret());
```
In earlier versions of OAuth 1, the token credentials identifier and token credentials secret were referred to as **access token** and **access token secret**. Don't be scared by the new terminology here - they are the same. This package is using the exact terminology in the RFC 5849 OAuth 1 standard.
> Twitter will send back an error message in the `denied` query string parameter, allowing you to provide feedback. Some servers do not send back an error message, but rather do not provide the successful `oauth_token` and `oauth_verifier` parameters.
### Accessing User Information
Now you have token credentials stored somewhere, you may use them to make calls against the server, as an authenticated user.
While this package is not intended to be a wrapper for every server's API, it does include basic methods that you may use to retrieve limited information. An example of where this may be useful is if you are using social logins, you only need limited information to confirm who the user is.
The four exposed methods are:
```php
// User is an instance of League\OAuth1\Client\Server\User
$user = $server->getUserDetails($tokenCredentials);
// UID is a string / integer unique representation of the user
$uid = $server->getUserUid($tokenCredentials);
// Email is either a string or null (as some providers do not supply this data)
$email = $server->getUserEmail($tokenCredentials);
// Screen name is also known as a username (Twitter handle etc)
$screenName = $server->getUserScreenName($tokenCredentials);
```
> `League\OAuth1\Client\Server\User` exposes a number of default public properties and also stores any additional data in an extra array - `$user->extra`. You may also iterate over a user's properties as if it was an array, `foreach ($user as $key => $value)`.
## Examples
Examples may be found under the [resources/examples](https://github.com/thephpleague/oauth1-client/tree/master/resources/examples) directory, which take the usage instructions here and go into a bit more depth. They are working examples that would only you substitute in your client credentials to have working.
## Testing
``` bash
$ phpunit
```
## Contributing
Please see [CONTRIBUTING](https://github.com/thephpleague/oauth1-client/blob/master/CONTRIBUTING.md) for details.
## Credits
- [Ben Corlett](https://github.com/bencorlett)
- [Steven Maguire](https://github.com/stevenmaguire)
- [All Contributors](https://github.com/thephpleague/oauth1-client/contributors)
## License
The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth1-client/blob/master/LICENSE) for more information.

View File

@@ -0,0 +1,66 @@
{
"name": "league/oauth1-client",
"description": "OAuth 1.0 Client Library",
"license": "MIT",
"require": {
"php": ">=7.1||>=8.0",
"ext-json": "*",
"ext-openssl": "*",
"guzzlehttp/guzzle": "^6.0|^7.0",
"guzzlehttp/psr7": "^1.7|^2.0"
},
"require-dev": {
"ext-simplexml": "*",
"phpunit/phpunit": "^7.5||9.5",
"mockery/mockery": "^1.3.3",
"phpstan/phpstan": "^0.12.42",
"friendsofphp/php-cs-fixer": "^2.17"
},
"scripts": {
"analyze": "vendor/bin/phpstan analyse -l 6 src/",
"php-cs-fixer:lint": "PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix --verbose --dry-run",
"php-cs-fixer:format": "PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix",
"test:unit": "vendor/bin/phpunit --coverage-text --coverage-clover coverage.xml"
},
"suggest": {
"ext-simplexml": "For decoding XML-based responses."
},
"keywords": [
"oauth",
"oauth1",
"authorization",
"authentication",
"idp",
"identity",
"sso",
"single sign on",
"bitbucket",
"trello",
"tumblr",
"twitter"
],
"authors": [
{
"name": "Ben Corlett",
"email": "bencorlett@me.com",
"homepage": "http://www.webcomm.com.au",
"role": "Developer"
}
],
"autoload": {
"psr-4": {
"League\\OAuth1\\Client\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"League\\OAuth1\\Client\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0-dev",
"dev-develop": "2.0-dev"
}
}
}

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,22 @@
<?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.
*
* @param string $callbackUri
*
* @return void
*/
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,38 @@
<?php
namespace League\OAuth1\Client\Credentials;
interface CredentialsInterface
{
/**
* Get the credentials identifier.
*
* @return string
*/
public function getIdentifier();
/**
* Set the credentials identifier.
*
* @param string $identifier
*
* @return void
*/
public function setIdentifier($identifier);
/**
* Get the credentials secret.
*
* @return string
*/
public function getSecret();
/**
* Set the credentials secret.
*
* @param string $secret
*
* @return void
*/
public function setSecret($secret);
}

View File

@@ -0,0 +1,110 @@
<?php
namespace League\OAuth1\Client\Credentials;
use OpenSSLAsymmetricKey;
class RsaClientCredentials extends ClientCredentials
{
/**
* @var string
*/
protected $rsaPublicKeyFile;
/**
* @var string
*/
protected $rsaPrivateKeyFile;
/**
* @var resource|OpenSSLAsymmetricKey|null
*/
protected $rsaPublicKey;
/**
* @var resource|OpenSSLAsymmetricKey|null
*/
protected $rsaPrivateKey;
/**
* Sets the path to the RSA public key.
*
* @param string $filename
*
* @return self
*/
public function setRsaPublicKey($filename)
{
$this->rsaPublicKeyFile = $filename;
$this->rsaPublicKey = null;
return $this;
}
/**
* Sets the path to the RSA private key.
*
* @param string $filename
*
* @return self
*/
public function setRsaPrivateKey($filename)
{
$this->rsaPrivateKeyFile = $filename;
$this->rsaPrivateKey = null;
return $this;
}
/**
* Gets the RSA public key.
*
* @throws CredentialsException when the key could not be loaded.
*
* @return resource|OpenSSLAsymmetricKey
*/
public function getRsaPublicKey()
{
if ($this->rsaPublicKey) {
return $this->rsaPublicKey;
}
if ( ! file_exists($this->rsaPublicKeyFile)) {
throw new CredentialsException('Could not read the public key file.');
}
$this->rsaPublicKey = openssl_get_publickey(file_get_contents($this->rsaPublicKeyFile));
if ( ! $this->rsaPublicKey) {
throw new CredentialsException('Cannot access public key for signing');
}
return $this->rsaPublicKey;
}
/**
* Gets the RSA private key.
*
* @throws CredentialsException when the key could not be loaded.
*
* @return resource|OpenSSLAsymmetricKey
*/
public function getRsaPrivateKey()
{
if ($this->rsaPrivateKey) {
return $this->rsaPrivateKey;
}
if ( ! file_exists($this->rsaPrivateKeyFile)) {
throw new CredentialsException('Could not read the private key file.');
}
$this->rsaPrivateKey = openssl_pkey_get_private(file_get_contents($this->rsaPrivateKeyFile));
if ( ! $this->rsaPrivateKey) {
throw new CredentialsException('Cannot access private key for signing');
}
return $this->rsaPrivateKey;
}
}

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 = ['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 null;
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['user']['display_name'];
}
}

View File

@@ -0,0 +1,218 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
/**
* 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 = [
'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 null;
}
return $data['email'];
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return null;
}
/**
* @inheritDoc
*/
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier)
{
$this->verifier = $verifier;
return parent::getTokenCredentials($temporaryCredentials, $temporaryIdentifier, $verifier);
}
/**
* @inheritDoc
*/
protected function additionalProtocolParameters()
{
return [
'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
*
* @return void
*
* @throws \Exception
*/
private function parseConfigurationArray(array $configuration = [])
{
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,728 @@
<?php
namespace League\OAuth1\Client\Server;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\BadResponseException;
use League\OAuth1\Client\Credentials\ClientCredentials;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\CredentialsException;
use League\OAuth1\Client\Credentials\CredentialsInterface;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\HmacSha1Signature;
use League\OAuth1\Client\Signature\RsaSha1Signature;
use League\OAuth1\Client\Signature\SignatureInterface;
use SimpleXMLElement;
use Throwable;
abstract class Server
{
/**
* Client credentials.
*
* @var ClientCredentialsInterface
*/
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 array|SimpleXMLElement
*/
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;
if ( ! $signature && $clientCredentials instanceof RsaClientCredentials) {
$signature = new RsaSha1Signature($clientCredentials);
}
$this->signature = $signature ?: new HmacSha1Signature($clientCredentials);
}
/**
* Gets temporary credentials by performing a request to
* the server.
*
* @return TemporaryCredentials
*
* @throws CredentialsException
*/
public function getTemporaryCredentials()
{
$uri = $this->urlTemporaryCredentials();
$client = $this->createHttpClient();
$header = $this->temporaryCredentialsProtocolHeader($uri);
$authorizationHeader = ['Authorization' => $header];
$headers = $this->buildHttpClientHeaders($authorizationHeader);
try {
$response = $client->post($uri, [
'headers' => $headers,
]);
return $this->createTemporaryCredentials((string) $response->getBody());
} catch (BadResponseException $e) {
$this->handleTemporaryCredentialsBadResponse($e);
}
throw new CredentialsException('Failed to get temporary credentials');
}
/**
* Get the authorization URL by passing in the temporary credentials
* identifier or an object instance.
*
* @param TemporaryCredentials|string $temporaryIdentifier
* @param array $options
*
* @return string
*/
public function getAuthorizationUrl($temporaryIdentifier, array $options = [])
{
// 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_merge($options, ['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
*
* @return void
*/
public function authorize($temporaryIdentifier)
{
$url = $this->getAuthorizationUrl($temporaryIdentifier);
header('Location: ' . $url);
}
/**
* 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
*
* @throws CredentialsException
*/
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 = ['oauth_verifier' => $verifier];
$client = $this->createHttpClient();
$headers = $this->getHeaders($temporaryCredentials, 'POST', $uri, $bodyParameters);
try {
$response = $client->post($uri, [
'headers' => $headers,
'form_params' => $bodyParameters,
]);
return $this->createTokenCredentials((string) $response->getBody());
} catch (BadResponseException $e) {
$this->handleTokenCredentialsBadResponse($e);
}
throw new CredentialsException('Failed to get token credentials.');
}
/**
* 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 = [])
{
$header = $this->protocolHeader(strtoupper($method), $url, $credentials, $bodyParameters);
$authorizationHeader = ['Authorization' => $header];
$headers = $this->buildHttpClientHeaders($authorizationHeader);
return $headers;
}
/**
* Get Guzzle HTTP client default headers.
*
* @return array
*/
protected function getHttpClientDefaultHeaders()
{
$defaultHeaders = [];
if ( ! empty($this->userAgent)) {
$defaultHeaders['User-Agent'] = $this->userAgent;
}
return $defaultHeaders;
}
/**
* Build Guzzle HTTP client headers.
*
* @param array $headers
*
* @return array
*/
protected function buildHttpClientHeaders($headers = [])
{
$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 = ['identifier', 'secret'];
foreach ($keys as $key) {
if ( ! isset($clientCredentials[$key])) {
throw new \InvalidArgumentException("Missing client credentials key [$key] from options.");
}
}
if (isset($clientCredentials['rsa_private_key']) && isset($clientCredentials['rsa_public_key'])) {
$_clientCredentials = new RsaClientCredentials();
$_clientCredentials->setRsaPrivateKey($clientCredentials['rsa_private_key']);
$_clientCredentials->setRsaPublicKey($clientCredentials['rsa_public_key']);
} else {
$_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
*
* @return void
*
* @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
*
* @return void
*
* @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 [
'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 [];
}
/**
* 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(), [
'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 = [])
{
$parameters = array_merge(
$this->baseProtocolParameters(),
$this->additionalProtocolParameters(),
[
'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|null
*/
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|null
*/
abstract public function userScreenName($data, TokenCredentials $tokenCredentials);
}

View File

@@ -0,0 +1,254 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
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->extra = (array) $data;
return $user;
}
/**
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['id'];
}
/**
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return null;
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['username'];
}
/**
* Build authorization query parameters.
*
* @return string
*/
private function buildAuthorizationQueryParameters()
{
$params = [
'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
*
* @return void
*/
private function parseConfiguration(array $configuration = [])
{
$configToPropertyMap = [
'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,101 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
use LogicException;
use RuntimeException;
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'])) {
throw new LogicException('Not possible to get user info');
}
$data = $data['response']['user'];
$user = new User();
$user->nickname = $data['name'];
// Save all extra data
$used = ['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'])) {
throw new LogicException('Not possible to get user UUID');
}
$data = $data['response']['user'];
return $data['name'];
}
/**
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return null;
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
if ( ! isset($data['response']['user']) || ! is_array($data['response']['user'])) {
throw new LogicException('Not possible to get user screen name');
}
$data = $data['response']['user'];
return $data['name'];
}
}

View File

@@ -0,0 +1,183 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
class Twitter extends Server
{
/**
* Application scope.
*
* @var ?string
*/
protected $applicationScope = null;
/**
* @inheritDoc
*/
public function __construct($clientCredentials, ?SignatureInterface $signature = null)
{
parent::__construct($clientCredentials, $signature);
if (is_array($clientCredentials)) {
$this->parseConfiguration($clientCredentials);
}
}
/**
* Set the application scope.
*
* @param ?string $applicationScope
*
* @return Twitter
*/
public function setApplicationScope($applicationScope)
{
$this->applicationScope = $applicationScope;
return $this;
}
/**
* Get application scope.
*
* @return ?string
*/
public function getApplicationScope()
{
return $this->applicationScope;
}
/**
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
$url = 'https://api.twitter.com/oauth/request_token';
$queryParams = $this->temporaryCredentialsQueryParameters();
return empty($queryParams) ? $url : $url . '?' . $queryParams;
}
/**
* @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'];
if (isset($data['email'])) {
$user->email = $data['email'];
}
$used = ['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 null;
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['name'];
}
/**
* Query parameters for a Twitter OAuth request to get temporary credentials.
*
* @return string
*/
protected function temporaryCredentialsQueryParameters()
{
$queryParams = [];
if ($scope = $this->getApplicationScope()) {
$queryParams['x_auth_access_type'] = $scope;
}
return http_build_query($queryParams);
}
/**
* Parse configuration array to set attributes.
*
* @param array $configuration
*
* @return void
*/
private function parseConfiguration(array $configuration = [])
{
$configToPropertyMap = [
'scope' => 'applicationScope',
];
foreach ($configToPropertyMap as $config => $property) {
if (isset($configuration[$config])) {
$this->$property = $configuration[$config];
}
}
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace League\OAuth1\Client\Server;
use ArrayIterator;
class User implements \IteratorAggregate
{
/**
* The user's unique ID.
*
* @var mixed
*/
public $uid;
/**
* The user's nickname (screen name, username etc).
*
* @var mixed
*/
public $nickname;
/**
* The user's name.
*
* @var mixed
*/
public $name;
/**
* The user's first name.
*
* @var string
*/
public $firstName;
/**
* The user's last name.
*
* @var string
*/
public $lastName;
/**
* The user's email.
*
* @var string
*/
public $email;
/**
* The user's location.
*
* @var string|array
*/
public $location;
/**
* The user's description.
*
* @var string
*/
public $description;
/**
* The user's image URL.
*
* @var string
*/
public $imageUrl;
/**
* The users' URLs.
*
* @var string|array
*/
public $urls = [];
/**
* Any extra data.
*
* @var array
*/
public $extra = [];
/**
* Set a property on the user.
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function __set($key, $value)
{
if (isset($this->{$key})) {
$this->{$key} = $value;
}
}
/**
* Tells if a property is set.
*
* @param string $key
*
* @return bool
*/
public function __isset($key)
{
return isset($this->{$key});
}
/**
* Get a property from the user.
*
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
if (isset($this->{$key})) {
return $this->{$key};
}
}
/**
* @inheritDoc
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator(get_object_vars($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'], 2);
$user->firstName = $parts[0];
if (2 === count($parts)) {
$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
*
* @return void
*
* @throws InvalidArgumentException
*/
private function parseConfigurationArray(array $configuration = [])
{
if (isset($configuration['host'])) {
throw new InvalidArgumentException('Missing host');
}
$this->base = trim($configuration['host'], '/');
}
}

View File

@@ -0,0 +1,183 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
class X extends Server
{
/**
* Application scope.
*
* @var ?string
*/
protected $applicationScope = null;
/**
* @inheritDoc
*/
public function __construct($clientCredentials, ?SignatureInterface $signature = null)
{
parent::__construct($clientCredentials, $signature);
if (is_array($clientCredentials)) {
$this->parseConfiguration($clientCredentials);
}
}
/**
* Set the application scope.
*
* @param ?string $applicationScope
*
* @return Twitter
*/
public function setApplicationScope($applicationScope)
{
$this->applicationScope = $applicationScope;
return $this;
}
/**
* Get application scope.
*
* @return ?string
*/
public function getApplicationScope()
{
return $this->applicationScope;
}
/**
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
$url = 'https://api.x.com/oauth/request_token';
$queryParams = $this->temporaryCredentialsQueryParameters();
return empty($queryParams) ? $url : $url . '?' . $queryParams;
}
/**
* @inheritDoc
*/
public function urlAuthorization()
{
return 'https://api.x.com/oauth/authenticate';
}
/**
* @inheritDoc
*/
public function urlTokenCredentials()
{
return 'https://api.x.com/oauth/access_token';
}
/**
* @inheritDoc
*/
public function urlUserDetails()
{
return 'https://api.x.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'];
if (isset($data['email'])) {
$user->email = $data['email'];
}
$used = ['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 null;
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['name'];
}
/**
* Query parameters for a Twitter OAuth request to get temporary credentials.
*
* @return string
*/
protected function temporaryCredentialsQueryParameters()
{
$queryParams = [];
if ($scope = $this->getApplicationScope()) {
$queryParams['x_auth_access_type'] = $scope;
}
return http_build_query($queryParams);
}
/**
* Parse configuration array to set attributes.
*
* @param array $configuration
*
* @return void
*/
private function parseConfiguration(array $configuration = [])
{
$configToPropertyMap = [
'scope' => 'applicationScope',
];
foreach ($configToPropertyMap as $config => $property) {
if (isset($configuration[$config])) {
$this->$property = $configuration[$config];
}
}
}
}

View File

@@ -0,0 +1,95 @@
<?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,115 @@
<?php
namespace League\OAuth1\Client\Signature;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\UriInterface;
trait EncodesUrl
{
/**
* Create a Guzzle url for the given URI.
*
* @param string $uri
*
* @return UriInterface
*/
protected function createUrl($uri)
{
return Psr7\Utils::uriFor($uri);
}
/**
* Generate a base string for a RSA-SHA1 signature
* based on the given a url, method, and any parameters.
*
* @param UriInterface $url
* @param string $method
* @param array $parameters
*
* @return string
*/
protected function baseString(UriInterface $url, $method = 'POST', array $parameters = [])
{
$baseString = rawurlencode($method) . '&';
$schemeHostPath = Uri::fromParts([
'scheme' => $url->getScheme(),
'host' => $url->getHost(),
'port' => $url->getPort(),
'path' => $url->getPath(),
]);
$baseString .= rawurlencode($schemeHostPath) . '&';
parse_str($url->getQuery(), $query);
$data = array_merge($query, $parameters);
// normalize data key/values
$data = $this->normalizeArray($data);
ksort($data);
$baseString .= $this->queryStringFromData($data);
return $baseString;
}
/**
* Return a copy of the given array with all keys and values rawurlencoded.
*
* @param array $array Array to normalize
*
* @return array Normalized array
*/
protected function normalizeArray(array $array = [])
{
$normalizedArray = [];
foreach ($array as $key => $value) {
$key = rawurlencode(rawurldecode($key));
if (is_array($value)) {
$normalizedArray[$key] = $this->normalizeArray($value);
} else {
$normalizedArray[$key] = rawurlencode(rawurldecode($value));
}
}
return $normalizedArray;
}
/**
* Creates an array of rawurlencoded strings out of each array key/value pair
* Handles multi-dimensional arrays recursively.
*
* @param array $data Array of parameters to convert.
* @param array|null $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 = null, $prevKey = '')
{
if ($initial = (null === $queryParams)) {
$queryParams = [];
}
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;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace League\OAuth1\Client\Signature;
class HmacSha1Signature extends Signature implements SignatureInterface
{
use EncodesUrl;
/**
* @inheritDoc
*/
public function method()
{
return 'HMAC-SHA1';
}
/**
* @inheritDoc
*/
public function sign($uri, array $parameters = [], $method = 'POST')
{
$url = $this->createUrl($uri);
$baseString = $this->baseString($url, $method, $parameters);
return base64_encode($this->hash($baseString));
}
/**
* 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 = [], $method = 'POST')
{
return $this->key();
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace League\OAuth1\Client\Signature;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
class RsaSha1Signature extends Signature implements SignatureInterface
{
use EncodesUrl;
/**
* @inheritDoc
*/
public function method()
{
return 'RSA-SHA1';
}
/**
* @inheritDoc
*/
public function sign($uri, array $parameters = [], $method = 'POST')
{
$url = $this->createUrl($uri);
$baseString = $this->baseString($url, $method, $parameters);
/** @var RsaClientCredentials $clientCredentials */
$clientCredentials = $this->clientCredentials;
$privateKey = $clientCredentials->getRsaPrivateKey();
openssl_sign($baseString, $signature, $privateKey);
return base64_encode($signature);
}
}

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,46 @@
<?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
*
* @return void
*/
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 = [], $method = 'POST');
}