Merge branch 'v4.0.0-relational-example' of github.com:thephpleague/oauth2-server into v4.0.0-relational-example

This commit is contained in:
Alex Bilbie 2014-07-28 13:54:46 +01:00
commit 0810be9ce4
24 changed files with 2420 additions and 50 deletions

5
.gitignore vendored
View File

@ -7,5 +7,6 @@
/examples/nosql/vendor
/examples/nosql/config/oauth2.sqlite3
/examples/relational/composer.lock
/tests/functional/tests/_log
tests/_output/*
/tests/codecept/tests/_log
tests/_output/*
oauth2-server.paw

View File

@ -73,7 +73,12 @@ class AccessTokenStorage extends Adapter implements AccessTokenInterface
*/
public function create($token, $expireTime, $sessionId)
{
die(var_dump(__METHOD__, func_get_args()));
Capsule::table('oauth_access_tokens')
->insert([
'access_token' => $token,
'session_id' => $sessionId,
'expire_time' => $expireTime
]);
}
/**

View File

@ -24,13 +24,14 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
if (count($result) === 1) {
$token = new AuthCodeEntity($this->server);
$token->setId($result[0]['auth_code']);
$token->setRedirectUri($result[0]['client_redirect_uri']);
return $token;
}
return null;
}
public function create($token, $$expireTime, $sessionId)
public function create($token, $expireTime, $sessionId, $redirectUri)
{
Capsule::table('oauth_auth_codes')
->insert([
@ -46,7 +47,25 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
*/
public function getScopes(AuthCodeEntity $token)
{
die(var_dump(__METHOD__, func_get_args()));
$result = Capsule::table('oauth_auth_code_scopes')
->select(['oauth_scopes.id', 'oauth_scopes.description'])
->join('oauth_scopes', 'oauth_auth_code_scopes.scope', '=', 'oauth_scopes.id')
->where('auth_code', $token->getId())
->get();
$response = [];
if (count($result) > 0) {
foreach ($result as $row) {
$scope = (new ScopeEntity($this->server))->hydrate([
'id' => $row['id'],
'description' => $row['description']
]);
$response[] = $scope;
}
}
return $response;
}
/**
@ -55,10 +74,10 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
public function associateScope(AuthCodeEntity $token, ScopeEntity $scope)
{
Capsule::table('oauth_auth_code_scopes')
->insert([
'auth_code' => $token->getToken(),
'scope' => $scope->getId()
]);
->insert([
'auth_code' => $token->getId(),
'scope' => $scope->getId()
]);
}
/**
@ -66,6 +85,8 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
*/
public function delete(AuthCodeEntity $token)
{
die(var_dump(__METHOD__, func_get_args()));
Capsule::table('oauth_auth_codes')
->where('auth_code', $token->getId())
->delete();
}
}

View File

@ -29,11 +29,10 @@ class SessionStorage extends Adapter implements SessionInterface
$result = Capsule::table('oauth_sessions')
->select(['oauth_sessions.id', 'oauth_sessions.owner_type', 'oauth_sessions.owner_id', 'oauth_sessions.client_id', 'oauth_sessions.client_redirect_uri'])
->join('oauth_access_tokens', 'oauth_access_tokens.session_id', '=', 'oauth_sessions.id')
->where('oauth_access_tokens.access_token', $accessToken->getToken())
->where('oauth_access_tokens.access_token', $accessToken->getId())
->get();
if (count($result) === 1) {
// die(var_dump($result));
$session = new SessionEntity($this->server);
$session->setId($result[0]['id']);
$session->setOwner($result[0]['owner_type'], $result[0]['owner_id']);
@ -49,7 +48,21 @@ class SessionStorage extends Adapter implements SessionInterface
*/
public function getByAuthCode(AuthCodeEntity $authCode)
{
die(var_dump(__METHOD__, func_get_args()));
$result = Capsule::table('oauth_sessions')
->select(['oauth_sessions.id', 'oauth_sessions.owner_type', 'oauth_sessions.owner_id', 'oauth_sessions.client_id', 'oauth_sessions.client_redirect_uri'])
->join('oauth_auth_codes', 'oauth_auth_codes.session_id', '=', 'oauth_sessions.id')
->where('oauth_auth_codes.auth_code', $authCode->getId())
->get();
if (count($result) === 1) {
$session = new SessionEntity($this->server);
$session->setId($result[0]['id']);
$session->setOwner($result[0]['owner_type'], $result[0]['owner_id']);
return $session;
}
return null;
}
/**
@ -67,9 +80,10 @@ class SessionStorage extends Adapter implements SessionInterface
$scopes = [];
foreach ($result as $scope) {
$scopes[] = (new ScopeEntity($this->server))
->setId($scope['id'])
->setDescription($scope['description']);
$scopes[] = (new ScopeEntity($this->server))->hydrate([
'id' => $scope['id'],
'description' => $scope['description']
]);
}
return $scopes;
@ -95,6 +109,10 @@ class SessionStorage extends Adapter implements SessionInterface
*/
public function associateScope(SessionEntity $session, ScopeEntity $scope)
{
die(var_dump(__CLASS__.'::'.__METHOD__, func_get_args()));
Capsule::table('oauth_session_scopes')
->insert([
'session_id' => $session->getId(),
'scope' => $scope->getId()
]);
}
}

View File

@ -33,20 +33,25 @@ $server->addGrantType($authCodeGrant);
$request = (new Request)->createFromGlobals();
$server->setRequest($request);
// GET /authorize
$router->get('/authorize', function (Request $request) use ($server) {
// First ensure the parameters in the query string are correct
try {
$authParams = $server->getGrantType('authorization_code')->checkAuthorizeParams();
} catch (\Exception $e) {
echo json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
]);
exit;
$authParams = $server->getGrantType('authorization_code')->checkAuthorizeParams();
} catch (\Exception $e) {
return new Response(
json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
]),
$e->httpStatusCode,
$e->getHttpHeaders()
);
}
// Normally at this point you would show the user a sign-in screen and ask them to authorize the requested scopes
@ -68,18 +73,24 @@ $router->get('/authorize', function (Request $request) use ($server) {
return $response;
});
// /access_token
$router->post('/access_token', function (Request $request) use ($server) {
try {
$response = $server->getGrantType('authorization_code')->completeFlow();
} catch (\Exception $e) {
echo json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
]);
exit;
$response = $server->issueAccessToken();
return new Response(json_encode($response), 200);
} catch (\Exception $e) {
return new Response(
json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
]),
$e->httpStatusCode,
$e->getHttpHeaders()
);
}
});
@ -87,5 +98,3 @@ $router->post('/access_token', function (Request $request) use ($server) {
$dispatcher = $router->getDispatcher();
$response = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo());
$response->send();
// var_dump(Capsule::getQueryLog());

View File

@ -181,6 +181,7 @@ Capsule::schema()->create('oauth_auth_codes', function ($table) {
$table->string('auth_code')->primary();
$table->integer('session_id');
$table->integer('expire_time');
$table->string('client_redirect_uri');
$table->foreign('session_id')->references('id')->on('oauth_sessions')->onDelete('cascade');
});

View File

@ -0,0 +1,64 @@
<?php
namespace OAuth2Server\RelationalExample;
use \Orno\Http\Request;
use \Orno\Http\Response;
use \Orno\Http\JsonResponse;
use \Orno\Http\Exception\MethodNotAllowedException;
use Illuminate\Database\Capsule\Manager as Capsule;
// use \League\OAuth2\Server\Exception;
use \RelationalExample\Storage;
use \RelationalExample\Model;
include __DIR__.'/vendor/autoload.php';
// Routing setup
$router = new \Orno\Route\RouteCollection;
// Set up the OAuth 2.0 resource server
$server = new \League\OAuth2\Server\AuthorizationServer;
$server->setSessionStorage(new Storage\SessionStorage);
$server->setAccessTokenStorage(new Storage\AccessTokenStorage);
$server->setRefreshTokenStorage(new Storage\RefreshTokenStorage);
$server->setClientStorage(new Storage\ClientStorage);
$server->setScopeStorage(new Storage\ScopeStorage);
$server->setAuthCodeStorage(new Storage\AuthCodeStorage);
$clientCredentials = new \League\OAuth2\Server\Grant\ClientCredentialsGrant();
$server->addGrantType($clientCredentials);
$passwordGrant = new \League\OAuth2\Server\Grant\PasswordGrant();
$server->addGrantType($passwordGrant);
$refrehTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$server->addGrantType($refrehTokenGrant);
$request = (new Request)->createFromGlobals();
$server->setRequest($request);
$router->post('/access_token', function (Request $request) use ($server) {
try {
$response = $server->issueAccessToken();
return new Response(json_encode($response), 200);
} catch (\Exception $e) {
return new Response(
json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
]),
$e->httpStatusCode,
$e->getHttpHeaders()
);
}
});
$dispatcher = $router->getDispatcher();
$response = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo());
$response->send();

View File

@ -96,7 +96,8 @@ class AuthCodeEntity extends AbstractTokenEntity
$this->server->getStorage('auth_code')->create(
$this->getId(),
$this->getExpireTime(),
$this->getSession()->getId()
$this->getSession()->getId(),
$this->getRedirectUri()
);
// Associate the scope with the token

View File

@ -218,7 +218,6 @@ class AuthCodeGrant extends AbstractGrant
}
$this->server->getTokenType()->set('access_token', $accessToken->getId());
$this->server->getTokenType()->set('expires', $accessToken->getExpireTime());
$this->server->getTokenType()->set('expires_in', $this->server->getAccessTokenTTL());
// Associate a refresh token if set

View File

@ -102,7 +102,6 @@ class ClientCredentialsGrant extends AbstractGrant
$accessToken->save($this->server->getStorage('access_token'));
$this->server->getTokenType()->set('access_token', $accessToken->getId());
$this->server->getTokenType()->set('expires', $accessToken->getExpireTime());
$this->server->getTokenType()->set('expires_in', $this->server->getAccessTokenTTL());
return $this->server->getTokenType()->generateResponse();

View File

@ -137,7 +137,6 @@ class PasswordGrant extends AbstractGrant
}
$this->server->getTokenType()->set('access_token', $accessToken->getId());
$this->server->getTokenType()->set('expires', $accessToken->getExpireTime());
$this->server->getTokenType()->set('expires_in', $this->server->getAccessTokenTTL());
// Associate a refresh token if set

View File

@ -132,7 +132,6 @@ class RefreshTokenGrant extends AbstractGrant
$newAccessToken->save($this->server->getStorage('access_token'));
$this->server->getTokenType()->set('access_token', $newAccessToken->getId());
$this->server->getTokenType()->set('expires', $newAccessToken->getExpireTime());
$this->server->getTokenType()->set('expires_in', $this->server->getAccessTokenTTL());
// Expire the old refresh token

View File

@ -28,13 +28,14 @@ interface AuthCodeInterface
/**
* Create an auth code.
* @param string $token The token ID
* @param integer $expireTime Token expire time
* @param integer $sessionId Session identifier
* @param string $token The token ID
* @param integer $expireTime Token expire time
* @param integer $sessionId Session identifier
* @param string $redirectUri Client redirect uri
*
* @return void
*/
public function create($token, $expireTime, $sessionId);
public function create($token, $expireTime, $sessionId, $redirectUri);
/**
* Get the scopes for an access token

View File

@ -23,7 +23,6 @@ class Bearer extends AbstractTokenType implements TokenTypeInterface
$return = [
'access_token' => $this->get('access_token'),
'token_type' => 'Bearer',
'expires' => $this->get('expires'),
'expires_in' => $this->get('expires_in')
];

View File

@ -0,0 +1,22 @@
<?php
namespace Codeception\Module;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class AuthHelper extends \Codeception\Module
{
function seeJsonKeyExists($key)
{
$json = $this->getModule('REST')->grabResponse();
$array = json_decode($json);
$this->assertTrue(array_key_exists($key, $array));
}
function seeJsonKeyDoesNotExists($key)
{
$json = $this->getModule('REST')->grabResponse();
$array = json_decode($json);
$this->assertFalse(array_key_exists($key, $array));
}
}

8
tests/auth.suite.yml Normal file
View File

@ -0,0 +1,8 @@
class_name: AuthTester
modules:
enabled: [PhpBrowser, REST, AuthHelper]
config:
PhpBrowser:
url: http://localhost:8000/
REST:
url: http://localhost:8000/

View File

@ -0,0 +1,24 @@
<?php
$I = new AuthTester($scenario);
$I->wantTo('get an access token with an authorization code');
$I->sendGET('authcode_grant.php/authorize?client_id=testclient&redirect_uri=http%3A%2F%2Fexample.com%2Fredirect&response_type=code&scope=basic');
$I->seeResponseCodeIs(200);
$I->seeHttpHeader('Location');
$location = $I->grabHttpHeader('Location');
$urlParts = parse_url($location);
parse_str($urlParts['query'], $queryString);
$I->sendPOST('authcode_grant.php/access_token', [
'client_id' => 'testclient',
'redirect_uri' => 'http://example.com/redirect',
'client_secret' => 'secret',
'code' => $queryString['code'],
'grant_type' => 'authorization_code'
]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->seeJsonKeyExists('expires_in');
$I->seeJsonKeyExists('access_token');
$I->seeResponseContainsJson(['token_type' => 'Bearer']);
$I->seeJsonKeyDoesNotExists('foobar');

2162
tests/auth/AuthTester.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
<?php
$I = new AuthTester($scenario);
$I->wantTo('get an access token with client credentials');
$I->sendPOST('other_grants.php/access_token', [
'client_id' => 'testclient',
'client_secret' => 'secret',
'grant_type' => 'client_credentials'
]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->seeJsonKeyExists('expires_in');
$I->seeJsonKeyExists('access_token');
$I->seeResponseContainsJson(['token_type' => 'Bearer']);
$I->seeJsonKeyDoesNotExists('foobar');

View File

@ -0,0 +1,11 @@
<?php
$I = new AuthTester($scenario);
$I->wantTo('get an access token with resource owner credentials');
$I->sendPOST('other_grants.php/access_token', [
'client_id' => 'testclient',
'client_secret' => 'secret',
'grant_type' => 'password',
'username' => 'alexbilbie'
]);
$I->seeResponseCodeIs(400);
$I->seeResponseIsJson();

View File

@ -0,0 +1,15 @@
<?php
$I = new AuthTester($scenario);
$I->wantTo('get an access token with resource owner credentials');
$I->sendPOST('other_grants.php/access_token', [
'client_id' => 'testclient',
'client_secret' => 'secret',
'grant_type' => 'password'
]);
$I->seeResponseCodeIs(400);
$I->seeResponseIsJson();
$I->seeResponseContainsJson([
'error' => 'invalid_request',
'message' => 'The request is missing a required parameter, includes an invalid parameter value, includes a parameter
more than once, or is otherwise malformed. Check the "username" parameter.'
]);

View File

@ -0,0 +1,2 @@
<?php
// Here you can initialize variables that will be available to your tests

View File

@ -402,7 +402,6 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertTrue(array_key_exists('expires', $response));
}
public function testCompleteFlowRefreshToken()
@ -470,6 +469,5 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
// $this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertTrue(array_key_exists('expires', $response));
}
}

View File

@ -11,7 +11,7 @@ use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\AuthorizationServer;
use Mockery as M;
class RefreshTokenGreantTest extends \PHPUnit_Framework_TestCase
class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetRefreshTokenTTL()
{
@ -212,7 +212,6 @@ class RefreshTokenGreantTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertTrue(array_key_exists('expires', $response));
}
public function testCompleteFlowRequestScopes()
@ -284,7 +283,6 @@ class RefreshTokenGreantTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(isset($response['refresh_token']));
$this->assertTrue(isset($response['token_type']));
$this->assertTrue(isset($response['expires_in']));
$this->assertTrue(isset($response['expires']));
}
public function testCompleteFlowRequestScopesInvalid()