Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
Steven Maguire committed Mar 21, 2015
0 parents commit a644957
Show file tree
Hide file tree
Showing 8 changed files with 371 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
@@ -0,0 +1,4 @@
/vendor
composer.phar
composer.lock
.DS_Store
11 changes: 11 additions & 0 deletions .travis.yml
@@ -0,0 +1,11 @@
language: php

php:
- 5.4
- 5.5
- 5.6
- hhvm

before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Steven Maguire

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.
81 changes: 81 additions & 0 deletions README.md
@@ -0,0 +1,81 @@
# Uber Provider for OAuth 2.0 Client

[![Build Status](https://travis-ci.org/stevenmaguire/oauth2-uber.svg?branch=master)](https://travis-ci.org/stevenmaguire/oauth2-uber)
[![Latest Stable Version](https://poser.pugx.org/stevenmaguire/oauth2-uber/v/stable.svg)](https://packagist.org/packages/stevenmaguire/oauth2-uber)

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

## Installation

To install, use composer:

```
composer require stevenmaguire/oauth2-uber
```

## Usage

Usage is the same as The League's OAuth client, using `\Stevenmaguire\OAuth2\Client\Provider\Uber` as the provider.

### Authorization Code Flow

```php
$provider = new Stevenmaguire\OAuth2\Client\Provider\Uber([
'clientId' => '{uber-client-id}',
'clientSecret' => '{uber-client-secret}',
'redirectUri' => 'https://example.com/callback-url'
]);

if (!isset($_GET['code'])) {

// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->state;
header('Location: '.$authUrl);
exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

unset($_SESSION['oauth2state']);
exit('Invalid state');

} else {

// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);

// Optional: Now you have a token you can look up a users profile data
try {

// We got an access token, let's now get the user's details
$userDetails = $provider->getUserDetails($token);

// Use these details to create a new profile
printf('Hello %s!', $userDetails->firstName);

} catch (Exception $e) {

// Failed to get user details
exit('Oh dear...');
}

// Use this to interact with an API on the users behalf
echo $token->accessToken;
}
```

### Refreshing a Token

```php
$provider = new Stevenmaguire\OAuth2\Client\Provider\Uber([
'clientId' => '{uber-client-id}',
'clientSecret' => '{uber-client-secret}',
'redirectUri' => 'https://example.com/callback-url'
]);

$grant = new \League\OAuth2\Client\Grant\RefreshToken();
$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);
```
39 changes: 39 additions & 0 deletions composer.json
@@ -0,0 +1,39 @@
{
"name": "stevenmaguire/oauth2-uber",
"description": "Uber OAuth 2.0 Client Provider for The PHP League OAuth2-Client",
"license": "MIT",
"authors": [
{
"name": "Steven Maguire",
"email": "stevenmaguire@gmail.com",
"homepage": "https://github.com/stevenmaguire"
}
],
"version": "0.1.1",
"keywords": [
"oauth",
"oauth2",
"client",
"authorization",
"authorisation",
"uber"
],
"require": {
"php": ">=5.4.0",
"league/oauth2-client": ">=0.10.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0",
"mockery/mockery": "~0.9"
},
"autoload": {
"psr-4": {
"Stevenmaguire\\OAuth2\\Client\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Stevenmaguire\\OAuth2\\Client\\Test\\": "tests/src/"
}
}
}
18 changes: 18 additions & 0 deletions phpunit.xml
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
88 changes: 88 additions & 0 deletions src/Provider/Uber.php
@@ -0,0 +1,88 @@
<?php namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Entity\User;
use League\OAuth2\Client\Token\AccessToken;

class Uber extends AbstractProvider
{
public $scopes = [];
public $responseType = 'json';
public $authorizationHeader = 'Bearer';
public $version = 'v1';

/**
* Get the URL that this provider uses to begin authorization.
*
* @return string
*/
public function urlAuthorize()
{
return 'https://login.uber.com/oauth/authorize';
}

/**
* Get the URL that this provider users to request an access token.
*
* @return string
*/
public function urlAccessToken()
{
return 'https://login.uber.com/oauth/token';
}

/**
* Get the URL that this provider uses to request user details.
*
* Since this URL is typically an authorized route, most providers will require you to pass the access_token as
* a parameter to the request. For example, the google url is:
*
* 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$token
*
* @param AccessToken $token
* @return string
*/
public function urlUserDetails(AccessToken $token)
{
return 'https://api.uber.com/'.$this->version.'/me';
}

/**
* Given an object response from the server, process the user details into a format expected by the user
* of the client.
*
* @param object $response
* @param AccessToken $token
* @return mixed
*/
public function userDetails($response, AccessToken $token)
{
$user = new User();

$user->exchangeArray([
'uid' => $response->uuid,
'name' => $response->first_name . ' ' . $response->last_name,
'firstname' => $response->first_name,
'lastname' => $response->last_name,
'email' => $response->email,
'imageUrl' => $response->picture,
]);

return $user;
}

public function userUid($response, AccessToken $token)
{
return $response->uuid;
}

public function userEmail($response, AccessToken $token)
{
return $response->email;
}

public function userScreenName($response, AccessToken $token)
{
return null;
}
}
109 changes: 109 additions & 0 deletions tests/src/Provider/UberTest.php
@@ -0,0 +1,109 @@
<?php namespace Stevenmaguire\OAuth2\Client\Test\Provider;

use Mockery as m;

class UberTest extends \PHPUnit_Framework_TestCase
{
protected $provider;

protected function setUp()
{
$this->provider = new \Stevenmaguire\OAuth2\Client\Provider\Uber([
'clientId' => 'mock_client_id',
'clientSecret' => 'mock_secret',
'redirectUri' => 'none',
]);
}

public function tearDown()
{
m::close();
parent::tearDown();
}

public function testAuthorizationUrl()
{
$url = $this->provider->getAuthorizationUrl();
$uri = parse_url($url);
parse_str($uri['query'], $query);

$this->assertArrayHasKey('client_id', $query);
$this->assertArrayHasKey('redirect_uri', $query);
$this->assertArrayHasKey('state', $query);
$this->assertArrayHasKey('scope', $query);
$this->assertArrayHasKey('response_type', $query);
$this->assertArrayHasKey('approval_prompt', $query);
$this->assertNotNull($this->provider->state);
}

public function testUrlAuthorize()
{
$url = $this->provider->urlAuthorize();
$uri = parse_url($url);

$this->assertEquals('/oauth/authorize', $uri['path']);
}

public function testUrlAccessToken()
{
$url = $this->provider->urlAccessToken();
$uri = parse_url($url);

$this->assertEquals('/oauth/token', $uri['path']);
}

public function testGetAccessToken()
{
$response = m::mock('Guzzle\Http\Message\Response');
$response->shouldReceive('getBody')->times(1)->andReturn('{"access_token": "mock_access_token", "expires": 3600, "refresh_token": "mock_refresh_token", "uid": 1}');

$client = m::mock('Guzzle\Service\Client');
$client->shouldReceive('setBaseUrl')->times(1);
$client->shouldReceive('post->send')->times(1)->andReturn($response);
$this->provider->setHttpClient($client);

$token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);

$this->assertEquals('mock_access_token', $token->accessToken);
$this->assertLessThanOrEqual(time() + 3600, $token->expires);
$this->assertGreaterThanOrEqual(time(), $token->expires);
$this->assertEquals('mock_refresh_token', $token->refreshToken);
$this->assertEquals('1', $token->uid);
}

public function testScopes()
{
$this->assertEmpty($this->provider->getScopes());
}

public function testAuthorizationHeader()
{
$this->assertEquals('Bearer', $this->provider->authorizationHeader);
}

public function testUserData()
{
$postResponse = m::mock('Guzzle\Http\Message\Response');
$postResponse->shouldReceive('getBody')->times(1)->andReturn('{"access_token": "mock_access_token","token_type": "Bearer","expires_in": "mock_expires","refresh_token": "mock_refresh_token","scope": "scope1 scope2"}');

$getResponse = m::mock('Guzzle\Http\Message\Response');
$getResponse->shouldReceive('getBody')->times(4)->andReturn('{"first_name": "mock_first_name","last_name": "mock_last_name","email": "mock_email","picture": "mock_image_url","promo_code": "teypo","uuid": "mock_id"}');

$client = m::mock('Guzzle\Service\Client');
$client->shouldReceive('setBaseUrl')->times(5);
$client->shouldReceive('setDefaultOption')->times(4);
$client->shouldReceive('post->send')->times(1)->andReturn($postResponse);
$client->shouldReceive('get->send')->times(4)->andReturn($getResponse);
$this->provider->setHttpClient($client);

$token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
$user = $this->provider->getUserDetails($token);

$this->assertEquals('mock_id', $this->provider->getUserUid($token));
$this->assertNull($this->provider->getUserScreenName($token));
$this->assertEquals('mock_email', $this->provider->getUserEmail($token));
$this->assertEquals('mock_email', $user->email);
$this->assertEquals('mock_image_url', $user->imageUrl);
}
}

0 comments on commit a644957

Please sign in to comment.