Poniverse auth

This commit is contained in:
nelsonlaquet 2013-08-31 21:59:12 -05:00
parent 018e880508
commit b15b804999
50 changed files with 3904 additions and 34 deletions

11
app/config/poniverse.php Normal file
View file

@ -0,0 +1,11 @@
<?php
return [
'version' => 1,
'urls' => [
'api' => '',
'auth' => '',
'token' => ''
],
'client_id' => 0,
'secret' => ''
];

View file

@ -5,26 +5,7 @@
use Commands\RegisterUserCommand;
class AuthController extends \Controller {
public function postLogin() {
if (!\Auth::attempt(array('email' => \Input::get('email'), 'password' => \Input::get('password')), \Input::get('remember')))
return \Response::json(['messages' => ['username' => 'Invalid username or password']], 400);
return \Response::json(['user' => \Auth::user()]);
}
public function postLogout() {
\Auth::logout();
}
public function postRegister() {
$command = new RegisterUserCommand();
if (!$command->authorize())
return \Response::json([], 403);
$errors = $command->validate();
if ($errors->fails())
return \Response::json([], 400);
return \Response::json($command->execute());
}
}

View file

@ -20,7 +20,7 @@
->explicitFilter()
->published()
->orderBy('published_at', 'desc')
->take(30);
->take(20);
$recentTracks = [];

View file

@ -0,0 +1,93 @@
<?php
use Entities\User;
class AuthController extends Controller {
protected $poniverse;
public function __construct() {
$this->poniverse = new Poniverse(Config::get('poniverse.client_id'), Config::get('poniverse.secret'));
}
public function getLogin() {
if (Auth::guest())
return Redirect::to($this->poniverse->getAuthenticationUrl('login'));
return Redirect::to('/');
}
public function postLogout() {
Auth::logout();
return Redirect::to('/');
}
public function getOAuth() {
$code = $this->poniverse->getClient()->getAccessToken(
Config::get('poniverse.urls')['token'],
'authorization_code',
[
'code' => Input::query('code'),
'redirect_uri' => URL::to('/auth/oauth')
]);
if($code['code'] != 200) {
if($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) {
return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt'));
}
return Redirect::to('/')->with('message', 'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.' );
}
$this->poniverse->setAccessToken($code['result']['access_token']);
$poniverseUser = $this->poniverse->getUser();
$token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where('service', '=', 'poniverse')->first();
$setData = [
'access_token' => $code['result']['access_token'],
'expires' => date( 'Y-m-d H:i:s', strtotime("+".$code['result']['expires_in']." Seconds", time())),
'type' => $code['result']['token_type'],
];
if(isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) {
$setData['refresh_token'] = $code['result']['refresh_token'];
}
if($token) {
//User already exists, update access token and refresh token if provided.
DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData);
return $this->loginRedirect(User::find($token->user_id));
}
//Check by email to see if they already have an account
$localMember = User::where('email', '=', $poniverseUser['email'])->first();
if ($localMember) {
return $this->loginRedirect($localMember);
}
$user = new User;
$user->username = $poniverseUser['username'];
$user->display_name = $poniverseUser['display_name'];
$user->email = $poniverseUser['email'];
$user->created_at = gmdate("Y-m-d H:i:s", time());
$user->save();
$user->roles()->attach(4);
//We need to insert a new token row :O
$setData['user_id'] = $user->id;
$setData['external_user_id'] = $poniverseUser['id'];
$setData['service'] = 'poniverse';
DB::table('oauth2_tokens')->insert($setData);
return $this->loginRedirect($user);
}
protected function loginRedirect($user, $rememberMe = true) {
Auth::login($user, $rememberMe);
return Redirect::to('/');
}
}

View file

@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
class Oauth extends Migration {
public function up() {
Schema::create('oauth2_tokens', function($table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('external_user_id');
$table->text('access_token');
$table->timestamp('expires');
$table->text('refresh_token');
$table->string('type');
$table->string('service');
});
}
public function down() {
Schema::drop('oauth2_tokens');
}
}

View file

@ -1,15 +1,21 @@
<?php
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Auth\UserInterface;
use Illuminate\Hashing\HasherInterface;
class NullHasher implements HasherInterface {
public function make($value, array $options = array()) {
}
public function check($value, $hashedValue, array $options = array()) {
}
public function needsRehash($hashedValue, array $options = array()) {
}
}
class PFMAuth extends EloquentUserProvider {
function __construct() {
parent::__construct(new IpsHasher(), 'Entities\User');
}
public function validateCredentials(UserInterface $user, array $credentials) {
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword(), ['salt' => $user->password_salt]);
parent::__construct(new NullHasher(), 'Entities\User');
}
}

View file

@ -0,0 +1,95 @@
<?php
/**
* Class Poniverse
*
* Just for the sake of being sane without an autoloader
* this class is going to be a simple flat api class.
*/
class Poniverse {
protected $clientId;
protected $clientSecret;
protected $accessToken;
protected $redirectUri;
protected $urls;
/**
* @var OAuth2\Client
*/
protected $client;
/**
* Initialises the class
*
* @param string $clientId
* @param string $clientSecret
* @param string $accessToken
*/
public function __construct($clientId, $clientSecret, $accessToken = '')
{
$this->urls = Config::get('poniverse.urls');
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->accessToken = $accessToken;
//Setup Dependencies
$this->setupOAuth2();
$this->setupHttpful();
}
protected function setupOAuth2()
{
require_once('oauth2/Client.php');
require_once('oauth2/GrantType/IGrantType.php');
require_once('oauth2/GrantType/AuthorizationCode.php');
$this->client = new \OAuth2\Client($this->clientId, $this->clientSecret);
}
protected function setupHttpful()
{
require_once('autoloader.php');
$autoloader = new SplClassLoader('Httpful', __DIR__."/httpful/src/");
$autoloader->register();
}
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
}
public function getAuthenticationUrl($state)
{
return $this->client->getAuthenticationUrl($this->urls['auth'], $this->redirectUri, ['state' => $state]);
}
public function setRedirectUri($redirectUri)
{
$this->redirectUri = $redirectUri;
}
/**
* Gets the OAuth2 Client
*
* @return \OAuth2\Client
*/
public function getClient()
{
return $this->client;
}
/**
* Gets data about the currently logged in user
*
* @return array
*/
public function getUser()
{
$data = \Httpful\Request::get($this->urls['api'] . "users?access_token=" . $this->accessToken );
$result = $data->addHeader('Accept', 'application/json')->send();
return json_decode($result, true);
}
}

View file

@ -0,0 +1,137 @@
<?php
/**
* SplClassLoader implementation that implements the technical interoperability
* standards for PHP 5.3 namespaces and class names.
*
* http://groups.google.com/group/php-standards/web/final-proposal
*
* // Example which loads classes for the Doctrine Common package in the
* // Doctrine\Common namespace.
* $classLoader = new SplClassLoader('Doctrine\Common', '/path/to/doctrine');
* $classLoader->register();
*
* @author Jonathan H. Wage <jonwage@gmail.com>
* @author Roman S. Borschel <roman@code-factory.org>
* @author Matthew Weier O'Phinney <matthew@zend.com>
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
* @author Fabien Potencier <fabien.potencier@symfony-project.org>
*/
class SplClassLoader
{
private $_fileExtension = '.php';
private $_namespace;
private $_includePath;
private $_namespaceSeparator = '\\';
/**
* Creates a new <tt>SplClassLoader</tt> that loads classes of the
* specified namespace.
*
* @param string $ns The namespace to use.
* @param string $includePath
*/
public function __construct($ns = null, $includePath = null)
{
$this->_namespace = $ns;
$this->_includePath = $includePath;
}
/**
* Sets the namespace separator used by classes in the namespace of this class loader.
*
* @param string $sep The separator to use.
*/
public function setNamespaceSeparator($sep)
{
$this->_namespaceSeparator = $sep;
}
/**
* Gets the namespace seperator used by classes in the namespace of this class loader.
*
* @return string
*/
public function getNamespaceSeparator()
{
return $this->_namespaceSeparator;
}
/**
* Sets the base include path for all class files in the namespace of this class loader.
*
* @param string $includePath
*/
public function setIncludePath($includePath)
{
$this->_includePath = $includePath;
}
/**
* Gets the base include path for all class files in the namespace of this class loader.
*
* @return string $includePath
*/
public function getIncludePath()
{
return $this->_includePath;
}
/**
* Sets the file extension of class files in the namespace of this class loader.
*
* @param string $fileExtension
*/
public function setFileExtension($fileExtension)
{
$this->_fileExtension = $fileExtension;
}
/**
* Gets the file extension of class files in the namespace of this class loader.
*
* @return string $fileExtension
*/
public function getFileExtension()
{
return $this->_fileExtension;
}
/**
* Installs this class loader on the SPL autoload stack.
*/
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
}
/**
* Uninstalls this class loader from the SPL autoloader stack.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $className The name of the class to load.
* @return void
*/
public function loadClass($className)
{
if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) {
$fileName = '';
$namespace = '';
if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;
require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;
}
}
}

View file

@ -0,0 +1,4 @@
.DS_Store
composer.lock
vendor
downloads

View file

@ -0,0 +1,5 @@
language: php
before_script: cd tests
php:
- 5.3
- 5.4

View file

@ -0,0 +1,7 @@
Copyright (c) 2012 Nate Good <me@nategood.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.

View file

@ -0,0 +1,150 @@
# Httpful
[![Build Status](https://secure.travis-ci.org/nategood/httpful.png?branch=master)](http://travis-ci.org/nategood/httpful)
[Httpful](http://phphttpclient.com) is a simple Http Client library for PHP 5.3+. There is an emphasis of readability, simplicity, and flexibility basically provide the features and flexibility to get the job done and make those features really easy to use.
Features
- Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS)
- Custom Headers
- Automatic "Smart" Parsing
- Automatic Payload Serialization
- Basic Auth
- Client Side Certificate Auth
- Request "Templates"
# Sneak Peak
Here's something to whet your appetite. Search the twitter API for tweets containing "#PHP". Include a trivial header for the heck of it. Notice that the library automatically interprets the response as JSON (can override this if desired) and parses it as an array of objects.
$url = "http://search.twitter.com/search.json?q=" . urlencode('#PHP');
$response = Request::get($url)
->withXTrivialHeader('Just as a demo')
->send();
foreach ($response->body->results as $tweet) {
echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n";
}
# Installation
## Phar
A [PHP Archive](http://php.net/manual/en/book.phar.php) (or .phar) file is available for [downloading](http://phphttpclient.com/httpful.phar). Simply [download](http://phphttpclient.com/httpful.phar) the .phar, drop it into your project, and include it like you would any other php file. _This method is ideal smaller projects, one off scripts, and quick API hacking_.
<?php
include('httpful.phar');
$r = \Httpful\Request::get($uri)->sendIt();
...
## Composer
Httpful is PSR-0 compliant and can be installed using [composer](http://getcomposer.org/). Simply add `nategood/httpful` to your composer.json file. _Composer is the sane alternative to PEAR. It is excellent for managing dependancies in larger projects_.
{
"require": {
"nategood/httpful": "*"
}
}
## Install from Source
Because Httpful is PSR-0 compliant, you can also just clone the Httpful repository and use a PSR-0 compatible autoloader to load the library, like [Symfony's](http://symfony.com/doc/current/components/class_loader.html). Alternatively you can use the PSR-0 compliant autoloader included with the Httpful (simply `require("bootstrap.php")`).
# Show Me More!
You can checkout the [Httpful Landing Page](http://phphttpclient.com) for more info including many examples and [documentation](http:://phphttpclient.com/docs).
# Contributing
Httpful highly encourages sending in pull requests. When submitting a pull request please:
- All pull requests should target the `dev` branch (not `master`)
- Make sure your code follows the [coding conventions](http://pear.php.net/manual/en/standards.php)
- Please use soft tabs (four spaces) instead of hard tabs
- Make sure you add appropriate test coverage for your changes
- Run all unit tests in the test directory via `phpunit ./tests`
- Include commenting where appropriate and add a descriptive pull request message
# Changelog
## 0.2.6
- FIX [I #85](https://github.com/nategood/httpful/issues/85) Empty Content Length issue resolved
## 0.2.5
- FEATURE [I #80](https://github.com/nategood/httpful/issues/80) [I #81](https://github.com/nategood/httpful/issues/81) Proxy support added with `useProxy` method.
## 0.2.4
- FEATURE [I #77](https://github.com/nategood/httpful/issues/77) Convenience method for setting a timeout (seconds) `$req->timeoutIn(10);`
- FIX [I #75](https://github.com/nategood/httpful/issues/75) [I #78](https://github.com/nategood/httpful/issues/78) Bug with checking if digest auth is being used.
## 0.2.3
- FIX Overriding default Mime Handlers
- FIX [PR #73](https://github.com/nategood/httpful/pull/73) Parsing http status codes
## 0.2.2
- FEATURE Add support for parsing JSON responses as associative arrays instead of objects
- FEATURE Better support for setting constructor arguments on Mime Handlers
## 0.2.1
- FEATURE [PR #72](https://github.com/nategood/httpful/pull/72) Allow support for custom Accept header
## 0.2.0
- REFACTOR [PR #49](https://github.com/nategood/httpful/pull/49) Broke headers out into their own class
- REFACTOR [PR #54](https://github.com/nategood/httpful/pull/54) Added more specific Exceptions
- FIX [PR #58](https://github.com/nategood/httpful/pull/58) Fixes throwing an error on an empty xml response
- FEATURE [PR #57](https://github.com/nategood/httpful/pull/57) Adds support for digest authentication
## 0.1.6
- Ability to set the number of max redirects via overloading `followRedirects(int max_redirects)`
- Standards Compliant fix to `Accepts` header
- Bug fix for bootstrap process when installed via Composer
## 0.1.5
- Use `DIRECTORY_SEPARATOR` constant [PR #33](https://github.com/nategood/httpful/pull/32)
- [PR #35](https://github.com/nategood/httpful/pull/35)
- Added the raw\_headers property reference to response.
- Compose request header and added raw\_header to Request object.
- Fixed response has errors and added more comments for clarity.
- Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616.
- Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details.
- Added default User-Agent header
- `User-Agent: Httpful/0.1.5` + curl version + server software + PHP version
- To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks.
- Completed test units for additions.
- Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier.
## 0.1.4
- Add support for CSV Handling [PR #32](https://github.com/nategood/httpful/pull/32)
## 0.1.3
- Handle empty responses in JsonParser and XmlParser
## 0.1.2
- Added support for setting XMLHandler configuration options
- Added examples for overriding XmlHandler and registering a custom parser
- Removed the httpful.php download (deprecated in favor of httpful.phar)
## 0.1.1
- Bug fix serialization default case and phpunit tests
## 0.1.0
- Added Support for Registering Mime Handlers
- Created AbstractMimeHandler type that all Mime Handlers must extend
- Pulled out the parsing/serializing logic from the Request/Response classes into their own MimeHandler classes
- Added ability to register new mime handlers for mime types

View file

@ -0,0 +1,4 @@
<?php
require(__DIR__ . '/src/Httpful/Bootstrap.php');
\Httpful\Bootstrap::init();

View file

@ -0,0 +1,51 @@
#!/usr/bin/php
<?php
/**
* Build the whole library into a single file
* as an easy drop in solution as opposed to
* relying on autoloader. Sometimes we just
* want to hack with an API as a one off thing.
* Httpful should make this easy.
*/
function exit_unless($condition, $msg = null) {
if ($condition)
return;
echo "[FAIL]\n$msg\n";
exit(1);
}
// Create the Httpful Phar
echo "Building Phar... ";
$base_dir = dirname(__FILE__);
$source_dir = $base_dir . '/src/Httpful/';
$phar_path = $base_dir . '/downloads/httpful.phar';
$phar = new Phar($phar_path, 0, 'httpful.phar');
$stub = <<<HEREDOC
<?php
// Phar Stub File
Phar::mapPhar('httpful.phar');
include('phar://httpful.phar/Httpful/Bootstrap.php');
\Httpful\Bootstrap::pharInit();
__HALT_COMPILER();
HEREDOC;
try {
$phar->setStub($stub);
} catch(Exception $e) {
$phar = false;
}
exit_unless($phar, "Unable to create a phar. Make certain you have phar.readonly=0 set in your ini file.");
$phar->buildFromDirectory(dirname($source_dir));
echo "[ OK ]\n";
// Add it to git!
echo "Adding httpful.phar to the repo... ";
$return_code = 0;
passthru("git add $phar_path", $return_code);
exit_unless($return_code === 0, "Unable to add download files to git.");
echo "[ OK ]\n";
echo "\nBuild completed successfully.\n\n";

View file

@ -0,0 +1,27 @@
{
"name": "nategood/httpful",
"description": "A Readable, Chainable, REST friendly, PHP HTTP Client",
"homepage": "http://github.com/nategood/httpful",
"license": "MIT",
"keywords": ["http", "curl", "rest", "restful", "api", "requests"],
"version": "0.2.6",
"authors": [
{
"name": "Nate Good",
"email": "me@nategood.com",
"homepage": "http://nategood.com"
}
],
"require": {
"php": ">=5.3",
"ext-curl": "*"
},
"autoload": {
"psr-0": {
"Httpful": "src/"
}
},
"require-dev": {
"phpunit/phpunit": "*"
}
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Grab some The Dead Weather albums from Freebase
*/
require(__DIR__ . '/../bootstrap.php');
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)
->expectsJson()
->sendIt();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";

View file

@ -0,0 +1,9 @@
<?php
// XML Example from GitHub
require(__DIR__ . '/../bootstrap.php');
use \Httpful\Request;
$uri = 'https://github.com/api/v2/xml/user/show/nategood';
$request = Request::get($uri)->send();
echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n";

View file

@ -0,0 +1,44 @@
<?php
require(__DIR__ . '/../bootstrap.php');
// We can override the default parser configuration options be registering
// a parser with different configuration options for a particular mime type
// Example setting a namespace for the XMLHandler parser
$conf = array('namespace' => 'http://example.com');
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
// We can also add the parsers with our own...
class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
{
/**
* Takes a response body, and turns it into
* a two dimensional array.
*
* @param string $body
* @return mixed
*/
public function parse($body)
{
return str_getcsv($body);
}
/**
* Takes a two dimensional array and turns it
* into a serialized string to include as the
* body of a request
*
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
$serialized = '';
foreach ($payload as $line) {
$serialized .= '"' . implode('","', $line) . '"' . "\n";
}
return $serialized;
}
}
\Httpful\Httpful::register('text/csv', new SimpleCsvHandler());

View file

@ -0,0 +1,24 @@
<?php
require(__DIR__ . '/../bootstrap.php');
use \Httpful\Request;
// Get event details for a public event
$uri = "http://api.showclix.com/Event/8175";
$response = Request::get($uri)
->expectsType('json')
->sendIt();
// Print out the event details
echo "The event {$response->body->event} will take place on {$response->body->event_start}\n";
// Example overriding the default JSON handler with one that encodes the response as an array
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));
$response = Request::get($uri)
->expectsType('json')
->sendIt();
// Print out the event details
echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n";

View file

@ -0,0 +1,97 @@
<?php
namespace Httpful;
/**
* Bootstrap class that facilitates autoloading. A naive
* PSR-0 autoloader.
*
* @author Nate Good <me@nategood.com>
*/
class Bootstrap
{
const DIR_GLUE = DIRECTORY_SEPARATOR;
const NS_GLUE = '\\';
public static $registered = false;
/**
* Register the autoloader and any other setup needed
*/
public static function init()
{
spl_autoload_register(array('\Httpful\Bootstrap', 'autoload'));
self::registerHandlers();
}
/**
* The autoload magic (PSR-0 style)
*
* @param string $classname
*/
public static function autoload($classname)
{
self::_autoload(dirname(dirname(__FILE__)), $classname);
}
/**
* Register the autoloader and any other setup needed
*/
public static function pharInit()
{
spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload'));
self::registerHandlers();
}
/**
* Phar specific autoloader
*
* @param string $classname
*/
public static function pharAutoload($classname)
{
self::_autoload('phar://httpful.phar', $classname);
}
/**
* @param string base
* @param string classname
*/
private static function _autoload($base, $classname)
{
$parts = explode(self::NS_GLUE, $classname);
$path = $base . self::DIR_GLUE . implode(self::DIR_GLUE, $parts) . '.php';
if (file_exists($path)) {
require_once($path);
}
}
/**
* Register default mime handlers. Is idempotent.
*/
public static function registerHandlers()
{
if (self::$registered === true) {
return;
}
// @todo check a conf file to load from that instead of
// hardcoding into the library?
$handlers = array(
\Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(),
\Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(),
\Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(),
\Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(),
);
foreach ($handlers as $mime => $handler) {
// Don't overwrite if the handler has already been registered
if (Httpful::hasParserRegistered($mime))
continue;
Httpful::register($mime, $handler);
}
self::$registered = true;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace Httpful\Exception;
class ConnectionErrorException extends \Exception
{
}

View file

@ -0,0 +1,50 @@
<?php
/**
* Mime Type: text/csv
* @author Raja Kapur <rajak@twistedthrottle.com>
*/
namespace Httpful\Handlers;
class CsvHandler extends MimeHandlerAdapter
{
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
if (empty($body))
return null;
$parsed = array();
$fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r');
while (($r = fgetcsv($fp)) !== FALSE) {
$parsed[] = $r;
}
if (empty($parsed))
throw new \Exception("Unable to parse response as CSV");
return $parsed;
}
/**
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
$fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+');
$i = 0;
foreach ($payload as $fields) {
if($i++ == 0) {
fputcsv($fp, array_keys($fields));
}
fputcsv($fp, $fields);
}
rewind($fp);
$data = stream_get_contents($fp);
fclose($fp);
return $data;
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* Mime Type: application/x-www-urlencoded
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class FormHandler extends MimeHandlerAdapter
{
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
$parsed = array();
parse_str($body, $parsed);
return $parsed;
}
/**
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
return http_build_query($payload, null, '&');
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* Mime Type: application/json
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class JsonHandler extends MimeHandlerAdapter
{
private $decode_as_array = false;
public function init(array $args)
{
$this->decode_as_array = !!(array_key_exists('decode_as_array', $args) ? $args['decode_as_array'] : false);
}
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
if (empty($body))
return null;
$parsed = json_decode($body, $this->decode_as_array);
if (is_null($parsed))
throw new \Exception("Unable to parse response as JSON");
return $parsed;
}
/**
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
return json_encode($payload);
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* Handlers are used to parse and serialize payloads for specific
* mime types. You can register a custom handler via the register
* method. You can also override a default parser in this way.
*/
namespace Httpful\Handlers;
class MimeHandlerAdapter
{
public function __construct(array $args = array())
{
$this->init($args);
}
/**
* Initial setup of
* @param array $args
*/
public function init(array $args)
{
}
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
return $body;
}
/**
* @param mixed $payload
* @return string
*/
function serialize($payload)
{
return (string) $payload;
}
}

View file

@ -0,0 +1,44 @@
# Handlers
Handlers are simple classes that are used to parse response bodies and serialize request payloads. All Handlers must extend the `MimeHandlerAdapter` class and implement two methods: `serialize($payload)` and `parse($response)`. Let's build a very basic Handler to register for the `text/csv` mime type.
<?php
class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
{
/**
* Takes a response body, and turns it into
* a two dimensional array.
*
* @param string $body
* @return mixed
*/
public function parse($body)
{
return str_getcsv($body);
}
/**
* Takes a two dimensional array and turns it
* into a serialized string to include as the
* body of a request
*
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
$serialized = '';
foreach ($payload as $line) {
$serialized .= '"' . implode('","', $line) . '"' . "\n";
}
return $serialized;
}
}
Finally, you must register this handler for a particular mime type.
Httpful::register('text/csv', new SimpleCsvHandler());
After this registering the handler in your source code, by default, any responses with a mime type of text/csv should be parsed by this handler.

View file

@ -0,0 +1,15 @@
<?php
/**
* Mime Type: text/html
* Mime Type: application/html+xml
*
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class XHtmlHandler extends MimeHandlerAdapter
{
// @todo add html specific parsing
// see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php
}

View file

@ -0,0 +1,120 @@
<?php
/**
* Mime Type: application/xml
*
* @author Zack Douglas <zack@zackerydouglas.info>
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class XmlHandler extends MimeHandlerAdapter
{
/**
* @var string $namespace xml namespace to use with simple_load_string
*/
private $namespace;
/**
* @var int $libxml_opts see http://www.php.net/manual/en/libxml.constants.php
*/
private $libxml_opts;
/**
* @param array $conf sets configuration options
*/
public function __construct(array $conf = array())
{
$this->namespace = isset($conf['namespace']) ? $conf['namespace'] : '';
$this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0;
}
/**
* @param string $body
* @return mixed
* @throws Exception if unable to parse
*/
public function parse($body)
{
if (empty($body))
return null;
$parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace);
if ($parsed === false)
throw new \Exception("Unable to parse response as XML");
return $parsed;
}
/**
* @param mixed $payload
* @return string
* @throws Exception if unable to serialize
*/
public function serialize($payload)
{
list($_, $dom) = $this->_future_serializeAsXml($payload);
return $dom->saveXml();
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
*/
private function _future_serializeAsXml($value, $node = null, $dom = null)
{
if (!$dom) {
$dom = new \DOMDocument;
}
if (!$node) {
if (!is_object($value)) {
$node = $dom->createElement('response');
$dom->appendChild($node);
} else {
$node = $dom;
}
}
if (is_object($value)) {
$objNode = $dom->createElement(get_class($value));
$node->appendChild($objNode);
$this->_future_serializeObjectAsXml($value, $objNode, $dom);
} else if (is_array($value)) {
$arrNode = $dom->createElement('array');
$node->appendChild($arrNode);
$this->_future_serializeArrayAsXml($value, $arrNode, $dom);
} else if (is_bool($value)) {
$node->appendChild($dom->createTextNode($value?'TRUE':'FALSE'));
} else {
$node->appendChild($dom->createTextNode($value));
}
return array($node, $dom);
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
*/
private function _future_serializeArrayAsXml($value, &$parent, &$dom)
{
foreach ($value as $k => &$v) {
$n = $k;
if (is_numeric($k)) {
$n = "child-{$n}";
}
$el = $dom->createElement($n);
$parent->appendChild($el);
$this->_future_serializeAsXml($v, $el, $dom);
}
return array($parent, $dom);
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
*/
private function _future_serializeObjectAsXml($value, &$parent, &$dom)
{
$refl = new \ReflectionObject($value);
foreach ($refl->getProperties() as $pr) {
if (!$pr->isPrivate()) {
$el = $dom->createElement($pr->getName());
$parent->appendChild($el);
$this->_future_serializeAsXml($pr->getValue($value), $el, $dom);
}
}
return array($parent, $dom);
}
}

View file

@ -0,0 +1,86 @@
<?php
namespace Httpful;
/**
* @author Nate Good <me@nategood.com>
*/
class Http
{
const HEAD = 'HEAD';
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const DELETE = 'DELETE';
const PATCH = 'PATCH';
const OPTIONS = 'OPTIONS';
const TRACE = 'TRACE';
/**
* @return array of HTTP method strings
*/
public static function safeMethods()
{
return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE);
}
/**
* @return bool
* @param string HTTP method
*/
public static function isSafeMethod($method)
{
return in_array($method, self::safeMethods());
}
/**
* @return bool
* @param string HTTP method
*/
public static function isUnsafeMethod($method)
{
return !in_array($method, self::safeMethods());
}
/**
* @return array list of (always) idempotent HTTP methods
*/
public static function idempotentMethods()
{
// Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than
// not, it is not.
return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH);
}
/**
* @return bool
* @param string HTTP method
*/
public static function isIdempotent($method)
{
return in_array($method, self::safeidempotentMethodsMethods());
}
/**
* @return bool
* @param string HTTP method
*/
public static function isNotIdempotent($method)
{
return !in_array($method, self::idempotentMethods());
}
/**
* @deprecated Technically anything *can* have a body,
* they just don't have semantic meaning. So say's Roy
* http://tech.groups.yahoo.com/group/rest-discuss/message/9962
*
* @return array of HTTP method strings
*/
public static function canHaveBody()
{
return array(self::POST, self::PUT, self::PATCH, self::OPTIONS);
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Httpful;
class Httpful {
const VERSION = '0.2.4';
private static $mimeRegistrar = array();
private static $default = null;
/**
* @param string $mime_type
* @param MimeHandlerAdapter $handler
*/
public static function register($mimeType, \Httpful\Handlers\MimeHandlerAdapter $handler)
{
self::$mimeRegistrar[$mimeType] = $handler;
}
/**
* @param string $mime_type defaults to MimeHandlerAdapter
* @return MimeHandlerAdapter
*/
public static function get($mimeType = null)
{
if (isset(self::$mimeRegistrar[$mimeType])) {
return self::$mimeRegistrar[$mimeType];
}
if (empty(self::$default)) {
self::$default = new \Httpful\Handlers\MimeHandlerAdapter();
}
return self::$default;
}
/**
* Does this particular Mime Type have a parser registered
* for it?
* @return bool
*/
public static function hasParserRegistered($mimeType)
{
return isset(self::$mimeRegistrar[$mimeType]);
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Httpful;
/**
* Class to organize the Mime stuff a bit more
* @author Nate Good <me@nategood.com>
*/
class Mime
{
const JSON = 'application/json';
const XML = 'application/xml';
const XHTML = 'application/html+xml';
const FORM = 'application/x-www-form-urlencoded';
const PLAIN = 'text/plain';
const JS = 'text/javascript';
const HTML = 'text/html';
const YAML = 'application/x-yaml';
const CSV = 'text/csv';
/**
* Map short name for a mime type
* to a full proper mime type
*/
public static $mimes = array(
'json' => self::JSON,
'xml' => self::XML,
'form' => self::FORM,
'plain' => self::PLAIN,
'text' => self::PLAIN,
'html' => self::HTML,
'xhtml' => self::XHTML,
'js' => self::JS,
'javascript'=> self::JS,
'yaml' => self::YAML,
'csv' => self::CSV,
);
/**
* Get the full Mime Type name from a "short name".
* Returns the short if no mapping was found.
* @return string full mime type (e.g. application/json)
* @param string common name for mime type (e.g. json)
*/
public static function getFullMime($short_name)
{
return array_key_exists($short_name, self::$mimes) ? self::$mimes[$short_name] : $short_name;
}
/**
* @return bool
* @param string $short_name
*/
public static function supportsMimeType($short_name)
{
return array_key_exists($short_name, self::$mimes);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,189 @@
<?php
namespace Httpful;
/**
* Models an HTTP response
*
* @author Nate Good <me@nategood.com>
*/
class Response
{
public $body,
$raw_body,
$headers,
$raw_headers,
$request,
$code = 0,
$content_type,
$parent_type,
$charset,
$is_mime_vendor_specific = false,
$is_mime_personal = false;
private $parsers;
/**
* @param string $body
* @param string $headers
* @param Request $request
*/
public function __construct($body, $headers, Request $request)
{
$this->request = $request;
$this->raw_headers = $headers;
$this->raw_body = $body;
$this->code = $this->_parseCode($headers);
$this->headers = Response\Headers::fromString($headers);
$this->_interpretHeaders();
$this->body = $this->_parse($body);
}
/**
* Status Code Definitions
*
* Informational 1xx
* Successful 2xx
* Redirection 3xx
* Client Error 4xx
* Server Error 5xx
*
* http://pretty-rfc.herokuapp.com/RFC2616#status.codes
*
* @return bool Did we receive a 4xx or 5xx?
*/
public function hasErrors()
{
return $this->code >= 400;
}
/**
* @return return bool
*/
public function hasBody()
{
return !empty($this->body);
}
/**
* Parse the response into a clean data structure
* (most often an associative array) based on the expected
* Mime type.
* @return array|string|object the response parse accordingly
* @param string Http response body
*/
public function _parse($body)
{
// If the user decided to forgo the automatic
// smart parsing, short circuit.
if (!$this->request->auto_parse) {
return $body;
}
// If provided, use custom parsing callback
if (isset($this->request->parse_callback)) {
return call_user_func($this->request->parse_callback, $body);
}
// Decide how to parse the body of the response in the following order
// 1. If provided, use the mime type specifically set as part of the `Request`
// 2. If a MimeHandler is registered for the content type, use it
// 3. If provided, use the "parent type" of the mime type from the response
// 4. Default to the content-type provided in the response
$parse_with = $this->request->expected_type;
if (empty($this->request->expected_type)) {
$parse_with = Httpful::hasParserRegistered($this->content_type)
? $this->content_type
: $this->parent_type;
}
return Httpful::get($parse_with)->parse($body);
}
/**
* Parse text headers from response into
* array of key value pairs
* @return array parse headers
* @param string $headers raw headers
*/
public function _parseHeaders($headers)
{
$headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY);
$parse_headers = array();
for ($i = 1; $i < count($headers); $i++) {
list($key, $raw_value) = explode(':', $headers[$i], 2);
$key = trim($key);
$value = trim($raw_value);
if (array_key_exists($key, $parse_headers)) {
// See HTTP RFC Sec 4.2 Paragraph 5
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
// If a header appears more than once, it must also be able to
// be represented as a single header with a comma-separated
// list of values. We transform accordingly.
$parse_headers[$key] .= ',' . $value;
} else {
$parse_headers[$key] = $value;
}
}
return $parse_headers;
}
public function _parseCode($headers)
{
$parts = explode(' ', substr($headers, 0, strpos($headers, "\r\n")));
if (count($parts) < 2 || !is_numeric($parts[1])) {
throw new \Exception("Unable to parse response code from HTTP response due to malformed response");
}
return intval($parts[1]);
}
/**
* After we've parse the headers, let's clean things
* up a bit and treat some headers specially
*/
public function _interpretHeaders()
{
// Parse the Content-Type and charset
$content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : '';
$content_type = explode(';', $content_type);
$this->content_type = $content_type[0];
if (count($content_type) == 2 && strpos($content_type[1], '=') !== false) {
list($nill, $this->charset) = explode('=', $content_type[1]);
}
// RFC 2616 states "text/*" Content-Types should have a default
// charset of ISO-8859-1. "application/*" and other Content-Types
// are assumed to have UTF-8 unless otherwise specified.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1
// http://www.w3.org/International/O-HTTP-charset.en.php
if (!isset($this->charset)) {
$this->charset = substr($this->content_type, 5) === 'text/' ? 'iso-8859-1' : 'utf-8';
}
// Is vendor type? Is personal type?
if (strpos($this->content_type, '/') !== false) {
list($type, $sub_type) = explode('/', $this->content_type);
$this->is_mime_vendor_specific = substr($sub_type, 0, 4) === 'vnd.';
$this->is_mime_personal = substr($sub_type, 0, 4) === 'prs.';
}
// Parent type (e.g. xml for application/vnd.github.message+xml)
$this->parent_type = $this->content_type;
if (strpos($this->content_type, '+') !== false) {
list($vendor, $this->parent_type) = explode('+', $this->content_type, 2);
$this->parent_type = Mime::getFullMime($this->parent_type);
}
}
/**
* @return string
*/
public function __toString()
{
return $this->raw_body;
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Httpful\Response;
final class Headers implements \ArrayAccess, \Countable {
private $headers;
private function __construct($headers)
{
$this->headers = $headers;
}
public static function fromString($string)
{
$lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY);
array_shift($lines); // HTTP HEADER
$headers = array();
foreach ($lines as $line) {
list($name, $value) = explode(':', $line, 2);
$headers[strtolower(trim($name))] = trim($value);
}
return new self($headers);
}
public function offsetExists($offset)
{
return isset($this->headers[strtolower($offset)]);
}
public function offsetGet($offset)
{
if (isset($this->headers[$name = strtolower($offset)])) {
return $this->headers[$name];
}
}
public function offsetSet($offset, $value)
{
throw new \Exception("Headers are read-only.");
}
public function offsetUnset($offset)
{
throw new \Exception("Headers are read-only.");
}
public function count()
{
return count($this->headers);
}
public function toArray()
{
return $this->headers;
}
}

View file

@ -0,0 +1,458 @@
<?php
/**
* Port over the original tests into a more traditional PHPUnit
* format. Still need to hook into a lightweight HTTP server to
* better test some things (e.g. obscure cURL settings). I've moved
* the old tests and node.js server to the tests/.legacy directory.
*
* @author Nate Good <me@nategood.com>
*/
namespace Httpful\Test;
require(dirname(dirname(dirname(__FILE__))) . '/bootstrap.php');
\Httpful\Bootstrap::init();
use Httpful\Httpful;
use Httpful\Request;
use Httpful\Mime;
use Httpful\Http;
use Httpful\Response;
class HttpfulTest extends \PHPUnit_Framework_TestCase
{
const TEST_SERVER = '127.0.0.1:8008';
const TEST_URL = 'http://127.0.0.1:8008';
const TEST_URL_400 = 'http://127.0.0.1:8008/400';
const SAMPLE_JSON_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/json
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_JSON_RESPONSE = '{"key":"value","object":{"key":"value"},"array":[1,2,3,4]}';
const SAMPLE_CSV_HEADER =
"HTTP/1.1 200 OK
Content-Type: text/csv
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_CSV_RESPONSE =
"Key1,Key2
Value1,Value2
\"40.0\",\"Forty\"";
const SAMPLE_XML_RESPONSE = '<stdClass><arrayProp><array><k1><myClass><intProp>2</intProp></myClass></k1></array></arrayProp><stringProp>a string</stringProp><boolProp>TRUE</boolProp></stdClass>';
const SAMPLE_XML_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/xml
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_VENDOR_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/vnd.nategood.message+xml
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_VENDOR_TYPE = "application/vnd.nategood.message+xml";
const SAMPLE_MULTI_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/json
Connection: keep-alive
Transfer-Encoding: chunked
X-My-Header:Value1
X-My-Header:Value2\r\n";
function testInit()
{
$r = Request::init();
// Did we get a 'Request' object?
$this->assertEquals('Httpful\Request', get_class($r));
}
function testMethods()
{
$valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head');
$url = 'http://example.com/';
foreach ($valid_methods as $method) {
$r = call_user_func(array('Httpful\Request', $method), $url);
$this->assertEquals('Httpful\Request', get_class($r));
$this->assertEquals(strtoupper($method), $r->method);
}
}
function testDefaults()
{
// Our current defaults are as follows
$r = Request::init();
$this->assertEquals(Http::GET, $r->method);
$this->assertFalse($r->strict_ssl);
}
function testShortMime()
{
// Valid short ones
$this->assertEquals(Mime::JSON, Mime::getFullMime('json'));
$this->assertEquals(Mime::XML, Mime::getFullMime('xml'));
$this->assertEquals(Mime::HTML, Mime::getFullMime('html'));
$this->assertEquals(Mime::CSV, Mime::getFullMime('csv'));
// Valid long ones
$this->assertEquals(Mime::JSON, Mime::getFullMime(Mime::JSON));
$this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML));
$this->assertEquals(Mime::HTML, Mime::getFullMime(Mime::HTML));
$this->assertEquals(Mime::CSV, Mime::getFullMime(Mime::CSV));
// No false positives
$this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML));
$this->assertNotEquals(Mime::JSON, Mime::getFullMime(Mime::XML));
$this->assertNotEquals(Mime::HTML, Mime::getFullMime(Mime::JSON));
$this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::CSV));
}
function testSettingStrictSsl()
{
$r = Request::init()
->withStrictSsl();
$this->assertTrue($r->strict_ssl);
$r = Request::init()
->withoutStrictSsl();
$this->assertFalse($r->strict_ssl);
}
function testSendsAndExpectsType()
{
$r = Request::init()
->sendsAndExpectsType(Mime::JSON);
$this->assertEquals(Mime::JSON, $r->expected_type);
$this->assertEquals(Mime::JSON, $r->content_type);
$r = Request::init()
->sendsAndExpectsType('html');
$this->assertEquals(Mime::HTML, $r->expected_type);
$this->assertEquals(Mime::HTML, $r->content_type);
$r = Request::init()
->sendsAndExpectsType('form');
$this->assertEquals(Mime::FORM, $r->expected_type);
$this->assertEquals(Mime::FORM, $r->content_type);
$r = Request::init()
->sendsAndExpectsType('application/x-www-form-urlencoded');
$this->assertEquals(Mime::FORM, $r->expected_type);
$this->assertEquals(Mime::FORM, $r->content_type);
$r = Request::init()
->sendsAndExpectsType(Mime::CSV);
$this->assertEquals(Mime::CSV, $r->expected_type);
$this->assertEquals(Mime::CSV, $r->content_type);
}
function testIni()
{
// Test setting defaults/templates
// Create the template
$template = Request::init()
->method(Http::POST)
->withStrictSsl()
->expectsType(Mime::HTML)
->sendsType(Mime::FORM);
Request::ini($template);
$r = Request::init();
$this->assertTrue($r->strict_ssl);
$this->assertEquals(Http::POST, $r->method);
$this->assertEquals(Mime::HTML, $r->expected_type);
$this->assertEquals(Mime::FORM, $r->content_type);
// Test the default accessor as well
$this->assertTrue(Request::d('strict_ssl'));
$this->assertEquals(Http::POST, Request::d('method'));
$this->assertEquals(Mime::HTML, Request::d('expected_type'));
$this->assertEquals(Mime::FORM, Request::d('content_type'));
Request::resetIni();
}
function testAccept()
{
$r = Request::get('http://example.com/')
->expectsType(Mime::JSON);
$this->assertEquals(Mime::JSON, $r->expected_type);
$r->_curlPrep();
$this->assertContains('application/json', $r->raw_headers);
}
function testCustomAccept()
{
$accept = 'application/api-1.0+json';
$r = Request::get('http://example.com/')
->addHeader('Accept', $accept);
$r->_curlPrep();
$this->assertContains($accept, $r->raw_headers);
$this->assertEquals($accept, $r->headers['Accept']);
}
function testUserAgent()
{
$r = Request::get('http://example.com/')
->withUserAgent('ACME/1.2.3');
$this->assertArrayHasKey('User-Agent', $r->headers);
$r->_curlPrep();
$this->assertContains('User-Agent: ACME/1.2.3', $r->raw_headers);
$this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers);
$r = Request::get('http://example.com/')
->withUserAgent('');
$this->assertArrayHasKey('User-Agent', $r->headers);
$r->_curlPrep();
$this->assertContains('User-Agent:', $r->raw_headers);
$this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers);
}
function testAuthSetup()
{
$username = 'nathan';
$password = 'opensesame';
$r = Request::get('http://example.com/')
->authenticateWith($username, $password);
$this->assertEquals($username, $r->username);
$this->assertEquals($password, $r->password);
$this->assertTrue($r->hasBasicAuth());
}
function testDigestAuthSetup()
{
$username = 'nathan';
$password = 'opensesame';
$r = Request::get('http://example.com/')
->authenticateWithDigest($username, $password);
$this->assertEquals($username, $r->username);
$this->assertEquals($password, $r->password);
$this->assertTrue($r->hasDigestAuth());
}
function testJsonResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals("value", $response->body->key);
$this->assertEquals("value", $response->body->object->key);
$this->assertInternalType('array', $response->body->array);
$this->assertEquals(1, $response->body->array[0]);
}
function testXMLResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response(self::SAMPLE_XML_RESPONSE, self::SAMPLE_XML_HEADER, $req);
$sxe = $response->body;
$this->assertEquals("object", gettype($sxe));
$this->assertEquals("SimpleXMLElement", get_class($sxe));
$bools = $sxe->xpath('/stdClass/boolProp');
list( , $bool ) = each($bools);
$this->assertEquals("TRUE", (string) $bool);
$ints = $sxe->xpath('/stdClass/arrayProp/array/k1/myClass/intProp');
list( , $int ) = each($ints);
$this->assertEquals("2", (string) $int);
$strings = $sxe->xpath('/stdClass/stringProp');
list( , $string ) = each($strings);
$this->assertEquals("a string", (string) $string);
}
function testCsvResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::CSV);
$response = new Response(self::SAMPLE_CSV_RESPONSE, self::SAMPLE_CSV_HEADER, $req);
$this->assertEquals("Key1", $response->body[0][0]);
$this->assertEquals("Value1", $response->body[1][0]);
$this->assertInternalType('string', $response->body[2][0]);
$this->assertEquals("40.0", $response->body[2][0]);
}
function testParsingContentTypeCharset()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
// $response = new Response(SAMPLE_JSON_RESPONSE, "", $req);
// // Check default content type of iso-8859-1
$response = new Response(self::SAMPLE_JSON_RESPONSE, "HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8\r\n", $req);
$this->assertInstanceOf('Httpful\Response\Headers', $response->headers);
$this->assertEquals($response->headers['Content-Type'], 'text/plain; charset=utf-8');
$this->assertEquals($response->content_type, 'text/plain');
$this->assertEquals($response->charset, 'utf-8');
}
function testEmptyResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response("", self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals(null, $response->body);
$reqXml = Request::init()->sendsAndExpects(Mime::XML);
$responseXml = new Response("", self::SAMPLE_XML_HEADER, $reqXml);
$this->assertEquals(null, $responseXml->body);
}
function testNoAutoParse()
{
$req = Request::init()->sendsAndExpects(Mime::JSON)->withoutAutoParsing();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertInternalType('string', $response->body);
$req = Request::init()->sendsAndExpects(Mime::JSON)->withAutoParsing();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertInternalType('object', $response->body);
}
function testParseHeaders()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals('application/json', $response->headers['Content-Type']);
}
function testRawHeaders()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertContains('Content-Type: application/json', $response->raw_headers);
}
function testHasErrors()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response('', "HTTP/1.1 100 Continue\r\n", $req);
$this->assertFalse($response->hasErrors());
$response = new Response('', "HTTP/1.1 200 OK\r\n", $req);
$this->assertFalse($response->hasErrors());
$response = new Response('', "HTTP/1.1 300 Multiple Choices\r\n", $req);
$this->assertFalse($response->hasErrors());
$response = new Response('', "HTTP/1.1 400 Bad Request\r\n", $req);
$this->assertTrue($response->hasErrors());
$response = new Response('', "HTTP/1.1 500 Internal Server Error\r\n", $req);
$this->assertTrue($response->hasErrors());
}
function test_parseCode()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$code = $response->_parseCode("HTTP/1.1 406 Not Acceptable\r\n");
$this->assertEquals(406, $code);
}
function testToString()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals(self::SAMPLE_JSON_RESPONSE, (string)$response);
}
function test_parseHeaders()
{
$parse_headers = Response\Headers::fromString(self::SAMPLE_JSON_HEADER);
$this->assertCount(3, $parse_headers);
$this->assertEquals('application/json', $parse_headers['Content-Type']);
$this->assertTrue(isset($parse_headers['Connection']));
}
function testMultiHeaders()
{
$req = Request::init();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_MULTI_HEADER, $req);
$parse_headers = $response->_parseHeaders(self::SAMPLE_MULTI_HEADER);
$this->assertEquals('Value1,Value2', $parse_headers['X-My-Header']);
}
function testDetectContentType()
{
$req = Request::init();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals('application/json', $response->headers['Content-Type']);
}
function testMissingBodyContentType()
{
$body = 'A string';
$request = Request::post(HttpfulTest::TEST_URL, $body)->_curlPrep();
$this->assertEquals($body, $request->serialized_payload);
}
function testParentType()
{
// Parent type
$request = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request);
$this->assertEquals("application/xml", $response->parent_type);
$this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type);
$this->assertTrue($response->is_mime_vendor_specific);
// Make sure we still parsed as if it were plain old XML
$this->assertEquals("Nathan", $response->body->name->__toString());
}
function testMissingContentType()
{
// Parent type
$request = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response('<xml><name>Nathan</name></xml>',
"HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked\r\n", $request);
$this->assertEquals("", $response->content_type);
}
function testCustomMimeRegistering()
{
// Register new mime type handler for "application/vnd.nategood.message+xml"
Httpful::register(self::SAMPLE_VENDOR_TYPE, new DemoMimeHandler());
$this->assertTrue(Httpful::hasParserRegistered(self::SAMPLE_VENDOR_TYPE));
$request = Request::init();
$response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request);
$this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type);
$this->assertEquals('custom parse', $response->body);
}
public function testShorthandMimeDefinition()
{
$r = Request::init()->expects('json');
$this->assertEquals(Mime::JSON, $r->expected_type);
$r = Request::init()->expectsJson();
$this->assertEquals(Mime::JSON, $r->expected_type);
}
public function testOverrideXmlHandler()
{
// Lazy test...
$prev = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertEquals($prev, new \Httpful\Handlers\XmlHandler());
$conf = array('namespace' => 'http://example.com');
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
$new = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertNotEquals($prev, $new);
}
}
class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter {
public function parse($body) {
return 'custom parse';
}
}

View file

@ -0,0 +1,9 @@
<phpunit>
<testsuite name="Httpful">
<directory>.</directory>
</testsuite>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
</logging>
</phpunit>

View file

@ -0,0 +1,515 @@
<?php
/**
* Note : Code is released under the GNU LGPL
*
* Please do not change the header of this file
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details.
*/
/**
* Light PHP wrapper for the OAuth 2.0 protocol.
*
* This client is based on the OAuth2 specification draft v2.15
* http://tools.ietf.org/html/draft-ietf-oauth-v2-15
*
* @author Pierrick Charron <pierrick@webstart.fr>
* @author Anis Berejeb <anis.berejeb@gmail.com>
* @version 1.2-dev
*/
namespace OAuth2;
class Client
{
/**
* Different AUTH method
*/
const AUTH_TYPE_URI = 0;
const AUTH_TYPE_AUTHORIZATION_BASIC = 1;
const AUTH_TYPE_FORM = 2;
/**
* Different Access token type
*/
const ACCESS_TOKEN_URI = 0;
const ACCESS_TOKEN_BEARER = 1;
const ACCESS_TOKEN_OAUTH = 2;
const ACCESS_TOKEN_MAC = 3;
/**
* Different Grant types
*/
const GRANT_TYPE_AUTH_CODE = 'authorization_code';
const GRANT_TYPE_PASSWORD = 'password';
const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
/**
* HTTP Methods
*/
const HTTP_METHOD_GET = 'GET';
const HTTP_METHOD_POST = 'POST';
const HTTP_METHOD_PUT = 'PUT';
const HTTP_METHOD_DELETE = 'DELETE';
const HTTP_METHOD_HEAD = 'HEAD';
const HTTP_METHOD_PATCH = 'PATCH';
/**
* HTTP Form content types
*/
const HTTP_FORM_CONTENT_TYPE_APPLICATION = 0;
const HTTP_FORM_CONTENT_TYPE_MULTIPART = 1;
/**
* Client ID
*
* @var string
*/
protected $client_id = null;
/**
* Client Secret
*
* @var string
*/
protected $client_secret = null;
/**
* Client Authentication method
*
* @var int
*/
protected $client_auth = self::AUTH_TYPE_URI;
/**
* Access Token
*
* @var string
*/
protected $access_token = null;
/**
* Access Token Type
*
* @var int
*/
protected $access_token_type = self::ACCESS_TOKEN_URI;
/**
* Access Token Secret
*
* @var string
*/
protected $access_token_secret = null;
/**
* Access Token crypt algorithm
*
* @var string
*/
protected $access_token_algorithm = null;
/**
* Access Token Parameter name
*
* @var string
*/
protected $access_token_param_name = 'access_token';
/**
* The path to the certificate file to use for https connections
*
* @var string Defaults to .
*/
protected $certificate_file = null;
/**
* cURL options
*
* @var array
*/
protected $curl_options = array();
/**
* Construct
*
* @param string $client_id Client ID
* @param string $client_secret Client Secret
* @param int $client_auth (AUTH_TYPE_URI, AUTH_TYPE_AUTHORIZATION_BASIC, AUTH_TYPE_FORM)
* @param string $certificate_file Indicates if we want to use a certificate file to trust the server. Optional, defaults to null.
* @return void
*/
public function __construct($client_id, $client_secret, $client_auth = self::AUTH_TYPE_URI, $certificate_file = null)
{
if (!extension_loaded('curl')) {
throw new Exception('The PHP exention curl must be installed to use this library.', Exception::CURL_NOT_FOUND);
}
$this->client_id = $client_id;
$this->client_secret = $client_secret;
$this->client_auth = $client_auth;
$this->certificate_file = $certificate_file;
if (!empty($this->certificate_file) && !is_file($this->certificate_file)) {
throw new InvalidArgumentException('The certificate file was not found', InvalidArgumentException::CERTIFICATE_NOT_FOUND);
}
}
/**
* Get the client Id
*
* @return string Client ID
*/
public function getClientId()
{
return $this->client_id;
}
/**
* Get the client Secret
*
* @return string Client Secret
*/
public function getClientSecret()
{
return $this->client_secret;
}
/**
* getAuthenticationUrl
*
* @param string $auth_endpoint Url of the authentication endpoint
* @param string $redirect_uri Redirection URI
* @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => ''))
* @return string URL used for authentication
*/
public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = array())
{
$parameters = array_merge(array(
'response_type' => 'code',
'client_id' => $this->client_id,
'redirect_uri' => $redirect_uri
), $extra_parameters);
return $auth_endpoint . '?' . http_build_query($parameters, null, '&');
}
/**
* getAccessToken
*
* @param string $token_endpoint Url of the token endpoint
* @param int $grant_type Grant Type ('authorization_code', 'password', 'client_credentials', 'refresh_token', or a custom code (@see GrantType Classes)
* @param array $parameters Array sent to the server (depend on which grant type you're using)
* @return array Array of parameters required by the grant_type (CF SPEC)
*/
public function getAccessToken($token_endpoint, $grant_type, array $parameters)
{
if (!$grant_type) {
throw new InvalidArgumentException('The grant_type is mandatory.', InvalidArgumentException::INVALID_GRANT_TYPE);
}
$grantTypeClassName = $this->convertToCamelCase($grant_type);
$grantTypeClass = __NAMESPACE__ . '\\GrantType\\' . $grantTypeClassName;
if (!class_exists($grantTypeClass)) {
throw new InvalidArgumentException('Unknown grant type \'' . $grant_type . '\'', InvalidArgumentException::INVALID_GRANT_TYPE);
}
$grantTypeObject = new $grantTypeClass();
$grantTypeObject->validateParameters($parameters);
if (!defined($grantTypeClass . '::GRANT_TYPE')) {
throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR);
}
$parameters['grant_type'] = $grantTypeClass::GRANT_TYPE;
$http_headers = array();
switch ($this->client_auth) {
case self::AUTH_TYPE_URI:
case self::AUTH_TYPE_FORM:
$parameters['client_id'] = $this->client_id;
$parameters['client_secret'] = $this->client_secret;
break;
case self::AUTH_TYPE_AUTHORIZATION_BASIC:
$parameters['client_id'] = $this->client_id;
$http_headers['Authorization'] = 'Basic ' . base64_encode($this->client_id . ':' . $this->client_secret);
break;
default:
throw new Exception('Unknown client auth type.', Exception::INVALID_CLIENT_AUTHENTICATION_TYPE);
break;
}
return $this->executeRequest($token_endpoint, $parameters, self::HTTP_METHOD_POST, $http_headers, self::HTTP_FORM_CONTENT_TYPE_APPLICATION);
}
/**
* setToken
*
* @param string $token Set the access token
* @return void
*/
public function setAccessToken($token)
{
$this->access_token = $token;
}
/**
* Set the client authentication type
*
* @param string $client_auth (AUTH_TYPE_URI, AUTH_TYPE_AUTHORIZATION_BASIC, AUTH_TYPE_FORM)
* @return void
*/
public function setClientAuthType($client_auth)
{
$this->client_auth = $client_auth;
}
/**
* Set an option for the curl transfer
*
* @param int $option The CURLOPT_XXX option to set
* @param mixed $value The value to be set on option
* @return void
*/
public function setCurlOption($option, $value)
{
$this->curl_options[$option] = $value;
}
/**
* Set multiple options for a cURL transfer
*
* @param array $options An array specifying which options to set and their values
* @return void
*/
public function setCurlOptions($options)
{
$this->curl_options = array_merge($this->curl_options, $options);
}
/**
* Set the access token type
*
* @param int $type Access token type (ACCESS_TOKEN_BEARER, ACCESS_TOKEN_MAC, ACCESS_TOKEN_URI)
* @param string $secret The secret key used to encrypt the MAC header
* @param string $algorithm Algorithm used to encrypt the signature
* @return void
*/
public function setAccessTokenType($type, $secret = null, $algorithm = null)
{
$this->access_token_type = $type;
$this->access_token_secret = $secret;
$this->access_token_algorithm = $algorithm;
}
/**
* Fetch a protected ressource
*
* @param string $protected_ressource_url Protected resource URL
* @param array $parameters Array of parameters
* @param string $http_method HTTP Method to use (POST, PUT, GET, HEAD, DELETE)
* @param array $http_headers HTTP headers
* @param int $form_content_type HTTP form content type to use
* @return array
*/
public function fetch($protected_resource_url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = array(), $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
{
if ($this->access_token) {
switch ($this->access_token_type) {
case self::ACCESS_TOKEN_URI:
if (is_array($parameters)) {
$parameters[$this->access_token_param_name] = $this->access_token;
} else {
throw new InvalidArgumentException(
'You need to give parameters as array if you want to give the token within the URI.',
InvalidArgumentException::REQUIRE_PARAMS_AS_ARRAY
);
}
break;
case self::ACCESS_TOKEN_BEARER:
$http_headers['Authorization'] = 'Bearer ' . $this->access_token;
break;
case self::ACCESS_TOKEN_OAUTH:
$http_headers['Authorization'] = 'OAuth ' . $this->access_token;
break;
case self::ACCESS_TOKEN_MAC:
$http_headers['Authorization'] = 'MAC ' . $this->generateMACSignature($protected_resource_url, $parameters, $http_method);
break;
default:
throw new Exception('Unknown access token type.', Exception::INVALID_ACCESS_TOKEN_TYPE);
break;
}
}
return $this->executeRequest($protected_resource_url, $parameters, $http_method, $http_headers, $form_content_type);
}
/**
* Generate the MAC signature
*
* @param string $url Called URL
* @param array $parameters Parameters
* @param string $http_method Http Method
* @return string
*/
private function generateMACSignature($url, $parameters, $http_method)
{
$timestamp = time();
$nonce = uniqid();
$parsed_url = parse_url($url);
if (!isset($parsed_url['port']))
{
$parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80;
}
if ($http_method == self::HTTP_METHOD_GET) {
if (is_array($parameters)) {
$parsed_url['path'] .= '?' . http_build_query($parameters, null, '&');
} elseif ($parameters) {
$parsed_url['path'] .= '?' . $parameters;
}
}
$signature = base64_encode(hash_hmac($this->access_token_algorithm,
$timestamp . "\n"
. $nonce . "\n"
. $http_method . "\n"
. $parsed_url['path'] . "\n"
. $parsed_url['host'] . "\n"
. $parsed_url['port'] . "\n\n"
, $this->access_token_secret, true));
return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"';
}
/**
* Execute a request (with curl)
*
* @param string $url URL
* @param mixed $parameters Array of parameters
* @param string $http_method HTTP Method
* @param array $http_headers HTTP Headers
* @param int $form_content_type HTTP form content type to use
* @return array
*/
private function executeRequest($url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
{
$curl_options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CUSTOMREQUEST => $http_method
);
switch($http_method) {
case self::HTTP_METHOD_POST:
$curl_options[CURLOPT_POST] = true;
/* No break */
case self::HTTP_METHOD_PUT:
case self::HTTP_METHOD_PATCH:
/**
* Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data,
* while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
* http://php.net/manual/en/function.curl-setopt.php
*/
if(is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) {
$parameters = http_build_query($parameters, null, '&');
}
$curl_options[CURLOPT_POSTFIELDS] = $parameters;
break;
case self::HTTP_METHOD_HEAD:
$curl_options[CURLOPT_NOBODY] = true;
/* No break */
case self::HTTP_METHOD_DELETE:
case self::HTTP_METHOD_GET:
if (is_array($parameters)) {
$url .= '?' . http_build_query($parameters, null, '&');
} elseif ($parameters) {
$url .= '?' . $parameters;
}
break;
default:
break;
}
$curl_options[CURLOPT_URL] = $url;
if (is_array($http_headers)) {
$header = array();
foreach($http_headers as $key => $parsed_urlvalue) {
$header[] = "$key: $parsed_urlvalue";
}
$curl_options[CURLOPT_HTTPHEADER] = $header;
}
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
// https handling
if (!empty($this->certificate_file)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, $this->certificate_file);
} else {
// bypass ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
if (!empty($this->curl_options)) {
curl_setopt_array($ch, $this->curl_options);
}
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ($curl_error = curl_error($ch)) {
throw new Exception($curl_error, Exception::CURL_ERROR);
} else {
$json_decode = json_decode($result, true);
}
curl_close($ch);
return array(
'result' => (null === $json_decode) ? $result : $json_decode,
'code' => $http_code,
'content_type' => $content_type
);
}
/**
* Set the name of the parameter that carry the access token
*
* @param string $name Token parameter name
* @return void
*/
public function setAccessTokenParamName($name)
{
$this->access_token_param_name = $name;
}
/**
* Converts the class name to camel case
*
* @param mixed $grant_type the grant type
* @return string
*/
private function convertToCamelCase($grant_type)
{
$parts = explode('_', $grant_type);
array_walk($parts, function(&$item) { $item = ucfirst($item);});
return implode('', $parts);
}
}
class Exception extends \Exception
{
const CURL_NOT_FOUND = 0x01;
const CURL_ERROR = 0x02;
const GRANT_TYPE_ERROR = 0x03;
const INVALID_CLIENT_AUTHENTICATION_TYPE = 0x04;
const INVALID_ACCESS_TOKEN_TYPE = 0x05;
}
class InvalidArgumentException extends \InvalidArgumentException
{
const INVALID_GRANT_TYPE = 0x01;
const CERTIFICATE_NOT_FOUND = 0x02;
const REQUIRE_PARAMS_AS_ARRAY = 0x03;
const MISSING_PARAMETER = 0x04;
}

View file

@ -0,0 +1,41 @@
<?php
namespace OAuth2\GrantType;
use OAuth2\InvalidArgumentException;
/**
* Authorization code Grant Type Validator
*/
class AuthorizationCode implements IGrantType
{
/**
* Defines the Grant Type
*
* @var string Defaults to 'authorization_code'.
*/
const GRANT_TYPE = 'authorization_code';
/**
* Adds a specific Handling of the parameters
*
* @return array of Specific parameters to be sent.
* @param mixed $parameters the parameters array (passed by reference)
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['code']))
{
throw new InvalidArgumentException(
'The \'code\' parameter must be defined for the Authorization Code grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
elseif (!isset($parameters['redirect_uri']))
{
throw new InvalidArgumentException(
'The \'redirect_uri\' parameter must be defined for the Authorization Code grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace OAuth2\GrantType;
/**
* Client Credentials Parameters
*/
class ClientCredentials implements IGrantType
{
/**
* Defines the Grant Type
*
* @var string Defaults to 'client_credentials'.
*/
const GRANT_TYPE = 'client_credentials';
/**
* Adds a specific Handling of the parameters
*
* @return array of Specific parameters to be sent.
* @param mixed $parameters the parameters array (passed by reference)
*/
public function validateParameters(&$parameters)
{
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace OAuth2\GrantType;
/**
* Specific GrantType Interface
*/
interface IGrantType
{
/**
* Adds a specific Handling of the parameters
*
* @return array of Specific parameters to be sent.
* @param mixed $parameters the parameters array (passed by reference)
*/
public function validateParameters(&$parameters);
}

View file

@ -0,0 +1,41 @@
<?php
namespace OAuth2\GrantType;
use OAuth2\InvalidArgumentException;
/**
* Password Parameters
*/
class Password implements IGrantType
{
/**
* Defines the Grant Type
*
* @var string Defaults to 'password'.
*/
const GRANT_TYPE = 'password';
/**
* Adds a specific Handling of the parameters
*
* @return array of Specific parameters to be sent.
* @param mixed $parameters the parameters array (passed by reference)
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['username']))
{
throw new InvalidArgumentException(
'The \'username\' parameter must be defined for the Password grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
elseif (!isset($parameters['password']))
{
throw new InvalidArgumentException(
'The \'password\' parameter must be defined for the Password grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace OAuth2\GrantType;
use OAuth2\InvalidArgumentException;
/**
* Refresh Token Parameters
*/
class RefreshToken implements IGrantType
{
/**
* Defines the Grant Type
*
* @var string Defaults to 'refresh_token'.
*/
const GRANT_TYPE = 'refresh_token';
/**
* Adds a specific Handling of the parameters
*
* @return array of Specific parameters to be sent.
* @param mixed $parameters the parameters array (passed by reference)
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['refresh_token']))
{
throw new InvalidArgumentException(
'The \'refresh_token\' parameter must be defined for the refresh token grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
}
}

View file

@ -0,0 +1,117 @@
___________________________________
Light PHP wrapper for the OAuth 2.0
___________________________________
AUTHOR & CONTACT
================
Charron Pierrick
- pierrick@webstart.fr
Berejeb Anis
- anis.berejeb@gmail.com
DOCUMENTATION & DOWNLOAD
========================
Latest version is available on github at :
- https://github.com/adoy/PHP-OAuth2
Documentation can be found on :
- https://github.com/adoy/PHP-OAuth2
LICENSE
=======
This Code is released under the GNU LGPL
Please do not change the header of the file(s).
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
How can I use it ?
==================
require('client.php');
require('GrantType/IGrantType.php');
require('GrantType/AuthorizationCode.php');
const CLIENT_ID = 'your client id';
const CLIENT_SECRET = 'your client secret';
const REDIRECT_URI = 'http://url/of/this.php';
const AUTHORIZATION_ENDPOINT = 'https://graph.facebook.com/oauth/authorize';
const TOKEN_ENDPOINT = 'https://graph.facebook.com/oauth/access_token';
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code']))
{
$auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
header('Location: ' . $auth_url);
die('Redirect');
}
else
{
$params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
parse_str($response['result'], $info);
$client->setAccessToken($info['access_token']);
$response = $client->fetch('https://graph.facebook.com/me');
var_dump($response, $response['result']);
}
How can I add a new Grant Type ?
================================
Simply write a new class in the namespace OAuth2\GrantType. You can place the class file under GrantType.
Here is an example :
namespace OAuth2\GrantType;
/**
* MyCustomGrantType Grant Type
*/
class MyCustomGrantType implements IGrantType
{
/**
* Defines the Grant Type
*
* @var string Defaults to 'my_custom_grant_type'.
*/
const GRANT_TYPE = 'my_custom_grant_type';
/**
* Adds a specific Handling of the parameters
*
* @return array of Specific parameters to be sent.
* @param mixed $parameters the parameters array (passed by reference)
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['first_mandatory_parameter']))
{
throw new \Exception('The \'first_mandatory_parameter\' parameter must be defined for the Password grant type');
}
elseif (!isset($parameters['second_mandatory_parameter']))
{
throw new \Exception('The \'seconde_mandatory_parameter\' parameter must be defined for the Password grant type');
}
}
}
call the OAuth client getAccessToken with the grantType you defined in the GRANT_TYPE constant, As following :
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'my_custom_grant_type', $params);

View file

@ -0,0 +1,19 @@
{
"name": "adoy/oauth2",
"description": "Light PHP wrapper for the OAuth 2.0 protocol (based on OAuth 2.0 Authorization Protocol draft-ietf-oauth-v2-15)",
"authors": [
{
"name": "Charron Pierrick",
"email": "pierrick@webstart.fr"
},
{
"name": "Berejeb Anis",
"email": "anis.berejeb@gmail.com"
}
],
"autoload": {
"classmap": [
"../"
]
}
}

View file

@ -34,8 +34,8 @@
Route::get('artists', 'ArtistsController@getIndex');
Route::get('playlists', 'PlaylistsController@getIndex');
Route::get('/login', function() { return View::make('auth.login'); });
Route::get('/register', function() { return View::make('auth.register'); });
Route::get('/login', 'AuthController@getLogin');
Route::get('/auth/oauth', 'AuthController@getOAuth');
Route::get('/about', function() { return View::make('pages.about'); });
Route::get('/faq', function() { return View::make('pages.faq'); });
@ -114,7 +114,6 @@
});
Route::group(['before' => 'csrf'], function(){
Route::post('/auth/login', 'Api\Web\AuthController@postLogin');
Route::post('/auth/logout', 'Api\Web\AuthController@postLogout');
});
});

View file

@ -20,6 +20,7 @@
app_path().'/models',
app_path().'/library',
app_path().'/database/seeds',
app_path().'/library/Poniverse',
));

View file

@ -74,6 +74,8 @@
<li class="dropdown" ng-repeat="playlist in playlists" ng-cloak ng-class="{selected: stateIncludes('content.playlist') && $state.params.id == playlist.id}">
<a href="{{Helpers::angular('playlist.url')}}" ng-bind="playlist.title"></a>
</li>
@else
<li><a href="/login" target="_self">Login <i class="icon-user"></i></a></li>
@endif
</ul>
<ui-view class="site-content">

2
vendor/autoload.php vendored
View file

@ -4,4 +4,4 @@
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225::getLoader();
return ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224::getLoader();

View file

@ -18,6 +18,7 @@ return array(
'Api\\Web\\CommentsController' => $baseDir . '/app/controllers/Api/Web/CommentsController.php',
'Api\\Web\\DashboardController' => $baseDir . '/app/controllers/Api/Web/DashboardController.php',
'Api\\Web\\FavouritesController' => $baseDir . '/app/controllers/Api/Web/FavouritesController.php',
'Api\\Web\\FollowController' => $baseDir . '/app/controllers/Api/Web/FollowController.php',
'Api\\Web\\ImagesController' => $baseDir . '/app/controllers/Api/Web/ImagesController.php',
'Api\\Web\\PlaylistsController' => $baseDir . '/app/controllers/Api/Web/PlaylistsController.php',
'Api\\Web\\ProfilerController' => $baseDir . '/app/controllers/Api/Web/ProfilerController.php',
@ -121,6 +122,7 @@ return array(
'Assetic\\Util\\TraversableString' => $vendorDir . '/kriswallsmith/assetic/src/Assetic/Util/TraversableString.php',
'Assetic\\Util\\VarUtils' => $vendorDir . '/kriswallsmith/assetic/src/Assetic/Util/VarUtils.php',
'Assetic\\ValueSupplierInterface' => $vendorDir . '/kriswallsmith/assetic/src/Assetic/ValueSupplierInterface.php',
'AuthController' => $baseDir . '/app/controllers/AuthController.php',
'Carbon\\Carbon' => $vendorDir . '/nesbot/carbon/Carbon/Carbon.php',
'Carbon\\Tests\\TestFixture' => $vendorDir . '/nesbot/carbon/Carbon/Tests/TestFixture.php',
'ClassPreloader\\Application' => $vendorDir . '/classpreloader/classpreloader/src/ClassPreloader/Application.php',
@ -147,6 +149,7 @@ return array(
'Commands\\EditTrackCommand' => $baseDir . '/app/models/Commands/EditTrackCommand.php',
'Commands\\SaveAccountSettingsCommand' => $baseDir . '/app/models/Commands/SaveAccountSettingsCommand.php',
'Commands\\ToggleFavouriteCommand' => $baseDir . '/app/models/Commands/ToggleFavouriteCommand.php',
'Commands\\ToggleFollowingCommand' => $baseDir . '/app/models/Commands/ToggleFollowingCommand.php',
'Commands\\UploadTrackCommand' => $baseDir . '/app/models/Commands/UploadTrackCommand.php',
'ContentController' => $baseDir . '/app/controllers/ContentController.php',
'CreateAlbums' => $baseDir . '/app/database/migrations/2013_07_28_060804_create_albums.php',
@ -428,6 +431,7 @@ return array(
'Entities\\Album' => $baseDir . '/app/models/Entities/Album.php',
'Entities\\Comment' => $baseDir . '/app/models/Entities/Comment.php',
'Entities\\Favourite' => $baseDir . '/app/models/Entities/Favourite.php',
'Entities\\Follower' => $baseDir . '/app/models/Entities/Follower.php',
'Entities\\Genre' => $baseDir . '/app/models/Entities/Genre.php',
'Entities\\Image' => $baseDir . '/app/models/Entities/Image.php',
'Entities\\License' => $baseDir . '/app/models/Entities/License.php',
@ -879,6 +883,7 @@ return array(
'Monolog\\Processor\\UidProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/UidProcessor.php',
'Monolog\\Processor\\WebProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/WebProcessor.php',
'Normalizer' => $vendorDir . '/patchwork/utf8/class/Normalizer.php',
'Oauth' => $baseDir . '/app/database/migrations/2013_09_01_025031_oauth.php',
'OutputProvider' => $vendorDir . '/codescale/ffmpeg-php/provider/OutputProvider.php',
'PHPParser_Autoloader' => $vendorDir . '/nikic/php-parser/lib/PHPParser/Autoloader.php',
'PHPParser_Builder' => $vendorDir . '/nikic/php-parser/lib/PHPParser/Builder.php',
@ -1863,6 +1868,7 @@ return array(
'TestCase' => $baseDir . '/app/tests/TestCase.php',
'TracksController' => $baseDir . '/app/controllers/TracksController.php',
'Traits\\SlugTrait' => $baseDir . '/app/models/Traits/SlugTrait.php',
'UploaderController' => $baseDir . '/app/controllers/UploaderController.php',
'UsersController' => $baseDir . '/app/controllers/UsersController.php',
'Whoops\\Exception\\ErrorException' => $vendorDir . '/filp/whoops/src/Whoops/Exception/ErrorException.php',
'Whoops\\Exception\\Frame' => $vendorDir . '/filp/whoops/src/Whoops/Exception/Frame.php',

View file

@ -2,7 +2,7 @@
// autoload_real.php generated by Composer
class ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225
class ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224
{
private static $loader;
@ -19,9 +19,9 @@ class ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224', 'loadClassLoader'));
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);