Skip to content

Commit

Permalink
Merge pull request #1 from gregurco/init
Browse files Browse the repository at this point in the history
Prepare v1
  • Loading branch information
gregurco committed Nov 3, 2017
2 parents 030ab80 + a3fa86f commit d1661ca
Show file tree
Hide file tree
Showing 11 changed files with 504 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Ignore potentially sensitive phpunit file
/phpunit.xml

# Ignore composer generated files
/composer.lock
/vendor/

# Ignore generated files
/build/
32 changes: 32 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
language: php

sudo: false

php:
- 7.0
- 7.1

env:
- SYMFONY_VERSION=3.2.*
- SYMFONY_VERSION=3.3.*

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

before_install:
- composer self-update

install:
- composer install

script:
- mkdir -p build/logs
- php vendor/bin/phpunit -c phpunit.xml.dist --coverage-text

after_success:
- travis_retry php vendor/bin/coveralls

notifications:
email:
- "gregurco.vlad@gmail.com"
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2017 Gregurco

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.
98 changes: 98 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Guzzle Bundle OAuth2 Plugin


[![Build Status](https://travis-ci.org/gregurco/GuzzleBundleOAuth2Plugin.svg?branch=master)](https://travis-ci.org/gregurco/GuzzleBundleOAuth2Plugin)
[![Coverage Status](https://coveralls.io/repos/gregurco/GuzzleBundleOAuth2Plugin/badge.svg?branch=master)](https://coveralls.io/r/gregurco/GuzzleBundleOAuth2Plugin)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/eba4f2e6-2c2a-4e92-85b6-c32ab3ac3aa7/mini.png)](https://insight.sensiolabs.com/projects/eba4f2e6-2c2a-4e92-85b6-c32ab3ac3aa7)

This plugin integrates [OAuth2][1] functionality into Guzzle Bundle, a bundle for building RESTful web service clients.


## Requirements
------------
- PHP 7.0 or above
- [Guzzle Bundle][2]
- [guzzle-oauth2-plugin][3]


## Installation
Using [composer][3]:

##### composer.json
``` json
{
"require": {
"gregurco/guzzle-bundle-oauth2-plugin": "dev-master"
}
}
```

##### command line
``` bash
$ composer require gregurco/guzzle-bundle-oauth2-plugin
```

## Usage
### Enable bundle
``` php
# app/AppKernel.php

new EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundle([
new Gregurco\Bundle\GuzzleBundleOAuth2Plugin\GuzzleBundleOAuth2Plugin(),
])
```

### Basic configuration
#### With password grant type
``` yaml
# app/config/config.yml

eight_points_guzzle:
clients:
api_payment:
base_url: "http://api.domain.tld"

auth: oauth2

# plugin settings
plugin:
oauth2:
base_uri: "https://example.com"
token_url: "/oauth/token"
username: "test@example.com"
password: "pa55w0rd"
client_id: "test-client-id"
scope: "administration"
```

#### With client credentials grant type
``` yaml
# app/config/config.yml

eight_points_guzzle:
clients:
api_payment:
base_url: "http://api.domain.tld"

auth: oauth2

# plugin settings
plugin:
oauth2:
base_uri: "http://om.dev"
token_url: "/app_dev.php/oauth"
client_id: "test-client-id"
client_secret: "test-client-secret" # optional
scope: "administration"
grant_type: "Sainsburys\\Guzzle\\Oauth2\\GrantType\\ClientCredentials"
```

See more information about middleware [here][3].

## License
This middleware is licensed under the MIT License - see the LICENSE file for details

[1]: http://www.xml.com/pub/a/2003/12/17/dive.html
[2]: https://github.com/8p/EightPointsGuzzleBundle
[3]: https://github.com/Sainsburys/guzzle-oauth2-plugin
[4]: https://getcomposer.org/
48 changes: 48 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "gregurco/guzzle-bundle-oauth2-plugin",
"type": "library",
"description": "OAuth2 Plugin for Guzzle Bundle, a PHP HTTP client library and framework for building RESTful web service clients",
"keywords": ["oauth2", "middleware", "plugin", "framework", "http", "rest", "web service", "curl", "client", "HTTP client"],
"homepage": "https://github.com/gregurco/GuzzleBundleOAuth2Plugin",
"license": "MIT",

"authors": [
{
"name": "Gregurco Vlad",
"email": "gregurco.vlad@gmail.com",
"homepage": "https://github.com/gregurco"
},
{
"name": "Community",
"homepage": "https://github.com/gregurco/GuzzleBundleOAuth2Plugin/contributors"
}
],

"require": {
"php": "^7.0",
"guzzlehttp/guzzle": "^6.0",
"eightpoints/guzzle-bundle": "~7.1",
"symfony/http-kernel": "~2.3|~3.0",
"symfony/config": "~2.3|~3.0",
"symfony/dependency-injection": "~2.3|~3.0",
"symfony/expression-language": "~2.3|~3.0",
"sainsburys/guzzle-oauth2-plugin": "^3.0"
},

"require-dev": {
"phpunit/phpunit": "~6.1",
"satooshi/php-coveralls": "~1.0"
},

"autoload": {
"psr-4": {
"Gregurco\\Bundle\\GuzzleBundleOAuth2Plugin\\": "src"
}
},

"autoload-dev": {
"psr-4": {
"Gregurco\\Bundle\\GuzzleBundleOAuth2Plugin\\Tests\\": "tests"
}
}
}
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 backupGlobals="false"
bootstrap="vendor/autoload.php"
colors="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.1/phpunit.xsd"
>
<testsuites>
<testsuite name="GuzzleBundleOAuth2Plugin Test Suite">
<directory>./tests</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory>./src</directory>
<exclude>
<directory>./src/Resources/</directory>
</exclude>
</whitelist>
</filter>

<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
22 changes: 22 additions & 0 deletions src/DependencyInjection/GuzzleBundleOAuth2Extension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Gregurco\Bundle\GuzzleBundleOAuth2Plugin\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class GuzzleBundleOAuth2Extension extends Extension
{
/**
* @param array $configs
* @param ContainerBuilder $container
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

$loader->load('services.xml');
}
}
112 changes: 112 additions & 0 deletions src/GuzzleBundleOAuth2Plugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

namespace Gregurco\Bundle\GuzzleBundleOAuth2Plugin;


use Gregurco\Bundle\GuzzleBundleOAuth2Plugin\DependencyInjection\GuzzleBundleOAuth2Extension;
use EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundlePlugin;
use Sainsburys\Guzzle\Oauth2\GrantType\PasswordCredentials;
use Sainsburys\Guzzle\Oauth2\GrantType\RefreshToken;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\ExpressionLanguage\Expression;
use GuzzleHttp\Client;

class GuzzleBundleOAuth2Plugin extends Bundle implements EightPointsGuzzleBundlePlugin
{
/**
* @param array $configs
* @param ContainerBuilder $container
*/
public function load(array $configs, ContainerBuilder $container)
{
$extension = new GuzzleBundleOAuth2Extension();
$extension->load($configs, $container);
}

/**
* @param array $config
* @param ContainerBuilder $container
* @param string $clientName
* @param Definition $handler
*/
public function loadForClient(array $config, ContainerBuilder $container, string $clientName, Definition $handler)
{
if ($config['enabled']) {
$middlewareConfig = [
PasswordCredentials::CONFIG_USERNAME => $config['username'],
PasswordCredentials::CONFIG_PASSWORD => $config['password'],
PasswordCredentials::CONFIG_CLIENT_ID => $config['client_id'],
PasswordCredentials::CONFIG_CLIENT_SECRET => $config['client_secret'],
PasswordCredentials::CONFIG_TOKEN_URL => $config['token_url'],
'scope' => $config['scope'],
];

// Define Client
$oauthClientDefinitionName = sprintf('guzzle_bundle_oauth2_plugin.client.%s', $clientName);
$oauthClientDefinition = new Definition(Client::class);
$oauthClientDefinition->addArgument(['base_uri' => $config['base_uri']]);
$container->setDefinition($oauthClientDefinitionName, $oauthClientDefinition);

// Define password credentials
$passwordCredentialsDefinitionName = sprintf('guzzle_bundle_oauth2_plugin.password_credentials.%s', $clientName);
$passwordCredentialsDefinition = new Definition($config['grant_type']);
$passwordCredentialsDefinition->addArgument(new Reference($oauthClientDefinitionName));
$passwordCredentialsDefinition->addArgument($middlewareConfig);
$container->setDefinition($passwordCredentialsDefinitionName, $passwordCredentialsDefinition);

// Define refresh token
$refreshTokenDefinitionName = sprintf('guzzle_bundle_oauth2_plugin.refresh_token.%s', $clientName);
$refreshTokenDefinition = new Definition(RefreshToken::class);
$refreshTokenDefinition->addArgument(new Reference($oauthClientDefinitionName));
$refreshTokenDefinition->addArgument($middlewareConfig);
$container->setDefinition($refreshTokenDefinitionName, $refreshTokenDefinition);

//Define middleware
$oAuth2MiddlewareDefinitionName = sprintf('guzzle_bundle_oauth2_plugin.middleware.%s', $clientName);
$oAuth2MiddlewareDefinition = new Definition('%guzzle_bundle_oauth2_plugin.middleware.class%');
$oAuth2MiddlewareDefinition->setArguments([
new Reference($oauthClientDefinitionName),
new Reference($passwordCredentialsDefinitionName),
new Reference($refreshTokenDefinitionName)
]);
$container->setDefinition($oAuth2MiddlewareDefinitionName, $oAuth2MiddlewareDefinition);

$onBeforeExpression = new Expression(sprintf('service("%s").onBefore()', $oAuth2MiddlewareDefinitionName));
$onFailureExpression = new Expression(sprintf('service("%s").onFailure(5)', $oAuth2MiddlewareDefinitionName));

$handler->addMethodCall('push', [$onBeforeExpression]);
$handler->addMethodCall('push', [$onFailureExpression]);
}
}

/**
* @param ArrayNodeDefinition $pluginNode
*/
public function addConfiguration(ArrayNodeDefinition $pluginNode)
{
$pluginNode
->canBeEnabled()
->children()
->scalarNode('base_uri')->defaultNull()->end()
->scalarNode('username')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()
->scalarNode('client_id')->defaultNull()->end()
->scalarNode('client_secret')->defaultNull()->end()
->scalarNode('token_url')->defaultNull()->end()
->scalarNode('scope')->defaultNull()->end()
->scalarNode('grant_type')->defaultValue(PasswordCredentials::class)->end()
->end();
}

/**
* @return string
*/
public function getPluginName() : string
{
return 'oauth2';
}
}
9 changes: 9 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
<parameter key="guzzle_bundle_oauth2_plugin.middleware.class">Sainsburys\Guzzle\Oauth2\Middleware\OAuthMiddleware</parameter>
</parameters>
</container>

0 comments on commit d1661ca

Please sign in to comment.