From 990bdfb59b4cd2086e0524b429dc12b5142d66ad Mon Sep 17 00:00:00 2001 From: Joan Touzet Date: Sun, 15 Oct 2017 03:14:10 -0400 Subject: [PATCH] Initial commit --- .gitignore | 9 + .scrutinizer.yml | 36 +++ .travis.yml | 41 ++++ CONTRIBUTING.md | 40 ++++ LICENSE | 22 ++ README.md | 205 ++++++++++++++++++ composer.json | 48 ++++ coverage.clover | 72 ++++++ phpunit.xml | 38 ++++ src/Provider/Discord.php | 125 +++++++++++ src/Provider/DiscordResourceOwner.php | 109 ++++++++++ .../DiscordIdentityProviderException.php | 49 +++++ test/src/Provider/DiscordTest.php | 148 +++++++++++++ 13 files changed, 942 insertions(+) create mode 100644 .gitignore create mode 100644 .scrutinizer.yml create mode 100644 .travis.yml create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 composer.json create mode 100644 coverage.clover create mode 100644 phpunit.xml create mode 100644 src/Provider/Discord.php create mode 100644 src/Provider/DiscordResourceOwner.php create mode 100644 src/Provider/Exception/DiscordIdentityProviderException.php create mode 100644 test/src/Provider/DiscordTest.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d88aa24 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*.swp +*~ +.coveralls.yml +build/ +composer.lock +composer.phar +coveralls.phar +test/log +vendor/ diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 0000000..ffefc4c --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,36 @@ +filter: + excluded_paths: [test/*] +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: 3 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..2b45709 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,41 @@ +language: php + +sudo: false + +matrix: + include: + - php: 5.6 + env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' + - php: 7.0 + - php: 7.1 + - php: nightly + - php: hhvm + sudo: required + dist: trusty + group: edge + - php: hhvm-nightly + sudo: required + dist: trusty + group: edge + fast_finish: true + allow_failures: + - php: nightly + - php: hhvm-nightly + + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source --dev + - travis_retry phpenv rehash + +script: + - ./vendor/bin/parallel-lint src test + - ./vendor/bin/phpcs src --standard=psr2 -sp + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_success: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover + - mkdir -p build/logs + - wget https://github.com/satooshi/php-coveralls/releases/download/v1.0.2/coveralls.phar + - travis_retry php coveralls.phar -x coverage.clover diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a3c2574 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/wohali/oauth2-discord-new). + + +## 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. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Testing + +The following tests must pass for a build to be considered successful. If contributing, please ensure these pass before submitting a pull request. Travis CI will be used to enforce a pass before a merge can occur! + +``` bash +$ ./vendor/bin/parallel-lint src test +$ ./vendor/bin/phpunit --coverage-text +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9c289f2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2017 Joan Touzet + +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. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..a86cd6b --- /dev/null +++ b/README.md @@ -0,0 +1,205 @@ +# Discord Provider for OAuth 2.0 Client +[![Source Code](http://img.shields.io/badge/source-wohali/oauth2--discord--new-blue.svg?style=flat-square)](https://github.com/wohali/oauth2-discord-new) +[![Latest Version](https://img.shields.io/github/release/wohali/oauth2-discord-new.svg?style=flat-square)](https://github.com/wohali/oauth2-discord-new/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/wohali/oauth2-discord-new/master.svg?style=flat-square)](https://travis-ci.org/wohali/oauth2-discord-new) +[![Scrutinizer](https://img.shields.io/scrutinizer/g/wohali/oauth2-discord-new/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/wohali/oauth2-discord-new) +[![Coverage Status](https://img.shields.io/coveralls/wohali/oauth2-discord-new/master.svg?style=flat-square)](https://coveralls.io/r/wohali/oauth2-discord-new?branch=master) +[![Total Downloads](https://img.shields.io/packagist/dt/wohali/oauth2-discord-new.svg?style=flat-square)](https://packagist.org/packages/wohali/oauth2-discord-new) + +This package provides Discord OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client), v2.0 and up. + +## Requirements + +The following versions of PHP are supported. + +* PHP 5.6 +* PHP 7.0 +* PHP 7.1 +* HHVM + +## Installation + +To install, use composer: + +```bash +$ composer require wohali/oauth2-discord-new +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\Wohali\OAuth2\Client\Provider\Discord` as the provider. + +### Sample Authorization Code Flow + +This self-contained example: + +1. Gets an authorization code +1. Gets an access token using the provided authorization code +1. Looks up the user's provile with the provided access token + +You can try this script by [registering a Discord App](https://discordapp.com/developers/applications/me/create) with a redirect URI to your server's copy of this sample script. Then, place the Discord app's client id and secret, along with that same URI, into the settings at the top of the script. + +```php +
'); + +$provider = new \Wohali\OAuth2\Client\Provider\Discord([ + 'clientId' => '{discord-client-id}', + 'clientSecret' => '{discord-client-secret}', + 'redirecturi' => '{your-server-uri-to-this-script-here}' +]); + +if (!isset($_GET['code'])) { + + // Step 1. Get authorization code + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Step 2. Get an access token using the provided authorization code + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Show some token details + echo '

Token details:

'; + echo 'Token: ' . $token->getToken() . "
"; + echo 'Refresh token: ' . $token->getRefreshToken() . "
"; + echo 'Expires: ' . $token->getExpires() . " - "; + echo ($token->hasExpired() ? 'expired' : 'not expired') . "
"; + + // Step 3. (Optional) Look up the user's profile with the provided token + try { + + $user = $provider->getResourceOwner($token); + + echo '

Resource owner details:

'; + printf('Hello %s#%s!

', $user->getUsername(), $user->getDiscriminator()); + var_export($user->toArray()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + + } +} +``` + +### Managing Scopes + +When creating your Discord authorization URL in Step 1, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['identify', 'email', '...'] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults. + +At the time of authoring this documentation, the [following scopes are available](https://discordapp.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes): + +- bot +- connections +- email +- identify +- guilds +- guilds.join +- gdm.join +- messages.read +- rpc +- rpc.api +- rpc.notifications.read +- webhook.incoming + +### Refreshing a Token + +You can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse the fresh token from your data store to request a refresh: + +```php +// create $provider as in the initial example +$existingAccessToken = getAccessTokenFromYourDataStore(); + +if ($existingAccessToken->hasExpired()) { + $newAccessToken = $provider->getAccessToken('refresh_token', [ + 'refresh_token' => $existingAccessToken->getRefreshToken() + ]); + + // Purge old access token and store new access token to your data store. +} +``` + +### Client Credentials Grant + +Discord provides a client credentials flow for bot developers to get their own bearer tokens for testing purposes. This returns an access token for the *bot owner*: + +```php +// create $provider as in the initial example +try { + + // Try to get an access token using the client credentials grant. + $accessToken = $provider->getAccessToken('client_credentials'); + +} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { + + // Failed to get the access token + exit($e->getMessage()); + +} +``` + +### Bot Authorization + +To authorize a bot, specify a scope of `bot` and set [permissions](https://discordapp.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags) appropriately: + +```php +// create $provider as in the initial example + +$options = [ + 'scope' => ['bot'], + 'permissions' => 1 +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); + +// Redirect user to authorization page +header('Location: ' . $authUrl); +``` + +## Testing + +``` bash +$ ./vendor/bin/parallel-lint src test +$ ./vendor/bin/phpcs src --standard=psr2 -sp +$ ./vendor/bin/phpunit --coverage-text +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/wohali/oauth2-discord-new/blob/master/CONTRIBUTING.md) for details. + +## Credits + +- [Joan Touzet](https://github.com/wohali) +- [All Contributors](https://github.com/wohali/oauth2-discord-new/contributors) + +## License + +The MIT License (MIT). Please see [License File](https://github.com/wohali/oauth2-discord-new/blob/master/LICENSE) for more information. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..94358c7 --- /dev/null +++ b/composer.json @@ -0,0 +1,48 @@ +{ + "name": "wohali/oauth2-discord-new", + "description": "Discord OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Joan Touzet", + "email": "wohali@gmail.com", + "homepage": "https://github.com/wohali" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "discord" + ], + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^5.0", + "mockery/mockery": "~0.9", + "squizlabs/php_codesniffer": "^2.0", + "jakub-onderka/php-parallel-lint": "~0.9" + }, + "autoload": { + "psr-4": { + "Wohali\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Wohali\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "conflict": { + "team-reflex/oauth2-discord": ">=1.0" + } +} + diff --git a/coverage.clover b/coverage.clover new file mode 100644 index 0000000..f76c4a9 --- /dev/null +++ b/coverage.clover @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..2729fe9 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,38 @@ + + + + + + + + + ./test/ + + + + + ./ + + ./vendor + ./test + + + + + diff --git a/src/Provider/Discord.php b/src/Provider/Discord.php new file mode 100644 index 0000000..3bc4d5b --- /dev/null +++ b/src/Provider/Discord.php @@ -0,0 +1,125 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://packagist.org/packages/wohali/oauth2-discord-new Packagist + * @link https://github.com/wohali/oauth2-discord-new GitHub + */ + +namespace Wohali\OAuth2\Client\Provider; + +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Tool\BearerAuthorizationTrait; +use Psr\Http\Message\ResponseInterface; +use Wohali\OAuth2\Client\Provider\Exception\DiscordIdentityProviderException; + +class Discord extends AbstractProvider +{ + use BearerAuthorizationTrait; + + /** + * API Domain + * + * @var string + */ + public $apiDomain = 'https://discordapp.com/api/v6'; + + /** + * Get authorization URL to begin OAuth flow + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return $this->apiDomain.'/oauth2/authorize'; + } + + /** + * Get access token URL to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->apiDomain.'/oauth2/token'; + } + + /** + * Get provider URL to retrieve user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->apiDomain.'/users/@me'; + } + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * Discord's scope separator is space (%20) + * + * @return string Scope separator + */ + protected function getScopeSeparator() + { + return ' '; + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return array + */ + protected function getDefaultScopes() + { + return [ + 'identify', + 'email', + 'connections', + 'guilds', + 'guilds.join' + ]; + } + + /** + * Check a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface @response + * @param array $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if ($response->getStatusCode() >= 400) { + throw DiscordIdentityProviderException::clientException($response, $data); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return \League\OAuth2\Client\Provider\ResourceOwnerInterface + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new DiscordResourceOwner($response); + } +} diff --git a/src/Provider/DiscordResourceOwner.php b/src/Provider/DiscordResourceOwner.php new file mode 100644 index 0000000..549948c --- /dev/null +++ b/src/Provider/DiscordResourceOwner.php @@ -0,0 +1,109 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://packagist.org/packages/wohali/oauth2-discord-new Packagist + * @link https://github.com/wohali/oauth2-discord-new GitHub + */ + +namespace Wohali\OAuth2\Client\Provider; + +use League\OAuth2\Client\Provider\ResourceOwnerInterface; +use League\OAuth2\Client\Tool\ArrayAccessorTrait; + +class DiscordResourceOwner implements ResourceOwnerInterface +{ + use ArrayAccessorTrait; + + /** + * Raw response + * + * @var array + */ + protected $response; + + /** + * Creates new resource owner. + * + * @param array $response + */ + public function __construct(array $response = array()) + { + $this->response = $response; + } + + /** + * Get resource owner ID + * + * @return string|null + */ + public function getId() + { + return $this->getValueByKey($this->response, 'id'); + } + + /** + * Get resource owner username + * + * @return string|null + */ + public function getUsername() + { + return $this->getValueByKey($this->response, 'username'); + } + + /** + * Get resource owner discriminator + * + * @return string|null + */ + public function getDiscriminator() + { + return $this->getValueByKey($this->response, 'discriminator'); + } + + /** + * Get resource owner avatar hash + * + * @return string|null + */ + public function getAvatarHash() + { + return $this->getValueByKey($this->response, 'avatar'); + } + + /** + * Get resource owner verified flag + * + * @return bool + */ + public function getVerified() + { + return $this->getValueByKey($this->response, 'verified', false); + } + + /** + * Get resource owner email + * + * @return string|null + */ + public function getEmail() + { + return $this->getValueByKey($this->response, 'email'); + } + + /** + * Returns the raw resource owner response. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/src/Provider/Exception/DiscordIdentityProviderException.php b/src/Provider/Exception/DiscordIdentityProviderException.php new file mode 100644 index 0000000..5f690e8 --- /dev/null +++ b/src/Provider/Exception/DiscordIdentityProviderException.php @@ -0,0 +1,49 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://packagist.org/packages/wohali/oauth2-discord-new Packagist + * @link https://github.com/wohali/oauth2-discord-new GitHub + */ + +namespace Wohali\OAuth2\Client\Provider\Exception; + +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use Psr\Http\Message\ResponseInterface; + +class DiscordIdentityProviderException extends IdentityProviderException +{ + /** + * Creates client exception from response + * + * @param ResponseInterface $response + * @param array $data Parsed response data + * + * @return IdentityProviderException + */ + public static function clientException(ResponseInterface $response, $data) + { + return static::fromResponse( + $response, + isset($data['message']) ? $data['message'] : json_encode($data) + ); + } + + /** + * Creates identity exception from response + * + * @param ResponseInterface $response + * @param string $message + * + * @return IdentityProviderException + */ + protected static function fromResponse(ResponseInterface $response, $message = null) + { + return new static($message, $response->getStatusCode(), (string) $response->getBody()); + } +} diff --git a/test/src/Provider/DiscordTest.php b/test/src/Provider/DiscordTest.php new file mode 100644 index 0000000..e0bd181 --- /dev/null +++ b/test/src/Provider/DiscordTest.php @@ -0,0 +1,148 @@ +provider = new \Wohali\OAuth2\Client\Provider\Discord([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none' + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testScopes() + { + $scopeSeparator = ' '; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertContains($encodedScope, $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/api/v6/oauth2/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/api/v6/oauth2/token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "token_type":"Bearer", "scope": "identify"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testUserData() + { + $discriminator = rand(1000,9999); + $id = uniqid(); + $name = uniqid(); + $avatar = uniqid(); + $email = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "token_type":"Bearer", "scope": "identify"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"id": "'.$id.'", "username": "'.$name.'", "discriminator": "'.$discriminator.'", "avatar": "'.$avatar.'", "verified": true, "email": "'.$email.'"}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($id, $user->getId()); + $this->assertEquals($id, $user->toArray()['id']); + $this->assertEquals($name, $user->getUsername()); + $this->assertEquals($name, $user->toArray()['username']); + $this->assertEquals($discriminator, $user->getDiscriminator()); + $this->assertEquals($discriminator, $user->toArray()['discriminator']); + $this->assertEquals($avatar, $user->getAvatarHash()); + $this->assertEquals($avatar, $user->toArray()['avatar']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + $this->assertEquals(true, $user->getVerified()); + $this->assertEquals(true, $user->toArray()['verified']); + } + + /** + * @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException + **/ + public function testExceptionThrownErrorObjectReceived() + { + $status = rand(400,600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"client_id": ["This field is required"]}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'appliction/json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } +}