Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexMasterov committed Feb 4, 2017
0 parents commit 4f649b6
Show file tree
Hide file tree
Showing 12 changed files with 610 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/tests export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
phpunit.xml.dist export-ignore
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
build/
vendor/

composer.lock
phpunit.xml
30 changes: 30 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
language: php

sudo: false

cache:
directories:
- $HOME/.composer/cache
- vendor

git:
depth: 1

matrix:
fast_finish: true
include:
- php: 5.6
- php: 7
env:
- COMPOSER_FLAGS="--prefer-stable"
- php: 7.1

before_script:
- travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source --ignore-platform-reqs

script:
- vendor/bin/phpunit --report-useless-tests

after_script:
- bash -c '[[ -f "build/logs/clover.xml" ]] && wget https://scrutinizer-ci.com/ocular.phar'
- bash -c '[[ -f "build/logs/clover.xml" ]] && php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml'
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016-1017 Alex Masterov <[email protected]>

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.
58 changes: 58 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# StackExchange.com Provider for the OAuth 2.0 Client

[![Latest Stable Version](https://poser.pugx.org/alexmasterov/oauth2-stackexchange/v/stable)](https://packagist.org/packages/alexmasterov/oauth2-stackexchange)
[![License](https://img.shields.io/packagist/l/alexmasterov/oauth2-stackexchange.svg)](https://github.com/AlexMasterov/oauth2-stackexchange/blob/master/LICENSE)
[![Build Status](https://travis-ci.org/AlexMasterov/oauth2-stackexchange.svg)](https://travis-ci.org/AlexMasterov/oauth2-stackexchange)
[![Code Coverage](https://scrutinizer-ci.com/g/AlexMasterov/oauth2-stackexchange/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/AlexMasterov/oauth2-stackexchange/?branch=master)
[![Code Quality](https://scrutinizer-ci.com/g/AlexMasterov/oauth2-stackexchange/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/AlexMasterov/oauth2-stackexchange/?branch=master)

This package provides [StackExchange.com](https://stackexchange.com) OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

## Installation

The suggested installation method is via [composer](https://getcomposer.org/):

```sh
composer require alexmasterov/oauth2-stackexchange
```

## Usage

### Configuration
```php
$provider = new AlexMasterov\OAuth2\Client\Provider\StackExchange([
'clientId' => '{client_id}',
'clientSecret' => '{client_secret}',
'redirectUri' => '{redirect_uri}',
'state' => '{state}',
]);
```

### Authorization
```php
if (!empty($_GET['error'])) {
// Got an error, probably user denied access
exit('Got error: ' . $_GET['error']);
}

if (empty($_GET['code'])) {
// If we don't have an authorization code then get one
$provider->authorize();
}
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the owner details
$ownerDetails = $provider->getResourceOwner($token);
// Use these details to create a new profile
printf('Hello, %s!', $ownerDetails->getFirstName());
} catch (\Exception $e) {
// Failed to get user details
exit('Something went wrong: ' . $e->getMessage());
}
// Use this to interact with an API on the users behalf
echo $token->accessToken;
```
35 changes: 35 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "alexmasterov/oauth2-stackexchange",
"description": "The Stack Exchange OAuth 2.0 Client Provider for The PHP League OAuth2-Client",
"license": "MIT",
"authors": [{
"name": "Alex Masterov",
"email": "[email protected]"
}],
"keywords": [
"oauth",
"oauth2",
"client",
"authorization",
"authentication",
"stackexchange",
"stackoverflow"
],
"require": {
"league/oauth2-client": "^2.2"
},
"require-dev": {
"phpunit/phpunit": "^6.0",
"eloquent/phony": "^0.14"
},
"autoload": {
"psr-4": {
"AlexMasterov\\OAuth2\\Client\\Provider\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"AlexMasterov\\OAuth2\\Client\\Test\\Provider\\": "tests/"
}
}
}
12 changes: 12 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "gulp-livereload",
"version": "0.1.0",
"private": true,
"devDependencies": {
"gulp": "^3.9.1",
"gulp-livereload": "^3.8.1"
},
"scripts": {
"serve": "gulp"
}
}
26 changes: 26 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite>
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-text" target="php://stdout" />
<log type="coverage-clover" target="build/logs/clover.xml" />
</logging>
</phpunit>
29 changes: 29 additions & 0 deletions src/Exception/StackExchangeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace AlexMasterov\OAuth2\Client\Provider\Exception;

use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Message\ResponseInterface;

class StackExchangeException extends IdentityProviderException
{
/**
* @param ResponseInterface $response
* @param string|array $data
*
* @return static
*/
public static function errorResponse(ResponseInterface $response, $data)
{
$message = $data['error']['type'];

if (!empty($data['error']['message'])) {
$message .= ': '.$data['error']['message'];
}

$code = $response->getStatusCode();
$body = (string) $response->getBody();

return new static($message, $code, $body);
}
}
157 changes: 157 additions & 0 deletions src/StackExchange.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php

namespace AlexMasterov\OAuth2\Client\Provider;

use AlexMasterov\OAuth2\Client\Provider\Exception\StackExchangeException;
use GuzzleHttp\Exception\BadResponseException;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use UnexpectedValueException;

class StackExchange extends AbstractProvider
{
use BearerAuthorizationTrait;

/**
* @var string
*/
protected $urlApi = 'https://api.stackexchange.com/2.2/';

/**
* @var string
*/
protected $urlAuthorize = 'https://stackexchange.com/oauth';

/**
* @var string
*/
protected $urlAccessToken = 'https://stackexchange.com/oauth/access_token';

/**
* @var string
*/
protected $scope;

/**
* @var string
*/
protected $key;

/**
* @var string
*/
protected $site = 'stackoverflow';

/**
* @var string
*/
protected $state;

/**
* @var string
*/
protected $redirectUri;

/**
* @inheritDoc
*/
public function getBaseAuthorizationUrl()
{
return $this->urlAuthorize;
}

/**
* @inheritDoc
*/
public function getBaseAccessTokenUrl(array $params)
{
if (empty($params['code'])) {
$params['code'] = '';
}

return $this->urlAccessToken.'?'.
$this->buildQueryString($params);
}

/**
* @inheritDoc
*/
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return $this->urlApi.'/me?'.
$this->buildQueryString([
'access_token' => (string) $token,
'key' => $this->key,
'site' => $this->site
]);
}

/**
* @inheritDoc
*/
protected function getDefaultScopes()
{
return [];
}

/**
* @inheritDoc
*/
protected function getAuthorizationParameters(array $options)
{
$options['response_type'] = 'code';
$options['client_id'] = $this->clientId;

if (empty($options['state'])) {
$options['state'] = $this->state;
}

if (empty($options['scope'])) {
$options['scope'] = $this->scope;
}

if (empty($options['redirect_uri'])) {
$options['redirect_uri'] = $this->redirectUri;
}

return $options;
}

/**
* @inheritDoc
*/
protected function parseResponse(ResponseInterface $response)
{
$type = $this->getContentType($response);

if (strpos($type, 'plain') !== false) {
$content = (string) $response->getBody();
parse_str($content, $parsed);

return $parsed;
}

return parent::parseResponse($response);
}

/**
* @inheritDoc
*/
protected function checkResponse(ResponseInterface $response, $data)
{
if (isset($data['error'])) {
throw StackExchangeException::errorResponse($response, $data);
}
}

/**
* @inheritDoc
*/
protected function createResourceOwner(array $response, AccessToken $token)
{
return new StackExchangeResourceOwner($response);
}
}
Loading

0 comments on commit 4f649b6

Please sign in to comment.