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,4 @@
/build
/vendor
/composer.lock
.DS_Store

View File

@@ -0,0 +1,35 @@
filter:
excluded_paths: [tests/*]
checks:
php:
code_rating: true
remove_extra_empty_lines: true
remove_php_closing_tag: true
remove_trailing_whitespace: true
fix_use_statements:
remove_unused: true
preserve_multiple: false
preserve_blanklines: true
order_alphabetically: true
fix_php_opening_tag: true
fix_linefeed: true
fix_line_ending: true
fix_identation_4spaces: true
fix_doc_comments: true
tools:
external_code_coverage:
timeout: 600
runs: 4
php_analyzer: true
php_code_coverage: false
php_code_sniffer:
config:
standard: PSR2
filter:
paths: ['src']
php_loc:
enabled: true
excluded_dirs: [vendor, tests]
php_cpd:
enabled: true
excluded_dirs: [vendor, tests]

22
vendor/league/oauth1-client/.travis.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev
- travis_retry phpenv rehash
script:
- ./vendor/bin/phpcs --standard=psr2 src/
- ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover
after_script:
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" ] && [ "$TRAVIS_PHP_VERSION" != "7.0" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" ] && [ "$TRAVIS_PHP_VERSION" != "7.0" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi

22
vendor/league/oauth1-client/CONDUCT.md vendored Normal file
View File

@@ -0,0 +1,22 @@
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses, without explicit permission
* Other unethical or unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community in a direct capacity. Personal views, beliefs and values of individuals do not necessarily reflect those of the organisation or affiliated individuals and organisations.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)

View File

@@ -0,0 +1,32 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/oauth1-client).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow semver. Randomly breaking public APIs is not an option.
- **Create topic branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
## Running Tests
``` bash
$ phpunit
```
**Happy coding**!

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.

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

@@ -0,0 +1,260 @@
# 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
- Trello
- Tumblr
- Twitter
- Xing
Adding support for other providers is trivial. The library requires PHP 5.3+ 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)
#### 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(array(
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
```
### Trello
```php
$server = new League\OAuth1\Client\Server\Trello(array(
'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(array(
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
```
### Twitter
```php
$server = new League\OAuth1\Client\Server\Twitter(array(
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
```
### Xing
```php
$server = new League\OAuth1\Client\Server\Xing(array(
'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,46 @@
{
"name": "league/oauth1-client",
"description": "OAuth 1.0 Client Library",
"license": "MIT",
"require": {
"php": ">=5.5.0",
"guzzlehttp/guzzle": "^6.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0",
"mockery/mockery": "^0.9",
"squizlabs/php_codesniffer": "^2.0"
},
"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\\": "src/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
}
}

28
vendor/league/oauth1-client/phpunit.xml vendored Normal file
View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true"
stopOnFailure="false"
bootstrap="./vendor/autoload.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true">
<logging>
<log type="coverage-html"
target="./build/coverage/html"
charset="UTF-8"
highlight="false"
lowUpperBound="35"
highLowerBound="70"/>
<log type="coverage-clover"
target="./build/coverage/log/coverage.xml"/>
</logging>
<testsuites>
<testsuite name="common">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src/</directory>
</whitelist>
</filter>
</phpunit>

View File

@@ -0,0 +1,87 @@
<?php
require_once __DIR__.'/../../vendor/autoload.php';
// Create server
$server = new League\OAuth1\Client\Server\Tumblr(array(
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
// Start session
session_start();
// Step 4
if (isset($_GET['user'])) {
// Check somebody hasn't manually entered this URL in,
// by checking that we have the token credentials in
// the session.
if ( ! isset($_SESSION['token_credentials'])) {
echo 'No token credentials.';
exit(1);
}
// Retrieve our token credentials. From here, it's play time!
$tokenCredentials = unserialize($_SESSION['token_credentials']);
// // Below is an example of retrieving the identifier & secret
// // (formally known as access token key & secret in earlier
// // OAuth 1.0 specs).
// $identifier = $tokenCredentials->getIdentifier();
// $secret = $tokenCredentials->getSecret();
// Some OAuth clients try to act as an API wrapper for
// the server and it's API. We don't. This is what you
// get - the ability to access basic information. If
// you want to get fancy, you should be grabbing a
// package for interacting with the APIs, by using
// the identifier & secret that this package was
// designed to retrieve for you. But, for fun,
// here's basic user information.
$user = $server->getUserDetails($tokenCredentials);
var_dump($user);
// Step 3
} elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
// Retrieve the temporary credentials from step 2
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
// Third and final part to OAuth 1.0 authentication is to retrieve token
// credentials (formally known as access tokens in earlier OAuth 1.0
// specs).
$tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
// Now, we'll store the token credentials and discard the temporary
// ones - they're irrelevant at this stage.
unset($_SESSION['temporary_credentials']);
$_SESSION['token_credentials'] = serialize($tokenCredentials);
session_write_close();
// Redirect to the user page
header("Location: http://{$_SERVER['HTTP_HOST']}/?user=user");
exit;
// Step 2
} elseif (isset($_GET['go'])) {
// First part of OAuth 1.0 authentication is retrieving temporary credentials.
// These identify you as a client to the server.
$temporaryCredentials = $server->getTemporaryCredentials();
// Store the credentials in the session.
$_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);
// Step 1
} else {
// Display link to start process
echo '<a href="?go=go">Login</a>';
}

View File

@@ -0,0 +1,91 @@
<?php
require_once __DIR__.'/../../vendor/autoload.php';
// Create server
$server = new League\OAuth1\Client\Server\Twitter(array(
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
// Start session
session_start();
// Step 4
if (isset($_GET['user'])) {
// Check somebody hasn't manually entered this URL in,
// by checking that we have the token credentials in
// the session.
if ( ! isset($_SESSION['token_credentials'])) {
echo 'No token credentials.';
exit(1);
}
// Retrieve our token credentials. From here, it's play time!
$tokenCredentials = unserialize($_SESSION['token_credentials']);
// // Below is an example of retrieving the identifier & secret
// // (formally known as access token key & secret in earlier
// // OAuth 1.0 specs).
// $identifier = $tokenCredentials->getIdentifier();
// $secret = $tokenCredentials->getSecret();
// Some OAuth clients try to act as an API wrapper for
// the server and it's API. We don't. This is what you
// get - the ability to access basic information. If
// you want to get fancy, you should be grabbing a
// package for interacting with the APIs, by using
// the identifier & secret that this package was
// designed to retrieve for you. But, for fun,
// here's basic user information.
$user = $server->getUserDetails($tokenCredentials);
var_dump($user);
// Step 3
} elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
// Retrieve the temporary credentials from step 2
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
// Third and final part to OAuth 1.0 authentication is to retrieve token
// credentials (formally known as access tokens in earlier OAuth 1.0
// specs).
$tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
// Now, we'll store the token credentials and discard the temporary
// ones - they're irrelevant at this stage.
unset($_SESSION['temporary_credentials']);
$_SESSION['token_credentials'] = serialize($tokenCredentials);
session_write_close();
// Redirect to the user page
header("Location: http://{$_SERVER['HTTP_HOST']}/?user=user");
exit;
// Step 2.5 - denied request to authorize client
} elseif (isset($_GET['denied'])) {
echo 'Hey! You denied the client access to your Twitter account! If you did this by mistake, you should <a href="?go=go">try again</a>.';
// Step 2
} elseif (isset($_GET['go'])) {
// First part of OAuth 1.0 authentication is retrieving temporary credentials.
// These identify you as a client to the server.
$temporaryCredentials = $server->getTemporaryCredentials();
// Store the credentials in the session.
$_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);
// Step 1
} else {
// Display link to start process
echo '<a href="?go=go">Login</a>';
}

View File

@@ -0,0 +1,91 @@
<?php
require_once __DIR__.'/../../vendor/autoload.php';
// Create server
$server = new League\OAuth1\Client\Server\Xing(array(
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
// Start session
session_start();
// Step 4
if (isset($_GET['user'])) {
// Check somebody hasn't manually entered this URL in,
// by checking that we have the token credentials in
// the session.
if ( ! isset($_SESSION['token_credentials'])) {
echo 'No token credentials.';
exit(1);
}
// Retrieve our token credentials. From here, it's play time!
$tokenCredentials = unserialize($_SESSION['token_credentials']);
// // Below is an example of retrieving the identifier & secret
// // (formally known as access token key & secret in earlier
// // OAuth 1.0 specs).
// $identifier = $tokenCredentials->getIdentifier();
// $secret = $tokenCredentials->getSecret();
// Some OAuth clients try to act as an API wrapper for
// the server and it's API. We don't. This is what you
// get - the ability to access basic information. If
// you want to get fancy, you should be grabbing a
// package for interacting with the APIs, by using
// the identifier & secret that this package was
// designed to retrieve for you. But, for fun,
// here's basic user information.
$user = $server->getUserDetails($tokenCredentials);
var_dump($user);
// Step 3
} elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
// Retrieve the temporary credentials from step 2
$temporaryCredentials = unserialize($_SESSION['temporary_credentials']);
// Third and final part to OAuth 1.0 authentication is to retrieve token
// credentials (formally known as access tokens in earlier OAuth 1.0
// specs).
$tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
// Now, we'll store the token credentials and discard the temporary
// ones - they're irrelevant at this stage.
unset($_SESSION['temporary_credentials']);
$_SESSION['token_credentials'] = serialize($tokenCredentials);
session_write_close();
// Redirect to the user page
header("Location: http://{$_SERVER['HTTP_HOST']}/?user=user");
exit;
// Step 2.5 - denied request to authorize client
} elseif (isset($_GET['denied'])) {
echo 'Hey! You denied the client access to your Xing account! If you did this by mistake, you should <a href="?go=go">try again</a>.';
// Step 2
} elseif (isset($_GET['go'])) {
// First part of OAuth 1.0 authentication is retrieving temporary credentials.
// These identify you as a client to the server.
$temporaryCredentials = $server->getTemporaryCredentials();
// Store the credentials in the session.
$_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);
// Step 1
} else {
// Display link to start process
echo '<a href="?go=go">Login</a>';
}

2131
vendor/league/oauth1-client/rfc5849.txt vendored Normal file

File diff suppressed because it is too large Load Diff

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');
}

View File

@@ -0,0 +1,47 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
use League\OAuth1\Client\Credentials\ClientCredentials;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class ClientCredentialsTest extends PHPUnit_Framework_TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
{
m::close();
}
public function testManipulating()
{
$credentials = new ClientCredentials;
$this->assertNull($credentials->getIdentifier());
$credentials->setIdentifier('foo');
$this->assertEquals('foo', $credentials->getIdentifier());
$this->assertNull($credentials->getSecret());
$credentials->setSecret('foo');
$this->assertEquals('foo', $credentials->getSecret());
}
}

View File

@@ -0,0 +1,164 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
use League\OAuth1\Client\Signature\HmacSha1Signature;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
{
m::close();
}
public function testSigningRequest()
{
$signature = new HmacSha1Signature($this->getMockClientCredentials());
$uri = 'http://www.example.com/?qux=corge';
$parameters = array('foo' => 'bar', 'baz' => null);
$this->assertEquals('A3Y7C1SUHXR1EBYIUlT3d6QT1cQ=', $signature->sign($uri, $parameters));
}
public function testQueryStringFromArray()
{
$array = array('a' => 'b');
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
'a%3Db',
$res
);
}
public function testQueryStringFromIndexedArray()
{
$array = array('a', 'b');
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
'0%3Da%261%3Db',
$res
);
}
public function testQueryStringFromMultiDimensionalArray()
{
$array = array(
'a' => array(
'b' => array(
'c' => 'd',
),
'e' => array(
'f' => 'g',
),
),
'h' => 'i',
'empty' => '',
'null' => null,
'false' => false,
);
// Convert to query string.
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
'a%5Bb%5D%5Bc%5D%3Dd%26a%5Be%5D%5Bf%5D%3Dg%26h%3Di%26empty%3D%26null%3D%26false%3D',
$res
);
// Reverse engineer the string.
$res = urldecode($res);
$this->assertSame(
'a[b][c]=d&a[e][f]=g&h=i&empty=&null=&false=',
$res
);
// Finally, parse the string back to an array.
parse_str($res, $original_array);
// And ensure it matches the orignal array (approximately).
$this->assertSame(
array(
'a' => array(
'b' => array(
'c' => 'd',
),
'e' => array(
'f' => 'g',
),
),
'h' => 'i',
'empty' => '',
'null' => '', // null value gets lost in string translation
'false' => '', // false value gets lost in string translation
),
$original_array
);
}
public function testSigningRequestWithMultiDimensionalParams()
{
$signature = new HmacSha1Signature($this->getMockClientCredentials());
$uri = 'http://www.example.com/';
$parameters = array(
'a' => array(
'b' => array(
'c' => 'd',
),
'e' => array(
'f' => 'g',
),
),
'h' => 'i',
'empty' => '',
'null' => null,
'false' => false,
);
$this->assertEquals('ZUxiJKugeEplaZm9e4hshN0I70U=', $signature->sign($uri, $parameters));
}
protected function invokeQueryStringFromData(array $args)
{
$signature = new HmacSha1Signature(m::mock('League\OAuth1\Client\Credentials\ClientCredentialsInterface'));
$refl = new \ReflectionObject($signature);
$method = $refl->getMethod('queryStringFromData');
$method->setAccessible(true);
return $method->invokeArgs($signature, array($args));
}
protected function getMockClientCredentials()
{
$clientCredentials = m::mock('League\OAuth1\Client\Credentials\ClientCredentialsInterface');
$clientCredentials->shouldReceive('getSecret')->andReturn('clientsecret');
return $clientCredentials;
}
}

View File

@@ -0,0 +1,60 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
use League\OAuth1\Client\Signature\PlainTextSignature;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class PlainTextSignatureTest extends PHPUnit_Framework_TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
{
m::close();
}
public function testSigningRequest()
{
$signature = new PlainTextSignature($this->getMockClientCredentials());
$this->assertEquals('clientsecret&', $signature->sign($uri = 'http://www.example.com/'));
$signature->setCredentials($this->getMockCredentials());
$this->assertEquals('clientsecret&tokensecret', $signature->sign($uri));
$this->assertEquals('PLAINTEXT', $signature->method());
}
protected function getMockClientCredentials()
{
$clientCredentials = m::mock('League\OAuth1\Client\Credentials\ClientCredentialsInterface');
$clientCredentials->shouldReceive('getSecret')->andReturn('clientsecret');
return $clientCredentials;
}
protected function getMockCredentials()
{
$credentials = m::mock('League\OAuth1\Client\Credentials\CredentialsInterface');
$credentials->shouldReceive('getSecret')->andReturn('tokensecret');
return $credentials;
}
}

View File

@@ -0,0 +1,285 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
use League\OAuth1\Client\Credentials\ClientCredentials;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class ServerTest extends PHPUnit_Framework_TestCase
{
/**
* Setup resources and dependencies.
*
* @return void
*/
public static function setUpBeforeClass()
{
require_once __DIR__.'/stubs/ServerStub.php';
}
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
{
m::close();
}
public function testCreatingWithArray()
{
$server = new ServerStub($this->getMockClientCredentials());
$credentials = $server->getClientCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\ClientCredentialsInterface', $credentials);
$this->assertEquals('myidentifier', $credentials->getIdentifier());
$this->assertEquals('mysecret', $credentials->getSecret());
$this->assertEquals('http://app.dev/', $credentials->getCallbackUri());
}
public function testCreatingWithObject()
{
$credentials = new ClientCredentials;
$credentials->setIdentifier('myidentifier');
$credentials->setSecret('mysecret');
$credentials->setCallbackUri('http://app.dev/');
$server = new ServerStub($credentials);
$this->assertEquals($credentials, $server->getClientCredentials());
}
/**
* @expectedException InvalidArgumentException
**/
public function testCreatingWithInvalidInput()
{
$server = new ServerStub(uniqid());
}
public function testGettingTemporaryCredentials()
{
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', array($this->getMockClientCredentials()));
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('http://www.example.com/temporary', m::on(function($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'.preg_quote('http%3A%2F%2Fapp.dev%2F', '/').'", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$credentials = $server->getTemporaryCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TemporaryCredentials', $credentials);
$this->assertEquals('temporarycredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('temporarycredentialssecret', $credentials->getSecret());
}
public function testGettingAuthorizationUrl()
{
$server = new ServerStub($this->getMockClientCredentials());
$expected = 'http://www.example.com/authorize?oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
/**
* @expectedException InvalidArgumentException
*/
public function testGettingTokenCredentialsFailsWithManInTheMiddle()
{
$server = new ServerStub($this->getMockClientCredentials());
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$server->getTokenCredentials($credentials, 'bar', 'verifier');
}
public function testGettingTokenCredentials()
{
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('temporarycredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('http://www.example.com/token', m::on(function($options) use ($me) {
$headers = $options['headers'];
$body = $options['form_params'];
$me->assertTrue(isset($headers['Authorization']));
$me->assertFalse(isset($headers['User-Agent']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TokenCredentials', $credentials);
$this->assertEquals('tokencredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('tokencredentialssecret', $credentials->getSecret());
}
public function testGettingTokenCredentialsWithUserAgent()
{
$userAgent = 'FooBar';
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('temporarycredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('http://www.example.com/token', m::on(function($options) use ($me, $userAgent) {
$headers = $options['headers'];
$body = $options['form_params'];
$me->assertTrue(isset($headers['Authorization']));
$me->assertTrue(isset($headers['User-Agent']));
$me->assertEquals($userAgent, $headers['User-Agent']);
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->setUserAgent($userAgent)->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TokenCredentials', $credentials);
$this->assertEquals('tokencredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('tokencredentialssecret', $credentials->getSecret());
}
public function testGettingUserDetails()
{
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient,protocolHeader]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('tokencredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('tokencredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('get')->with('http://www.example.com/user', m::on(function($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="tokencredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->once()->andReturn(json_encode(array('foo' => 'bar', 'id' => 123, 'contact_email' => 'baz@qux.com', 'username' => 'fred')));
$user = $server->getUserDetails($temporaryCredentials);
$this->assertInstanceOf('League\OAuth1\Client\Server\User', $user);
$this->assertEquals('bar', $user->firstName);
$this->assertEquals(123, $server->getUserUid($temporaryCredentials));
$this->assertEquals('baz@qux.com', $server->getUserEmail($temporaryCredentials));
$this->assertEquals('fred', $server->getUserScreenName($temporaryCredentials));
}
public function testGettingHeaders()
{
$server = new ServerStub($this->getMockClientCredentials());
$tokenCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$tokenCredentials->shouldReceive('getIdentifier')->andReturn('mock_identifier');
$tokenCredentials->shouldReceive('getSecret')->andReturn('mock_secret');
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="mock_identifier", oauth_signature=".*?"/';
// With a GET request
$headers = $server->getHeaders($tokenCredentials, 'GET', 'http://example.com/');
$this->assertTrue(isset($headers['Authorization']));
$matches = preg_match($pattern, $headers['Authorization']);
$this->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
// With a POST request
$headers = $server->getHeaders($tokenCredentials, 'POST', 'http://example.com/', array('body' => 'params'));
$this->assertTrue(isset($headers['Authorization']));
$matches = preg_match($pattern, $headers['Authorization']);
$this->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
}
protected function getMockClientCredentials()
{
return array(
'identifier' => 'myidentifier',
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
);
}
}

View File

@@ -0,0 +1,349 @@
<?php namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Server\Trello;
use League\OAuth1\Client\Credentials\ClientCredentials;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class TrelloTest extends PHPUnit_Framework_TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
{
m::close();
}
public function testCreatingWithArray()
{
$server = new Trello($this->getMockClientCredentials());
$credentials = $server->getClientCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\ClientCredentialsInterface', $credentials);
$this->assertEquals($this->getApplicationKey(), $credentials->getIdentifier());
$this->assertEquals('mysecret', $credentials->getSecret());
$this->assertEquals('http://app.dev/', $credentials->getCallbackUri());
}
public function testCreatingWithObject()
{
$credentials = new ClientCredentials;
$credentials->setIdentifier('myidentifier');
$credentials->setSecret('mysecret');
$credentials->setCallbackUri('http://app.dev/');
$server = new Trello($credentials);
$this->assertEquals($credentials, $server->getClientCredentials());
}
public function testGettingTemporaryCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient]', array($this->getMockClientCredentials()));
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('https://trello.com/1/OAuthGetRequestToken', m::on(function($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'.preg_quote('http%3A%2F%2Fapp.dev%2F', '/').'", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$credentials = $server->getTemporaryCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TemporaryCredentials', $credentials);
$this->assertEquals('temporarycredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('temporarycredentialssecret', $credentials->getSecret());
}
public function testGettingDefaultAuthorizationUrl()
{
$server = new Trello($this->getMockClientCredentials());
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
public function testGettingAuthorizationUrlWithExpirationAfterConstructingWithExpiration()
{
$credentials = $this->getMockClientCredentials();
$expiration = $this->getApplicationExpiration(2);
$credentials['expiration'] = $expiration;
$server = new Trello($credentials);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration='.urlencode($expiration).'&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
public function testGettingAuthorizationUrlWithExpirationAfterSettingExpiration()
{
$expiration = $this->getApplicationExpiration(2);
$server = new Trello($this->getMockClientCredentials());
$server->setApplicationExpiration($expiration);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration='.urlencode($expiration).'&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
public function testGettingAuthorizationUrlWithNameAfterConstructingWithName()
{
$credentials = $this->getMockClientCredentials();
$name = $this->getApplicationName();
$credentials['name'] = $name;
$server = new Trello($credentials);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&name='.urlencode($name).'&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
public function testGettingAuthorizationUrlWithNameAfterSettingName()
{
$name = $this->getApplicationName();
$server = new Trello($this->getMockClientCredentials());
$server->setApplicationName($name);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&name='.urlencode($name).'&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
public function testGettingAuthorizationUrlWithScopeAfterConstructingWithScope()
{
$credentials = $this->getMockClientCredentials();
$scope = $this->getApplicationScope(false);
$credentials['scope'] = $scope;
$server = new Trello($credentials);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope='.urlencode($scope).'&expiration=1day&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
public function testGettingAuthorizationUrlWithScopeAfterSettingScope()
{
$scope = $this->getApplicationScope(false);
$server = new Trello($this->getMockClientCredentials());
$server->setApplicationScope($scope);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope='.urlencode($scope).'&expiration=1day&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
/**
* @expectedException InvalidArgumentException
*/
public function testGettingTokenCredentialsFailsWithManInTheMiddle()
{
$server = new Trello($this->getMockClientCredentials());
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$server->getTokenCredentials($credentials, 'bar', 'verifier');
}
public function testGettingTokenCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('temporarycredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('https://trello.com/1/OAuthGetAccessToken', m::on(function($options) use ($me) {
$headers = $options['headers'];
$body = $options['form_params'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TokenCredentials', $credentials);
$this->assertEquals('tokencredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('tokencredentialssecret', $credentials->getSecret());
}
public function testGettingUserDetails()
{
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient,protocolHeader]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('tokencredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('tokencredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('get')->with('https://trello.com/1/members/me?key='.$this->getApplicationKey().'&token='.$this->getAccessToken(), m::on(function($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="tokencredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->once()->andReturn($this->getUserPayload());
$user = $server
->setAccessToken($this->getAccessToken())
->getUserDetails($temporaryCredentials);
$this->assertInstanceOf('League\OAuth1\Client\Server\User', $user);
$this->assertEquals('Matilda Wormwood', $user->name);
$this->assertEquals('545df696e29c0dddaed31967', $server->getUserUid($temporaryCredentials));
$this->assertEquals(null, $server->getUserEmail($temporaryCredentials));
$this->assertEquals('matildawormwood12', $server->getUserScreenName($temporaryCredentials));
}
protected function getMockClientCredentials()
{
return array(
'identifier' => $this->getApplicationKey(),
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
);
}
protected function getAccessToken()
{
return 'lmnopqrstuvwxyz';
}
protected function getApplicationKey()
{
return 'abcdefghijk';
}
protected function getApplicationExpiration($days = 0)
{
return is_numeric($days) && $days > 0 ? $days.'day'.($days == 1 ? '' : 's') : 'never';
}
protected function getApplicationName()
{
return 'fizz buzz';
}
protected function getApplicationScope($readonly = true)
{
return $readonly ? 'read' : 'read,write';
}
private function getUserPayload()
{
return '{
"id": "545df696e29c0dddaed31967",
"avatarHash": null,
"bio": "I have magical powers",
"bioData": null,
"confirmed": true,
"fullName": "Matilda Wormwood",
"idPremOrgsAdmin": [],
"initials": "MW",
"memberType": "normal",
"products": [],
"status": "idle",
"url": "https://trello.com/matildawormwood12",
"username": "matildawormwood12",
"avatarSource": "none",
"email": null,
"gravatarHash": "39aaaada0224f26f0bb8f1965326dcb7",
"idBoards": [
"545df696e29c0dddaed31968",
"545e01d6c7b2dd962b5b46cb"
],
"idOrganizations": [
"54adfd79f9aea14f84009a85",
"54adfde13b0e706947bc4789"
],
"loginTypes": null,
"oneTimeMessagesDismissed": [],
"prefs": {
"sendSummaries": true,
"minutesBetweenSummaries": 1,
"minutesBeforeDeadlineToNotify": 1440,
"colorBlind": false,
"timezoneInfo": {
"timezoneNext": "CDT",
"dateNext": "2015-03-08T08:00:00.000Z",
"offsetNext": 300,
"timezoneCurrent": "CST",
"offsetCurrent": 360
}
},
"trophies": [],
"uploadedAvatarHash": null,
"premiumFeatures": [],
"idBoardsPinned": null
}';
}
}

View File

@@ -0,0 +1,255 @@
<?php namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Server\Xing;
use League\OAuth1\Client\Credentials\ClientCredentials;
use Mockery as m;
use PHPUnit_Framework_TestCase;
class XingTest extends PHPUnit_Framework_TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
{
m::close();
}
public function testCreatingWithArray()
{
$server = new Xing($this->getMockClientCredentials());
$credentials = $server->getClientCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\ClientCredentialsInterface', $credentials);
$this->assertEquals($this->getApplicationKey(), $credentials->getIdentifier());
$this->assertEquals('mysecret', $credentials->getSecret());
$this->assertEquals('http://app.dev/', $credentials->getCallbackUri());
}
public function testCreatingWithObject()
{
$credentials = new ClientCredentials;
$credentials->setIdentifier('myidentifier');
$credentials->setSecret('mysecret');
$credentials->setCallbackUri('http://app.dev/');
$server = new Xing($credentials);
$this->assertEquals($credentials, $server->getClientCredentials());
}
public function testGettingTemporaryCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient]', array($this->getMockClientCredentials()));
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('https://api.xing.com/v1/request_token', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'.preg_quote('http%3A%2F%2Fapp.dev%2F', '/').'", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$credentials = $server->getTemporaryCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TemporaryCredentials', $credentials);
$this->assertEquals('temporarycredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('temporarycredentialssecret', $credentials->getSecret());
}
public function testGettingDefaultAuthorizationUrl()
{
$server = new Xing($this->getMockClientCredentials());
$expected = 'https://api.xing.com/v1/authorize?oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
/**
* @expectedException InvalidArgumentException
*/
public function testGettingTokenCredentialsFailsWithManInTheMiddle()
{
$server = new Xing($this->getMockClientCredentials());
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$server->getTokenCredentials($credentials, 'bar', 'verifier');
}
public function testGettingTokenCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('temporarycredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('https://api.xing.com/v1/access_token', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$body = $options['form_params'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TokenCredentials', $credentials);
$this->assertEquals('tokencredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('tokencredentialssecret', $credentials->getSecret());
}
public function testGettingUserDetails()
{
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient,protocolHeader]', array($this->getMockClientCredentials()));
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('tokencredentialsidentifier');
$temporaryCredentials->shouldReceive('getSecret')->andReturn('tokencredentialssecret');
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('get')->with('https://api.xing.com/v1/users/me', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="tokencredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->once()->andReturn($this->getUserPayload());
$user = $server->getUserDetails($temporaryCredentials);
$this->assertInstanceOf('League\OAuth1\Client\Server\User', $user);
$this->assertEquals('Roman Gelembjuk', $user->name);
$this->assertEquals('17144430_0f9409', $server->getUserUid($temporaryCredentials));
$this->assertEquals('XXXXXXXXXX@gmail.com', $server->getUserEmail($temporaryCredentials));
$this->assertEquals('Roman Gelembjuk', $server->getUserScreenName($temporaryCredentials));
}
protected function getMockClientCredentials()
{
return array(
'identifier' => $this->getApplicationKey(),
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
);
}
protected function getApplicationKey()
{
return 'abcdefghijk';
}
protected function getApplicationExpiration($days = 0)
{
return is_numeric($days) && $days > 0 ? $days.'day'.($days == 1 ? '' : 's') : 'never';
}
protected function getApplicationName()
{
return 'fizz buzz';
}
private function getUserPayload()
{
return '{
"users":[
{
"id":"17144430_0f9409",
"active_email":"XXXXXXXXXX@gmail.com",
"time_zone":
{
"utc_offset":3.0,
"name":"Europe/Kiev"
},
"display_name":"Roman Gelembjuk",
"first_name":"Roman",
"last_name":"Gelembjuk",
"gender":"m",
"page_name":"Roman_Gelembjuk",
"birth_date":
{"year":null,"month":null,"day":null},
"wants":null,
"haves":null,
"interests":null,
"web_profiles":{},
"badges":[],
"photo_urls":
{
"large":"https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.140x185.jpg",
"maxi_thumb":"https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.70x93.jpg",
"medium_thumb":"https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.57x75.jpg"
},
"permalink":"https://www.xing.com/profile/Roman_Gelembjuk",
"languages":{"en":null},
"employment_status":"EMPLOYEE",
"organisation_member":null,
"instant_messaging_accounts":{},
"educational_background":
{"degree":null,"primary_school":null,"schools":[],"qualifications":[]},
"private_address":{
"street":null,
"zip_code":null,
"city":null,
"province":null,
"country":null,
"email":"XXXXXXXX@gmail.com",
"fax":null,
"phone":null,
"mobile_phone":null}
,"business_address":
{
"street":null,
"zip_code":null,
"city":"Ivano-Frankivsk",
"province":null,
"country":"UA",
"email":null,
"fax":null,"phone":null,"mobile_phone":null
},
"premium_services":[]
}]}';
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Server\Server;
use League\OAuth1\Client\Server\User;
class ServerStub extends Server
{
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return 'http://www.example.com/temporary';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return 'http://www.example.com/authorize';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return 'http://www.example.com/token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return 'http://www.example.com/user';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User;
$user->firstName = $data['foo'];
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return isset($data['id']) ? $data['id'] : null;
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return isset($data['contact_email']) ? $data['contact_email'] : null;
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return isset($data['username']) ? $data['username'] : null;
}
}