From 565ce5ba4b9dfb2921dee8024e10fbcd6380d2fd Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 16 Nov 2015 12:20:57 +0100 Subject: [PATCH 01/61] new gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 6687d80d..de76a418 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ composer.lock phpunit.xml phpspec.yml vendor +.idea From 6c9a908f10403a6e390278e3adcf721ee90675c7 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 7 Jan 2016 11:20:08 +0100 Subject: [PATCH 02/61] First commit for v6 --- composer.json | 26 +- config/oauth2.php | 152 --------- ...04_24_110151_create_oauth_scopes_table.php | 47 --- ...04_24_110304_create_oauth_grants_table.php | 45 --- ...110403_create_oauth_grant_scopes_table.php | 63 ---- ...4_24_110459_create_oauth_clients_table.php | 49 --- ...57_create_oauth_client_endpoints_table.php | 59 ---- ...10705_create_oauth_client_scopes_table.php | 63 ---- ...10817_create_oauth_client_grants_table.php | 64 ---- ..._24_111002_create_oauth_sessions_table.php | 59 ---- ...1109_create_oauth_session_scopes_table.php | 63 ---- ...4_111254_create_oauth_auth_codes_table.php | 58 ---- ...03_create_oauth_auth_code_scopes_table.php | 63 ---- ...11518_create_oauth_access_tokens_table.php | 58 ---- ...create_oauth_access_token_scopes_table.php | 63 ---- ...1810_create_oauth_refresh_tokens_table.php | 56 ---- docs/README.md | 47 --- docs/authorization-server/auth-code.md | 85 ----- docs/authorization-server/choosing-grant.md | 124 ------- .../client-credentials.md | 26 -- docs/authorization-server/custom.md | 20 -- docs/authorization-server/password.md | 49 --- docs/authorization-server/refresh-token.md | 30 -- docs/getting-started/apache.md | 37 --- docs/getting-started/config.md | 86 ----- docs/getting-started/introduction.md | 21 -- docs/getting-started/laravel-4.md | 52 --- docs/getting-started/laravel-5.md | 54 --- docs/getting-started/lumen.md | 53 --- docs/getting-started/middlewares.md | 39 --- docs/getting-started/terminology.md | 17 - docs/resource-server/securing-endpoints.md | 48 --- src/Authorizer.php | 309 ------------------ .../NoActiveAccessTokenException.php | 24 -- src/Facades/Authorizer.php | 32 -- src/Lumen/OAuth2ServerServiceProvider.php | 26 -- .../CheckAuthCodeRequestMiddleware.php | 57 ---- src/Middleware/OAuthClientOwnerMiddleware.php | 62 ---- .../OAuthExceptionHandlerMiddleware.php | 46 --- src/Middleware/OAuthMiddleware.php | 91 ------ src/Middleware/OAuthUserOwnerMiddleware.php | 62 ---- src/OAuth2ServerServiceProvider.php | 199 ----------- src/Storage/AbstractFluentAdapter.php | 90 ----- src/Storage/FluentAccessToken.php | 149 --------- src/Storage/FluentAuthCode.php | 130 -------- src/Storage/FluentClient.php | 190 ----------- src/Storage/FluentRefreshToken.php | 87 ----- src/Storage/FluentScope.php | 139 -------- src/Storage/FluentSession.php | 165 ---------- src/Storage/FluentStorageServiceProvider.php | 132 -------- tests/AbstractTestCase.php | 46 --- .../Seeders/AccessTokensTableSeeder.php | 45 --- .../Database/Seeders/AuthCodesTableSeeder.php | 47 --- tests/Database/Seeders/ClientsTableSeeder.php | 64 ---- tests/Database/Seeders/GrantsTableSeeder.php | 60 ---- .../Database/Seeders/OAuth2DatabaseSeeder.php | 43 --- .../Seeders/RefreshTokensTableSeeder.php | 38 --- tests/Database/Seeders/ScopesTableSeeder.php | 81 ----- .../Database/Seeders/SessionsTableSeeder.php | 45 --- tests/functional/bootstrap/FeatureContext.php | 161 --------- .../functional/bootstrap/OAuthController.php | 55 ---- tests/functional/clientcredentials.feature | 25 -- tests/integration/AbstractDBTestCase.php | 48 --- tests/integration/FluentAccessTokenTest.php | 129 -------- tests/integration/FluentAuthCodeTest.php | 105 ------ tests/integration/FluentClientTest.php | 124 ------- tests/integration/FluentRefreshTokenTest.php | 71 ---- tests/integration/FluentScopeTest.php | 108 ------ tests/integration/FluentSessionTest.php | 138 -------- .../OAuth2Server/AuthorizerSpec.php | 189 ----------- .../CheckAuthCodeRequestMiddlewareSpec.php | 61 ---- .../OAuthClientOwnerMiddlewareSpec.php | 65 ---- .../Middleware/OAuthMiddlewareSpec.php | 84 ----- .../OAuthUserOwnerMiddlewareSpec.php | 65 ---- 74 files changed, 11 insertions(+), 5652 deletions(-) delete mode 100755 config/oauth2.php delete mode 100644 database/migrations/2014_04_24_110151_create_oauth_scopes_table.php delete mode 100644 database/migrations/2014_04_24_110304_create_oauth_grants_table.php delete mode 100644 database/migrations/2014_04_24_110403_create_oauth_grant_scopes_table.php delete mode 100644 database/migrations/2014_04_24_110459_create_oauth_clients_table.php delete mode 100644 database/migrations/2014_04_24_110557_create_oauth_client_endpoints_table.php delete mode 100644 database/migrations/2014_04_24_110705_create_oauth_client_scopes_table.php delete mode 100644 database/migrations/2014_04_24_110817_create_oauth_client_grants_table.php delete mode 100644 database/migrations/2014_04_24_111002_create_oauth_sessions_table.php delete mode 100644 database/migrations/2014_04_24_111109_create_oauth_session_scopes_table.php delete mode 100644 database/migrations/2014_04_24_111254_create_oauth_auth_codes_table.php delete mode 100644 database/migrations/2014_04_24_111403_create_oauth_auth_code_scopes_table.php delete mode 100644 database/migrations/2014_04_24_111518_create_oauth_access_tokens_table.php delete mode 100644 database/migrations/2014_04_24_111657_create_oauth_access_token_scopes_table.php delete mode 100644 database/migrations/2014_04_24_111810_create_oauth_refresh_tokens_table.php delete mode 100644 docs/README.md delete mode 100644 docs/authorization-server/auth-code.md delete mode 100644 docs/authorization-server/choosing-grant.md delete mode 100644 docs/authorization-server/client-credentials.md delete mode 100644 docs/authorization-server/custom.md delete mode 100644 docs/authorization-server/password.md delete mode 100644 docs/authorization-server/refresh-token.md delete mode 100644 docs/getting-started/apache.md delete mode 100644 docs/getting-started/config.md delete mode 100644 docs/getting-started/introduction.md delete mode 100644 docs/getting-started/laravel-4.md delete mode 100644 docs/getting-started/laravel-5.md delete mode 100644 docs/getting-started/lumen.md delete mode 100644 docs/getting-started/middlewares.md delete mode 100644 docs/getting-started/terminology.md delete mode 100644 docs/resource-server/securing-endpoints.md delete mode 100644 src/Authorizer.php delete mode 100644 src/Exceptions/NoActiveAccessTokenException.php delete mode 100644 src/Facades/Authorizer.php delete mode 100644 src/Lumen/OAuth2ServerServiceProvider.php delete mode 100644 src/Middleware/CheckAuthCodeRequestMiddleware.php delete mode 100644 src/Middleware/OAuthClientOwnerMiddleware.php delete mode 100644 src/Middleware/OAuthExceptionHandlerMiddleware.php delete mode 100644 src/Middleware/OAuthMiddleware.php delete mode 100644 src/Middleware/OAuthUserOwnerMiddleware.php delete mode 100644 src/OAuth2ServerServiceProvider.php delete mode 100644 src/Storage/AbstractFluentAdapter.php delete mode 100644 src/Storage/FluentAccessToken.php delete mode 100644 src/Storage/FluentAuthCode.php delete mode 100644 src/Storage/FluentClient.php delete mode 100644 src/Storage/FluentRefreshToken.php delete mode 100644 src/Storage/FluentScope.php delete mode 100644 src/Storage/FluentSession.php delete mode 100644 src/Storage/FluentStorageServiceProvider.php delete mode 100644 tests/AbstractTestCase.php delete mode 100644 tests/Database/Seeders/AccessTokensTableSeeder.php delete mode 100644 tests/Database/Seeders/AuthCodesTableSeeder.php delete mode 100644 tests/Database/Seeders/ClientsTableSeeder.php delete mode 100644 tests/Database/Seeders/GrantsTableSeeder.php delete mode 100644 tests/Database/Seeders/OAuth2DatabaseSeeder.php delete mode 100644 tests/Database/Seeders/RefreshTokensTableSeeder.php delete mode 100644 tests/Database/Seeders/ScopesTableSeeder.php delete mode 100644 tests/Database/Seeders/SessionsTableSeeder.php delete mode 100644 tests/functional/bootstrap/FeatureContext.php delete mode 100644 tests/functional/bootstrap/OAuthController.php delete mode 100644 tests/functional/clientcredentials.feature delete mode 100644 tests/integration/AbstractDBTestCase.php delete mode 100644 tests/integration/FluentAccessTokenTest.php delete mode 100644 tests/integration/FluentAuthCodeTest.php delete mode 100644 tests/integration/FluentClientTest.php delete mode 100644 tests/integration/FluentRefreshTokenTest.php delete mode 100644 tests/integration/FluentScopeTest.php delete mode 100644 tests/integration/FluentSessionTest.php delete mode 100644 tests/unit/LucaDegasperi/OAuth2Server/AuthorizerSpec.php delete mode 100644 tests/unit/LucaDegasperi/OAuth2Server/Middleware/CheckAuthCodeRequestMiddlewareSpec.php delete mode 100644 tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthClientOwnerMiddlewareSpec.php delete mode 100644 tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthMiddlewareSpec.php delete mode 100644 tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthUserOwnerMiddlewareSpec.php diff --git a/composer.json b/composer.json index d28e3d29..9edaa0ac 100644 --- a/composer.json +++ b/composer.json @@ -15,20 +15,20 @@ ], "require": { "php": ">=5.5.9", - "illuminate/database": "5.1.* || 5.2.*", - "illuminate/console": "5.1.* || 5.2.*", - "illuminate/contracts": "5.1.* || 5.2.*", - "illuminate/http": "5.1.* || 5.2.*", - "illuminate/support": "5.1.* || 5.2.*", - "illuminate/config": "5.1.* || 5.2.*", - "league/oauth2-server": "4.1.*" + "illuminate/database": "5.2.*", + "illuminate/console": "5.2.*", + "illuminate/contracts": "5.2.*", + "illuminate/http": "5.2.*", + "illuminate/support": "5.2.*", + "illuminate/config": "5.2.*", + "league/oauth2-server": "5.0.x-dev" }, "require-dev": { - "orchestra/testbench": "3.1.* || 3.2.*", - "phpunit/phpunit": "^4.8 || ^5.0", + "orchestra/testbench": "3.2.*", + "phpunit/phpunit": "^5.0", "phpspec/phpspec": "^2.2", "mockery/mockery": "^0.9.4", - "henrikbjorn/phpspec-code-coverage": "^1.0" + "henrikbjorn/phpspec-code-coverage": "^2.0" }, "autoload": { "psr-4": { @@ -41,15 +41,11 @@ }, "classmap": [ "database" - ], - "files": [ - "tests/AbstractTestCase.php", - "tests/integration/AbstractDBTestCase.php" ] }, "extra": { "branch-alias": { - "dev-master": "5.1-dev" + "dev-master": "6.0-dev" } }, "minimum-stability": "dev", diff --git a/config/oauth2.php b/config/oauth2.php deleted file mode 100755 index cd11554a..00000000 --- a/config/oauth2.php +++ /dev/null @@ -1,152 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -return [ - - /* - |-------------------------------------------------------------------------- - | Supported Grant Types - |-------------------------------------------------------------------------- - | - | Your OAuth2 Server can issue an access token based on different grant - | types you can even provide your own grant type. - | - | To choose which grant type suits your scenario, see - | http://oauth2.thephpleague.com/authorization-server/which-grant - | - | Please see this link to find available grant types - | http://git.io/vJLAv - | - */ - - 'grant_types' => [ - - ], - - /* - |-------------------------------------------------------------------------- - | Output Token Type - |-------------------------------------------------------------------------- - | - | This will tell the authorization server the output format for the access - | token and the resource server how to parse the access token used. - | - | Default value is League\OAuth2\Server\TokenType\Bearer - | - */ - - 'token_type' => 'League\OAuth2\Server\TokenType\Bearer', - - /* - |-------------------------------------------------------------------------- - | State Parameter - |-------------------------------------------------------------------------- - | - | Whether or not the state parameter is required in the query string. - | - */ - - 'state_param' => false, - - /* - |-------------------------------------------------------------------------- - | Scope Parameter - |-------------------------------------------------------------------------- - | - | Whether or not the scope parameter is required in the query string. - | - */ - - 'scope_param' => false, - - /* - |-------------------------------------------------------------------------- - | Scope Delimiter - |-------------------------------------------------------------------------- - | - | Which character to use to split the scope parameter in the query string. - | - */ - - 'scope_delimiter' => ',', - - /* - |-------------------------------------------------------------------------- - | Default Scope - |-------------------------------------------------------------------------- - | - | The default scope to use if not present in the query string. - | - */ - - 'default_scope' => null, - - /* - |-------------------------------------------------------------------------- - | Access Token TTL - |-------------------------------------------------------------------------- - | - | For how long the issued access token is valid (in seconds) this can be - | also set on a per grant-type basis. - | - */ - - 'access_token_ttl' => 3600, - - /* - |-------------------------------------------------------------------------- - | Limit clients to specific grants - |-------------------------------------------------------------------------- - | - | Whether or not to limit clients to specific grant types. This is useful - | to allow only trusted clients to access your API differently. - | - */ - - 'limit_clients_to_grants' => false, - - /* - |-------------------------------------------------------------------------- - | Limit clients to specific scopes - |-------------------------------------------------------------------------- - | - | Whether or not to limit clients to specific scopes. This is useful to - | only allow specific clients to use some scopes. - | - */ - - 'limit_clients_to_scopes' => false, - - /* - |-------------------------------------------------------------------------- - | Limit scopes to specific grants - |-------------------------------------------------------------------------- - | - | Whether or not to limit scopes to specific grants. This is useful to - | allow certain scopes to be used only with certain grant types. - | - */ - - 'limit_scopes_to_grants' => false, - - /* - |-------------------------------------------------------------------------- - | HTTP Header Only - |-------------------------------------------------------------------------- - | - | This will tell the resource server where to check for the access_token. - | By default it checks both the query string and the http headers. - | - */ - - 'http_headers_only' => false, - -]; diff --git a/database/migrations/2014_04_24_110151_create_oauth_scopes_table.php b/database/migrations/2014_04_24_110151_create_oauth_scopes_table.php deleted file mode 100644 index 0b4a1d6d..00000000 --- a/database/migrations/2014_04_24_110151_create_oauth_scopes_table.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth scopes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthScopesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_scopes', function (Blueprint $table) { - $table->string('id', 40)->primary(); - $table->string('description'); - - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('oauth_scopes'); - } -} diff --git a/database/migrations/2014_04_24_110304_create_oauth_grants_table.php b/database/migrations/2014_04_24_110304_create_oauth_grants_table.php deleted file mode 100644 index a15f8ff7..00000000 --- a/database/migrations/2014_04_24_110304_create_oauth_grants_table.php +++ /dev/null @@ -1,45 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth grants table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthGrantsTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_grants', function (Blueprint $table) { - $table->string('id', 40)->primary(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('oauth_grants'); - } -} diff --git a/database/migrations/2014_04_24_110403_create_oauth_grant_scopes_table.php b/database/migrations/2014_04_24_110403_create_oauth_grant_scopes_table.php deleted file mode 100644 index 97449c9e..00000000 --- a/database/migrations/2014_04_24_110403_create_oauth_grant_scopes_table.php +++ /dev/null @@ -1,63 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth grant scopes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthGrantScopesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_grant_scopes', function (Blueprint $table) { - $table->increments('id'); - $table->string('grant_id', 40); - $table->string('scope_id', 40); - - $table->timestamps(); - - $table->index('grant_id'); - $table->index('scope_id'); - - $table->foreign('grant_id') - ->references('id')->on('oauth_grants') - ->onDelete('cascade'); - - $table->foreign('scope_id') - ->references('id')->on('oauth_scopes') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_grant_scopes', function (Blueprint $table) { - $table->dropForeign('oauth_grant_scopes_grant_id_foreign'); - $table->dropForeign('oauth_grant_scopes_scope_id_foreign'); - }); - Schema::drop('oauth_grant_scopes'); - } -} diff --git a/database/migrations/2014_04_24_110459_create_oauth_clients_table.php b/database/migrations/2014_04_24_110459_create_oauth_clients_table.php deleted file mode 100644 index 817b3f38..00000000 --- a/database/migrations/2014_04_24_110459_create_oauth_clients_table.php +++ /dev/null @@ -1,49 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth client table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthClientsTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_clients', function (BluePrint $table) { - $table->string('id', 40)->primary(); - $table->string('secret', 40); - $table->string('name'); - $table->timestamps(); - - $table->unique(['id', 'secret']); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('oauth_clients'); - } -} diff --git a/database/migrations/2014_04_24_110557_create_oauth_client_endpoints_table.php b/database/migrations/2014_04_24_110557_create_oauth_client_endpoints_table.php deleted file mode 100644 index 86650385..00000000 --- a/database/migrations/2014_04_24_110557_create_oauth_client_endpoints_table.php +++ /dev/null @@ -1,59 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth client endpoints table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthClientEndpointsTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_client_endpoints', function (Blueprint $table) { - $table->increments('id'); - $table->string('client_id', 40); - $table->string('redirect_uri'); - - $table->timestamps(); - - $table->unique(['client_id', 'redirect_uri']); - - $table->foreign('client_id') - ->references('id')->on('oauth_clients') - ->onDelete('cascade') - ->onUpdate('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_client_endpoints', function (Blueprint $table) { - $table->dropForeign('oauth_client_endpoints_client_id_foreign'); - }); - - Schema::drop('oauth_client_endpoints'); - } -} diff --git a/database/migrations/2014_04_24_110705_create_oauth_client_scopes_table.php b/database/migrations/2014_04_24_110705_create_oauth_client_scopes_table.php deleted file mode 100644 index e7a76431..00000000 --- a/database/migrations/2014_04_24_110705_create_oauth_client_scopes_table.php +++ /dev/null @@ -1,63 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth client scopes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthClientScopesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_client_scopes', function (Blueprint $table) { - $table->increments('id'); - $table->string('client_id', 40); - $table->string('scope_id', 40); - - $table->timestamps(); - - $table->index('client_id'); - $table->index('scope_id'); - - $table->foreign('client_id') - ->references('id')->on('oauth_clients') - ->onDelete('cascade'); - - $table->foreign('scope_id') - ->references('id')->on('oauth_scopes') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_client_scopes', function (Blueprint $table) { - $table->dropForeign('oauth_client_scopes_client_id_foreign'); - $table->dropForeign('oauth_client_scopes_scope_id_foreign'); - }); - Schema::drop('oauth_client_scopes'); - } -} diff --git a/database/migrations/2014_04_24_110817_create_oauth_client_grants_table.php b/database/migrations/2014_04_24_110817_create_oauth_client_grants_table.php deleted file mode 100644 index 1afb2c9a..00000000 --- a/database/migrations/2014_04_24_110817_create_oauth_client_grants_table.php +++ /dev/null @@ -1,64 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth client grants table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthClientGrantsTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_client_grants', function (Blueprint $table) { - $table->increments('id'); - $table->string('client_id', 40); - $table->string('grant_id', 40); - $table->timestamps(); - - $table->index('client_id'); - $table->index('grant_id'); - - $table->foreign('client_id') - ->references('id')->on('oauth_clients') - ->onDelete('cascade') - ->onUpdate('no action'); - - $table->foreign('grant_id') - ->references('id')->on('oauth_grants') - ->onDelete('cascade') - ->onUpdate('no action'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_client_grants', function (Blueprint $table) { - $table->dropForeign('oauth_client_grants_client_id_foreign'); - $table->dropForeign('oauth_client_grants_grant_id_foreign'); - }); - Schema::drop('oauth_client_grants'); - } -} diff --git a/database/migrations/2014_04_24_111002_create_oauth_sessions_table.php b/database/migrations/2014_04_24_111002_create_oauth_sessions_table.php deleted file mode 100644 index 375c4a41..00000000 --- a/database/migrations/2014_04_24_111002_create_oauth_sessions_table.php +++ /dev/null @@ -1,59 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth sessions table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthSessionsTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_sessions', function (Blueprint $table) { - $table->increments('id'); - $table->string('client_id', 40); - $table->enum('owner_type', ['client', 'user'])->default('user'); - $table->string('owner_id'); - $table->string('client_redirect_uri')->nullable(); - $table->timestamps(); - - $table->index(['client_id', 'owner_type', 'owner_id']); - - $table->foreign('client_id') - ->references('id')->on('oauth_clients') - ->onDelete('cascade') - ->onUpdate('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_sessions', function (Blueprint $table) { - $table->dropForeign('oauth_sessions_client_id_foreign'); - }); - Schema::drop('oauth_sessions'); - } -} diff --git a/database/migrations/2014_04_24_111109_create_oauth_session_scopes_table.php b/database/migrations/2014_04_24_111109_create_oauth_session_scopes_table.php deleted file mode 100644 index 79b16146..00000000 --- a/database/migrations/2014_04_24_111109_create_oauth_session_scopes_table.php +++ /dev/null @@ -1,63 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth session scopes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthSessionScopesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_session_scopes', function (Blueprint $table) { - $table->increments('id'); - $table->integer('session_id')->unsigned(); - $table->string('scope_id', 40); - - $table->timestamps(); - - $table->index('session_id'); - $table->index('scope_id'); - - $table->foreign('session_id') - ->references('id')->on('oauth_sessions') - ->onDelete('cascade'); - - $table->foreign('scope_id') - ->references('id')->on('oauth_scopes') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_session_scopes', function (Blueprint $table) { - $table->dropForeign('oauth_session_scopes_session_id_foreign'); - $table->dropForeign('oauth_session_scopes_scope_id_foreign'); - }); - Schema::drop('oauth_session_scopes'); - } -} diff --git a/database/migrations/2014_04_24_111254_create_oauth_auth_codes_table.php b/database/migrations/2014_04_24_111254_create_oauth_auth_codes_table.php deleted file mode 100644 index 2904702c..00000000 --- a/database/migrations/2014_04_24_111254_create_oauth_auth_codes_table.php +++ /dev/null @@ -1,58 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth auth codes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthAuthCodesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_auth_codes', function (Blueprint $table) { - $table->string('id', 40)->primary(); - $table->integer('session_id')->unsigned(); - $table->string('redirect_uri'); - $table->integer('expire_time'); - - $table->timestamps(); - - $table->index('session_id'); - - $table->foreign('session_id') - ->references('id')->on('oauth_sessions') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_auth_codes', function (Blueprint $table) { - $table->dropForeign('oauth_auth_codes_session_id_foreign'); - }); - Schema::drop('oauth_auth_codes'); - } -} diff --git a/database/migrations/2014_04_24_111403_create_oauth_auth_code_scopes_table.php b/database/migrations/2014_04_24_111403_create_oauth_auth_code_scopes_table.php deleted file mode 100644 index fdee7611..00000000 --- a/database/migrations/2014_04_24_111403_create_oauth_auth_code_scopes_table.php +++ /dev/null @@ -1,63 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth code scopes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthAuthCodeScopesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_auth_code_scopes', function (Blueprint $table) { - $table->increments('id'); - $table->string('auth_code_id', 40); - $table->string('scope_id', 40); - - $table->timestamps(); - - $table->index('auth_code_id'); - $table->index('scope_id'); - - $table->foreign('auth_code_id') - ->references('id')->on('oauth_auth_codes') - ->onDelete('cascade'); - - $table->foreign('scope_id') - ->references('id')->on('oauth_scopes') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_auth_code_scopes', function (Blueprint $table) { - $table->dropForeign('oauth_auth_code_scopes_auth_code_id_foreign'); - $table->dropForeign('oauth_auth_code_scopes_scope_id_foreign'); - }); - Schema::drop('oauth_auth_code_scopes'); - } -} diff --git a/database/migrations/2014_04_24_111518_create_oauth_access_tokens_table.php b/database/migrations/2014_04_24_111518_create_oauth_access_tokens_table.php deleted file mode 100644 index c5881633..00000000 --- a/database/migrations/2014_04_24_111518_create_oauth_access_tokens_table.php +++ /dev/null @@ -1,58 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth access tokens table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthAccessTokensTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_access_tokens', function (Blueprint $table) { - $table->string('id', 40)->primary(); - $table->integer('session_id')->unsigned(); - $table->integer('expire_time'); - - $table->timestamps(); - - $table->unique(['id', 'session_id']); - $table->index('session_id'); - - $table->foreign('session_id') - ->references('id')->on('oauth_sessions') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_access_tokens', function (Blueprint $table) { - $table->dropForeign('oauth_access_tokens_session_id_foreign'); - }); - Schema::drop('oauth_access_tokens'); - } -} diff --git a/database/migrations/2014_04_24_111657_create_oauth_access_token_scopes_table.php b/database/migrations/2014_04_24_111657_create_oauth_access_token_scopes_table.php deleted file mode 100644 index 4c9a7af4..00000000 --- a/database/migrations/2014_04_24_111657_create_oauth_access_token_scopes_table.php +++ /dev/null @@ -1,63 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth access token scopes table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthAccessTokenScopesTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_access_token_scopes', function (Blueprint $table) { - $table->increments('id'); - $table->string('access_token_id', 40); - $table->string('scope_id', 40); - - $table->timestamps(); - - $table->index('access_token_id'); - $table->index('scope_id'); - - $table->foreign('access_token_id') - ->references('id')->on('oauth_access_tokens') - ->onDelete('cascade'); - - $table->foreign('scope_id') - ->references('id')->on('oauth_scopes') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_access_token_scopes', function (Blueprint $table) { - $table->dropForeign('oauth_access_token_scopes_scope_id_foreign'); - $table->dropForeign('oauth_access_token_scopes_access_token_id_foreign'); - }); - Schema::drop('oauth_access_token_scopes'); - } -} diff --git a/database/migrations/2014_04_24_111810_create_oauth_refresh_tokens_table.php b/database/migrations/2014_04_24_111810_create_oauth_refresh_tokens_table.php deleted file mode 100644 index b7262b03..00000000 --- a/database/migrations/2014_04_24_111810_create_oauth_refresh_tokens_table.php +++ /dev/null @@ -1,56 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; - -/** - * This is the create oauth refresh tokens table migration class. - * - * @author Luca Degasperi - */ -class CreateOauthRefreshTokensTable extends Migration -{ - /** - * Run the migrations. - * - * @return void - */ - public function up() - { - Schema::create('oauth_refresh_tokens', function (Blueprint $table) { - $table->string('id', 40)->unique(); - $table->string('access_token_id', 40)->primary(); - $table->integer('expire_time'); - - $table->timestamps(); - - $table->foreign('access_token_id') - ->references('id')->on('oauth_access_tokens') - ->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('oauth_refresh_tokens', function (Blueprint $table) { - $table->dropForeign('oauth_refresh_tokens_access_token_id_foreign'); - }); - - Schema::drop('oauth_refresh_tokens'); - } -} diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 4c3af43a..00000000 --- a/docs/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# Documentation - -This wiki will guide you through all the things you need to successfully integrate an OAuth 2.0 compliant server into your Laravel applications. Let's begin! - -## Getting Started - -1. [Introduction](getting-started/introduction.md) -2. [Terminology](getting-started/terminology.md) -3. [Laravel 4 Installation](getting-started/laravel-4.md) -4. [Laravel 5 Installation](getting-started/laravel-5.md) -5. [Lumen Installation](getting-started/lumen.md) -6. [Configuration](getting-started/config.md) -7. [Middlewares](getting-started/middlewares.md) -8. [Apache ModRewrite](getting-started/apache.md) - -#### Authorization Server - -1. [Choosing a Grant](authorization-server/choosing-grant.md) -2. Implementing an Authorization Server - 1. [With the Client Credentials Grant](authorization-server/client-credentials.md) - 2. [With the Password Grant](authorization-server/password.md) - 3. [With the Auth Code Grant](authorization-server/auth-code.md) - 4. [With the Refresh Token Grant](authorization-server/refresh-token.md) -3. Extending the server - 1. Using a different storage - 2. [Creating your own grant type](authorization-server/custom.md) - -#### Resource Server - -1. [Securing your API endpoints](resource-server/securing-endpoints.md) - 2. [Defining scopes](resource-server/securing-endpoints.md#defining-scopes) - 3. [Checking the access token](resource-server/securing-endpoints.md#checking-the-access-token) - 4. [Checking the scopes](resource-server/securing-endpoints.md#checking-the-scopes) - -## Articles & Resources - -- [The OAuth 2.0 authorization framework specification](https://tools.ietf.org/html/rfc6749) -- [The PHP League's official documentation](http://oauth2.thephpleague.com) -- [OAuth 2 Simplified by Aaron Parecki](https://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified) - -## Contributing - -We welcome any pull request to improve the documentation. Please see our [contributing guidelines](../CONTRIBUTING.md). - -## License - -The Laravel OAuth 2.0 package is released under [the MIT License](../LICENSE). diff --git a/docs/authorization-server/auth-code.md b/docs/authorization-server/auth-code.md deleted file mode 100644 index c509b983..00000000 --- a/docs/authorization-server/auth-code.md +++ /dev/null @@ -1,85 +0,0 @@ -# Implementing an Authorization Server with the Auth Code Grant - -1. To enable this grant add the following to the `config/oauth2.php` configuration file - - ```php - 'grant_types' => [ - 'authorization_code' => [ - 'class' => '\League\OAuth2\Server\Grant\AuthCodeGrant', - 'access_token_ttl' => 3600, - 'auth_token_ttl' => 3600 - ] - ] - ``` - -2. Set up a route to respond to the incoming auth code requests - - ```php - Route::get('oauth/authorize', ['as' => 'oauth.authorize.get', 'middleware' => ['check-authorization-params', 'auth'], function() { - $authParams = Authorizer::getAuthCodeRequestParams(); - - $formParams = array_except($authParams,'client'); - - $formParams['client_id'] = $authParams['client']->getId(); - - $formParams['scope'] = implode(config('oauth2.scope_delimiter'), array_map(function ($scope) { - return $scope->getId(); - }, $authParams['scopes'])); - - return View::make('oauth.authorization-form', ['params' => $formParams, 'client' => $authParams['client']]); - }]); - ``` - > **Note:** The form you submit should preserve the query string. - - ```php -

{{$client->getName()}}

-
- - - - - - - - -
- ``` - -3. Set up a route to respond to the form being posted. - - ```php - Route::post('oauth/authorize', ['as' => 'oauth.authorize.post', 'middleware' => ['csrf', 'check-authorization-params', 'auth'], function() { - - $params = Authorizer::getAuthCodeRequestParams(); - $params['user_id'] = Auth::user()->id; - $redirectUri = '/'; - - // If the user has allowed the client to access its data, redirect back to the client with an auth code. - if (Request::has('approve')) { - $redirectUri = Authorizer::issueAuthCode('user', $params['user_id'], $params); - } - - // If the user has denied the client to access its data, redirect back to the client with an error message. - if (Request::has('deny')) { - $redirectUri = Authorizer::authCodeRequestDeniedRedirectUri(); - } - - return Redirect::to($redirectUri); - }]); - ``` - -4. Add a route to respond to the access token requests - - ```php - Route::post('oauth/access_token', function() { - return Response::json(Authorizer::issueAccessToken()); - }); - ``` - -5. Next add a sample `client` to the `oauth_clients` table. - -6. And finally add `redirect_uri` to the `oauth_client_endpoints` table for `client`. - ---- - -[← Back to start](../README.md) diff --git a/docs/authorization-server/choosing-grant.md b/docs/authorization-server/choosing-grant.md deleted file mode 100644 index 2f6065a6..00000000 --- a/docs/authorization-server/choosing-grant.md +++ /dev/null @@ -1,124 +0,0 @@ -# Choosing a Grant - -OAuth 2.0 by it’s nature is a very flexible standard and can be adapted to work in many different scenarios. The [core specification](http://tools.ietf.org/html/rfc6749) describes four authorization grants: - -* Authorization code grant -* Implicit grant -* Resource owner credentials grant -* Client credentials grant - -The specification also details another grant called the _refresh token grant_. - -Furthermore there are a number of other grants that have gone through the IETF ratification process (none of which at the time of writing have been formally standardised): - -* Message authentication code (MAC) tokens -* SAML 2.0 Bearer Assertion Profiles -* JSON web token grant - -The end goal of each of these grants (except the refresh token grant) is for the client application to have an access token (which represents a user’s permission for the client to access their data) which it can use to authenticate a request to an API endpoint. - -This page describes each of the above grants and their appropriate use cases. - -As a refresher here is a quick glossary of OAuth terms (taken from the core spec): - -* **Resource owner (a.k.a. the User)** - An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an end-user. -* **Resource server (a.k.a. the API server)** - The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens. -* **Client** - An application making protected resource requests on behalf of the resource owner and with its authorization. The term client does not imply any particular implementation characteristics (e.g. whether the application executes on a server, a desktop, or other devices). -* **Authorization server** - The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization. - -## Authorization code grant ([section 4.1](http://tools.ietf.org/html/rfc6749#section-4.1)) - -> To enable this grant: -> ```php -> 'grant_types' => [ -> 'authorization_code' => [ -> 'class' => '\League\OAuth2\Server\Grant\AuthCodeGrant', -> 'access_token_ttl' => 3600, -> 'auth_token_ttl' => 60 -> ] -> ] -> ``` - -The authorization code grant is the grant that most people think of when OAuth is described. - -If you’ve ever signed into a website or application with your Twitter/Facebook/Google/(insert major Internet company here) account then you’ll have experienced using this grant. - -Essentially a user will click on a “sign in with Facebook” (or other IdP) and then be redirected from the application/website (the “client”) to the IdP authorization server. The user will then sign in to the IdP with their credentials, and then - if they haven’t already - authorise the client to allow it to use the user’s data (such as their name, email address, etc). If they authorise the request the user will be redirected back to the client with a token (called the authorization code) in the query string (e.g. `http://client.com/redirect?code=XYZ123`) which the client will capture and exchange for an access token in the background. - -This grant is suitable where the resource owner is a user and they are using a client which allows a user to interact with a website in a browser. An obvious example is the client being another website, but desktop applications such as Spotify or Reeder use embedded browsers. - -Some mobile applications use this flow and again use an embedded browser (or redirect the user to the native browser and then are redirected back to the app using a custom protocol). - -In this grant the access token is kept private from the resource owner. - -If you have a mobile application that is for your own service (such as the official Spotify or Facebook apps on iOS) it isn’t appropriate to use this grant as the app itself should already be trusted by your authorization server and so the _resource owner credentials grant_ would be more appropriate. - -## Implicit grant ([section 4.2](http://tools.ietf.org/html/rfc6749#section-4.2)) - -The implicit grant is similar to the authentication code grant described above. The user will be redirected in a browser to the IdP authorization server, sign in, authorize the request but instead of being returned to the client with an authentication code they are redirected with an access token straight away. - -The purpose of the implicit grant is for use by clients which are not capable of keeping the client’s own credentials secret; for example a JavaScript only application. - -**If you decide to implement this grant then you must be aware that the access token should be treated as “public knowledge” (like a public RSA key)** and therefore it must have a very limited permissions when interacting with the API server. For example an access token that was granted using the authentication code grant could have permission to be used to delete resources owned by the user, however an access token granted through the implicit flow should only be able to “read” resources and never perform any destructive operations (i.e. non-idempotent method). - -## Resource owner credentials grant ([section 4.3](http://tools.ietf.org/html/rfc6749#section-4.3)) - -To enable this grant: -```php -'grant_types' => [ - 'password' => [ - 'class' => '\League\OAuth2\Server\Grant\PasswordGrant', - 'callback' => '\YourAppNamespace\Verifier@verify', - 'access_token_ttl' => 3600 - ] -] -``` - -When this grant is implemented the client itself will ask the user for their username and password (as opposed to being redirected to an IdP authorization server to authenticate) and then send these to the authorization server along with the client’s own credentials. If the authentication is successful then the client will be issued with an access token. - -This grant is suitable for trusted clients such as a service’s own mobile client (for example Spotify’s iOS app). You could also use this in software where it’s not easy to implement the authorization code - for example we bolted this authorization grant into [OwnCloud](http://owncloud.org/) so we could retrieve details about a user that we couldn’t access over LDAP from the university’s Active Directory server. - -## Client credentials grant ([section 4.4](http://tools.ietf.org/html/rfc6749#section-4.4)) - -To enable this grant: -```php -'grant_types' => [ - 'client_credentials' => [ - 'class' => '\League\OAuth2\Server\Grant\ClientCredentialsGrant', - 'access_token_ttl' => 3600 - ] -] -``` - -This grant is similar to the resource owner credentials grant except only the client’s credentials are used to authenticate a request for an access token. Again this grant should only be allowed to be used by trusted clients. - -This grant is suitable for machine-to-machine authentication, for example for use in a cron job which is performing maintenance tasks over an API. Another example would be a client making requests to an API that don’t require user’s permission. - -When someone visits a member of staff’s page on the [University of Lincoln staff directory](http://staff.lincoln.ac.uk/) the website uses it’s own access token (that was generated using this grant) to authenticate a request to the API server to get the data about the member of staff that is used to build the page. When a member of staff signs in to update their profile however their own access token is used to retrieve and update their data. Therefore there is a good separation of concerns and we can easily restrict permissions that each type of access token has. - -## Refresh token grant ([section 1.5](http://tools.ietf.org/html/rfc6749#section-1.5)) - -To enable this grant: -```php -'grant_types' => [ - 'refresh_token' => [ - 'class' => '\League\OAuth2\Server\Grant\RefreshTokenGrant', - 'access_token_ttl' => 3600, - 'refresh_token_ttl' => 36000 - ] -] -``` - -The OAuth 2.0 specification also details a fifth grant which can be used to “refresh” (i.e. renew) an access token which has expired. - -Authorization servers which support this grant will also issue a “refresh token” when it returns an access token to a client. When the access token expires instead of sending the user back through the authorization code grant the client can use to the refresh token to retrieve a new access token with the same permissions as the old one. - -A problem with the grant is that it means the client has to maintain state of each token and then either on a cron job keep access tokens up to date or when it tries to make a request and it fails then go and update the access token and repeat the request. - ---- - -This page was originally posted at [http://alexbilbie.com/2013/02/a-guide-to-oauth-2-grants/](http://alexbilbie.com/2013/02/a-guide-to-oauth-2-grants/). It has been modified to suite this package configuration. - ---- - -[← Back to start](../README.md) diff --git a/docs/authorization-server/client-credentials.md b/docs/authorization-server/client-credentials.md deleted file mode 100644 index 66d630eb..00000000 --- a/docs/authorization-server/client-credentials.md +++ /dev/null @@ -1,26 +0,0 @@ -# Implementing an Authorization Server with the Client Credentials Grant - -1. To enable this grant add the following to the `config/oauth2.php` configuration file: - - ```php - 'grant_types' => [ - 'client_credentials' => [ - 'class' => '\League\OAuth2\Server\Grant\ClientCredentialsGrant', - 'access_token_ttl' => 3600 - ] - ] - ``` - -2. Next add a couple of `clients` to the `oauth_clients` table. - -3. Finally set up a route to respond to the incoming access token requests. - - ```php - Route::post('oauth/access_token', function() { - return Response::json(Authorizer::issueAccessToken()); - }); - ``` - ---- - -[← Back to start](../README.md) diff --git a/docs/authorization-server/custom.md b/docs/authorization-server/custom.md deleted file mode 100644 index a42a7b1c..00000000 --- a/docs/authorization-server/custom.md +++ /dev/null @@ -1,20 +0,0 @@ -# Creating a Custom Grant - -To create your custom grant type follow Alex's guide. - -> http://oauth2.thephpleague.com/authorization-server/custom-grants/ - -Registering your custom Grant with this package is easy: - -Add the following properties to your `config/oauth.php` -```php -'grant_types' => [ - 'custom_grant_identifier' => [ - 'class' => 'Your\Custom\Grant\Namespace\And\Class' - ] -] -``` - ---- - -[← Back to start](../README.md) diff --git a/docs/authorization-server/password.md b/docs/authorization-server/password.md deleted file mode 100644 index bc59f42b..00000000 --- a/docs/authorization-server/password.md +++ /dev/null @@ -1,49 +0,0 @@ -# Implementing an Authorization Server with the Password Grant - -1. To enable this grant add the following to the `config/oauth2.php` configuration file. - ```php - 'grant_types' => [ - 'password' => [ - 'class' => '\League\OAuth2\Server\Grant\PasswordGrant', - 'callback' => '\App\PasswordVerifier@verify', - 'access_token_ttl' => 3600 - ] - ] - ``` - -2. Create a class with a `verify` method where you check if the provided user is a valid one. - - ```php - use Illuminate\Support\Facades\Auth; - - class PasswordGrantVerifier - { - public function verify($username, $password) - { - $credentials = [ - 'email' => $username, - 'password' => $password, - ]; - - if (Auth::once($credentials)) { - return Auth::user()->id; - } - - return false; - } - } - ``` - -3. Next add a sample `client` to the `oauth_clients` table. - -4. Finally set up a route to respond to the incoming access token requests. - - ```php - Route::post('oauth/access_token', function() { - return Response::json(Authorizer::issueAccessToken()); - }); - ``` - ---- - -[← Back to start](../README.md) diff --git a/docs/authorization-server/refresh-token.md b/docs/authorization-server/refresh-token.md deleted file mode 100644 index d411a34f..00000000 --- a/docs/authorization-server/refresh-token.md +++ /dev/null @@ -1,30 +0,0 @@ -# Implementing an Authorization Server with the Refresh Token Grant - -1. To enable this grant add the following to the `config/oauth2.php` configuration file - - ```php - 'grant_types' => [ - 'refresh_token' => [ - 'class' => '\League\OAuth2\Server\Grant\RefreshTokenGrant', - 'access_token_ttl' => 3600, - 'refresh_token_ttl' => 36000 - ] - ] - ``` - - > **Note:** The refresh token grant is to be used together with one other of the following grants: `PasswordGrant`, `AuthCodeGrant`. - - -2. Set up a route to respond to the incoming access token requests. - - ```php - Route::post('oauth/access_token', function() { - return Response::json(Authorizer::issueAccessToken()); - }); - ``` - -3. Whenever you request an Access Token using a grant that supports the use of the Refresh Token grant, you'll get a Refresh Token together with the Access Token. Once the Access Token expires, use the Refresh Token to require a new one. - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/apache.md b/docs/getting-started/apache.md deleted file mode 100644 index 019b00f4..00000000 --- a/docs/getting-started/apache.md +++ /dev/null @@ -1,37 +0,0 @@ -# Apache ModRewrite - -If you are using Apache, you might notice that your Authorization headers are not making it through with the request. Many hosts do not allow this header through by default, and Apache is no exception. - -Open up your .htaccess file in /public and add the following lines of code before the Front Controller block: - -```sh -# Authorization Headers -RewriteCond %{HTTP:Authorization} . -RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] -``` - -Your full `.htaccess` file should look like this after the change: - -```sh - - - Options -MultiViews - - - RewriteEngine On - - # Redirect Trailing Slashes... - RewriteRule ^(.*)/$ /$1 [L,R=301] - # Authorization Header - RewriteCond %{HTTP:Authorization} . - RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] - # Handle Front Controller... - RewriteCond %{REQUEST_FILENAME} !-d - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^ index.php [L] - -``` - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/config.md b/docs/getting-started/config.md deleted file mode 100644 index eea0db76..00000000 --- a/docs/getting-started/config.md +++ /dev/null @@ -1,86 +0,0 @@ -# Config - -The file in `config/oauth2.php` contains plenty of options you can use to configure your OAuth 2.0 server implementation to suit the needs of your business. Here's the explanation for them. - -### `grant_types` -options: `array` - -An array of grant types supported by the authorization server to obtain an access token. See [Issuing access tokens](https://github.com/lucadegasperi/oauth2-server-laravel/wiki#authorization-server) for how to configure and use the different grant types. - -### `token_type` -options: `string` - -default: `League\OAuth2\Server\TokenType\Bearer` - -This option informs the authorization server how the returned tokens should be formatted. - -### `state_param` -options: `true` or `false` - -default: `false` - -If this option is true, each request to the authorization server should contain a `&state=random_string` param. The state parameter is an additional security measure and the authorization server will reply back to your request with a response containing the same state param you passed. If the state param between the request and response doesn't match, the authorization server might have been compromised. - -### `scope_param` -options: `true` or `false` - -default: `false` - -Whether or not the scope parameter is required in the query string. The scope(s) reflects the type of permission the client wants to access on user's behalf. See [Defining Scopes] for how to use scopes. - - -### `scope_delimiter` -options: `string` - -default `','` - -The separator used to split the different scopes provided in the query string when multiple scopes are provided. See [Defining Scopes] for how to use scopes. - - -### `default_scope` -options: `string` or `null` - -default: `null` - -This option indicates the default scope each access token request has when no scope parameter is provided in the query string. `null` means the requests have no default scope. See [Defining Scopes] for how to use scopes. - - -### `access_token_ttl` -options: `integer` - -default: `3600` - -The number of seconds after an issued access token is not considered valid. Can be overwritten on a grant type basis. - -### `limit_clients_to_grants` -options: `true` or `false` - -default: `false` - -This options sets whether or not a client is limited to specific grant types for obtaining an access token. The `oauth_client_grants` table regulates which clients can use which grant types. - -### `limit_clients_to_scopes` -options: `true` or `false` - -default: `false` - -This options sets which clients can use which scopes. It is useful for allowing different grades of permissions to different clients. The `oauth_client_scopes` table regulates which clients can use which scopes. - -### `limit_scopes_to_grants` -options: `true` or `false` - -default: `false` - -This options allows the use of certain scopes only when required with the appropriate grant type. this is due to the fact that different grant types have different grades of security. For example, a highly permissive scope should be allowed only to clients you trust or can request an access token securely. -The `oauth_grant_scopes` table regulates which grant types can use which scopes. - -### `http_headers_only` -options: `true` or `false` - -default: `false` - -This options tells the resource server where to check for the access token. If set to true only the http headers will be checked. - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/introduction.md b/docs/getting-started/introduction.md deleted file mode 100644 index 8787677c..00000000 --- a/docs/getting-started/introduction.md +++ /dev/null @@ -1,21 +0,0 @@ -# Introduction - -This library makes working with OAuth 2.0 inside your Laravel application trivial. You can easily configure an OAuth 2.0 server to protect your API with access tokens, or allow clients to request new access tokens and refresh them. - -It supports out of the box the following grants: - -- Authorization code grant -- Client credentials grant -- Resource owner password credentials grant -- Refresh grant -- You can also define your own grants. - -In addition it supports the following token types: - -- Bearer tokens -- MAC tokens (coming soon) -- JSON web tokens (coming soon) - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/laravel-4.md b/docs/getting-started/laravel-4.md deleted file mode 100644 index 1c116742..00000000 --- a/docs/getting-started/laravel-4.md +++ /dev/null @@ -1,52 +0,0 @@ -# Laravel 4 - -Composer is the recommended way to install this package. Add the following line to your `composer.json` file: - -```json -"lucadegasperi/oauth2-server-laravel": "^3.0" -``` - -Then run `composer update` to get the package. - -> **Note:** If installation fails set `"minimum-stability": "dev"` in your `composer.json` file. - -Once composer has installed the package add this line of code to the `providers` array located in your `app/config/app.php` file: -```php -'LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider', -'LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider', -``` - -And this lines to the `aliases` array: -```php -'Authorizer' => 'LucaDegasperi\OAuth2Server\Facades\AuthorizerFacade', -``` - -## Configuration Publishing - -In order to customize the behavior of this package, a configuration file to publish is provided to you. - -```bash -php artisan config:publish lucadegasperi/oauth2-server-laravel -``` - -Afterwards you can edit the file `app/config/packages/lucadegasperi/oauth2-server-laravel/oauth2.php` to suit your needs. A description of the configuration fields is [described here](https://github.com/lucadegasperi/oauth2-server-laravel/wiki/Configuration-Options). - -## Migrations - -This package comes with all the database tables you need to run a full featured OAuth 2.0 server. Run the migrations command to get them into your application installation - -```bash -php artisan oauth2-server:migrations -``` - -## Sample Controller - -To make your life easier, this package comes with a sample controller you can use to get started with your OAuth 2.0 Server. The `controller` command will publish the controller into your `app/controllers` directory. - -```bash -php artisan oauth2-server:controller -``` - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/laravel-5.md b/docs/getting-started/laravel-5.md deleted file mode 100644 index b5a87070..00000000 --- a/docs/getting-started/laravel-5.md +++ /dev/null @@ -1,54 +0,0 @@ -# Laravel 5 - -Composer is the recommended way to install this package. Add the following line to your `composer.json` file: - -```json -"lucadegasperi/oauth2-server-laravel": "5.0.*" -``` - -Then run `composer update` to get the package. - -Once composer has installed the package add this line of code to the `providers` array located in your `config/app.php` file: -```php -LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class, -LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class, -``` - -Add this line to the `aliases` array: -```php -'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class, -``` - -Add the following line to your `app/Http/Kernel.php` file in the `$middleware` array -```php -\LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class, -``` -This will catch any OAuth error and respond appropriately. - -Then add -```php -'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class, -'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class, -'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class, -'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class, -``` -to the `$routeMiddleware` array. - -In order to make some the authorization and resource server work correctly with Laravel5, remove the `App\Http\Middleware\VerifyCsrfToken` line from the `$middleware` array and place it in the `$routeMiddleware` array like this: `'csrf' => App\Http\Middleware\VerifyCsrfToken::class,` - -> **Note:** remember to add the csrf middleware manually on any route where it's appropriate. - -### Migrations and Configuration Publishing -Run `php artisan vendor:publish` to publish this package configuration and migrations. Afterwards you can edit the file `config/oauth2.php` to suit your needs. - -> **Note:** migrations are only published, remember to run them when ready. - -Run migration to create required tables - -```bash -php artisan migrate -``` - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/lumen.md b/docs/getting-started/lumen.md deleted file mode 100644 index bd23e2bd..00000000 --- a/docs/getting-started/lumen.md +++ /dev/null @@ -1,53 +0,0 @@ -# Lumen - -Composer is the recommended way to install this package. Add the following line to your composer.json file: - -```php -"lucadegasperi/oauth2-server-laravel": "^5.0" -``` -Then run composer update to get the package. - -### Register package - -In your `bootstrap/app.php` register service providers - -```php -$app->register(\LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class); -$app->register(\LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class); -``` - -... and middleware - -```php -$app->middleware([ - \LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class -]); -``` - -... and route middleware - -```php -$app->routeMiddleware([ - 'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class, - 'csrf' => \Laravel\Lumen\Http\Middleware\VerifyCsrfToken::class, - 'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class, - 'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class, - 'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class, -]); -``` - -### Copy config - -Copy `vendor/lucadegasperi/oauth2-server-laravel/config/oauth2.php` to your own config folder (`config/oauth2.php` in your project root). It has to be the correct config folder as it is registered using `$app->configure()`. - -### Migrate - -First copy the migrations from `vendor/lucadegasperi/oauth2-server-laravel/database/migrations` to your applications `database/migrations` directory. - -Uncomment `$app->withEloquent();` and run `php artisan migrate`. - -If you get an error saying the Config class can not be found, add `class_alias('Illuminate\Support\Facades\Config', 'Config');` to your `bootstrap/app.php` file and uncomment `$app->withFacades();` temporarily to import the migrations. - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/middlewares.md b/docs/getting-started/middlewares.md deleted file mode 100644 index 2870804d..00000000 --- a/docs/getting-started/middlewares.md +++ /dev/null @@ -1,39 +0,0 @@ -# Middlewares - -This package comes with four different middlewares to make the integration into Laravel much easier. - -### OAuthMiddleware - -This is the core middleware which should be used in almost all cases for authoring requests. - -### OAuthClientOwnerMiddleware - -Use this middleware to check if the current authorization request owner is of the type `client`. This middleware is associated with the `client_credentials` grant. - -### OAuthUserOwnerMiddleware - -Use this middleware to check if the current authorization request owner is of the type `user`. This middleware is associated with the `password` grant. - -> **Note:** this middleware is required in order to fetch the current resource owners ID. - -### CheckAuthCodeRequestMiddleware - -Use this middleware to check access tokens on the client after successfully authenticating the resource owner and obtaining authorization. This middleware is associated with the `authorization_code` grant. - -## Order - -Please note that the middlewares has to be applied in a certain order. The *OAuthMiddleware* has to be added before the `OAuthClientOwnerMiddleware` and the `OAuthUserOwnerMiddleware`. - -```php -public function __construct() -{ - $this->middleware('oauth'); - $this->middleware('oauth-user'); -} -``` - -If the middlewares isn't in the correct order, methods like the `Authorizer::getResourceOwnerId()` wont work. - ---- - -[← Back to start](../README.md) diff --git a/docs/getting-started/terminology.md b/docs/getting-started/terminology.md deleted file mode 100644 index 83d53032..00000000 --- a/docs/getting-started/terminology.md +++ /dev/null @@ -1,17 +0,0 @@ -# Terminology - -Before we dive into some code, here's a refresher on the meaning of the terms used by OAuth 2.0. - -Term | Description ------|----------- -Access token | A token used to access protected resources. -Authorization code | An intermediary token generated when a user authorizes a client to access protected resources on their behalf. The client receives this token and exchanges it for an access token. -Authorization server | A server which issues access tokens after successfully authenticating a client and resource owner, and authorizing the request. -Client | An application which accesses protected resources on behalf of the resource owner (such as a user). The client could be hosted on a server, desktop, mobile or other device. -Grant | A grant is a method of acquiring an access token. -Resource server | A server which sits in front of protected resources (for example "tweets", "users", "photos", or personal data) and is capable of accepting and responding to protected resource requests using access tokens. -Scope | A permission. - ---- - -[← Back to start](../README.md) diff --git a/docs/resource-server/securing-endpoints.md b/docs/resource-server/securing-endpoints.md deleted file mode 100644 index 83afd370..00000000 --- a/docs/resource-server/securing-endpoints.md +++ /dev/null @@ -1,48 +0,0 @@ -# Securing your API endpoints - -This package comes with a series of tools to help you protect your API endpoints using OAuth 2.0. This tools include the access token verification and the permissions verification. First let's talk about defining permissions (scopes). - -### Defining scopes - -In the context of OAuth, scopes are the part of your API, the client (the third-party application) is trying to access. You can think of them as a sort of permission the client asks to have. Scopes are completely arbitrary string you define. When using this package, all your scopes should be saved into the `oauth_scopes` table. -When a client asks for an access token he'll pass the scopes he needs in order to work. The authorization server will then verify the scopes exist and the client has the right to use them. - -> Using scopes is optional, but any non trivial application will benefit from them. - -### Checking the access token - -When requesting the resources of a protected endpoint the client should send an access token (previously issued to it) and the endpoint should check its validity. This is achieved by using the `oauth` middleware on any route of your API you want to protect with OAuth. - -```php -Route::get('protected-resource', ['middleware' => 'oauth', function() { - // return the protected resource -}]); -``` -This middleware will allow the access to the protected resource to any client with a valid access token. It will also send the client an error if he hasn't provided a valid access token. If you want to limit the access to the resource only to clients with certain permissions, here's where scopes come in handy. - -### Checking the scopes - -Every access token is tied to the client, the resource owner and the scopes it can access. To check if the client can access a resource with its permission, use the `oauth` middleware with the optional arguments. This will check the validity of the access token and the permissions. - -```php -Route::get('protected-resource', ['middleware' => 'oauth:scope1+scope2', function() { - // return the protected resource -}]); -``` -When at least one of the scope doesn't match the permissions the client has, the middleware will return an error to the client, informing it that it doesn't have the required permissions to access the endpoint. - -### Checking the access token owner - -When using the client_credentials grant type, the access token owner and the client can be the same entity to distinguish this particular case there's the `oauth-owner` middleware. Parameters for this middleware are either `client` or `user` - -### Finding access token owner - -```php -use LucaDegasperi\OAuth2Server\Facades\Authorizer; - -Authorizer::getResourceOwnerId(); -``` - ---- - -[← Back to start](../README.md) diff --git a/src/Authorizer.php b/src/Authorizer.php deleted file mode 100644 index 4dcc8495..00000000 --- a/src/Authorizer.php +++ /dev/null @@ -1,309 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server; - -use League\OAuth2\Server\AuthorizationServer as Issuer; -use League\OAuth2\Server\Exception\AccessDeniedException; -use League\OAuth2\Server\ResourceServer as Checker; -use League\OAuth2\Server\TokenType\TokenTypeInterface; -use League\OAuth2\Server\Util\RedirectUri; -use LucaDegasperi\OAuth2Server\Exceptions\NoActiveAccessTokenException; -use Symfony\Component\HttpFoundation\Request; - -/** - * This is the authorizer class. - * - * @author Luca Degasperi - */ -class Authorizer -{ - /** - * The authorization server (aka the issuer). - * - * @var \League\OAuth2\Server\AuthorizationServer - */ - protected $issuer; - - /** - * The resource server (aka the checker). - * - * @var \League\OAuth2\Server\ResourceServer - */ - protected $checker; - - /** - * The auth code request parameters. - * - * @var array - */ - protected $authCodeRequestParams; - - /** - * The redirect uri generator. - * - * @var bool|null - */ - protected $redirectUriGenerator = null; - - /** - * Create a new Authorizer instance. - * - * @param \League\OAuth2\Server\AuthorizationServer $issuer - * @param \League\OAuth2\Server\ResourceServer $checker - */ - public function __construct(Issuer $issuer, Checker $checker) - { - $this->issuer = $issuer; - $this->checker = $checker; - $this->authCodeRequestParams = []; - } - - /** - * Get the issuer. - * - * @return \League\OAuth2\Server\AuthorizationServer - */ - public function getIssuer() - { - return $this->issuer; - } - - /** - * Get the checker. - * - * @return \League\OAuth2\Server\ResourceServer - */ - public function getChecker() - { - return $this->checker; - } - - /** - * Get the current access token for the session. - * - * If the session does not have an active access token, an exception will be thrown. - * - * @throws \LucaDegasperi\OAuth2Server\Exceptions\NoActiveAccessTokenException - * - * @return \League\OAuth2\Server\Entity\AccessTokenEntity - */ - public function getAccessToken() - { - $accessToken = $this->getChecker()->getAccessToken(); - - if (is_null($accessToken)) { - throw new NoActiveAccessTokenException('Tried to access session data without an active access token'); - } - - return $accessToken; - } - - /** - * Issue an access token if the request parameters are valid. - * - * @return array a response object for the protocol in use - */ - public function issueAccessToken() - { - return $this->issuer->issueAccessToken(); - } - - /** - * Get the Auth Code request parameters. - * - * @return array - */ - public function getAuthCodeRequestParams() - { - return $this->authCodeRequestParams; - } - - /** - * Get a single parameter from the auth code request parameters. - * - * @param $key - * @param null $default - * - * @return mixed - */ - public function getAuthCodeRequestParam($key, $default = null) - { - if (array_key_exists($key, $this->authCodeRequestParams)) { - return $this->authCodeRequestParams[$key]; - } - - return $default; - } - - /** - * Check the validity of the auth code request. - * - * @return null a response appropriate for the protocol in use - */ - public function checkAuthCodeRequest() - { - $this->authCodeRequestParams = $this->issuer->getGrantType('authorization_code')->checkAuthorizeParams(); - } - - /** - * Issue an auth code. - * - * @param string $ownerType the auth code owner type - * @param string $ownerId the auth code owner id - * @param array $params additional parameters to merge - * - * @return string the auth code redirect url - */ - public function issueAuthCode($ownerType, $ownerId, $params = []) - { - $params = array_merge($this->authCodeRequestParams, $params); - - return $this->issuer->getGrantType('authorization_code')->newAuthorizeRequest($ownerType, $ownerId, $params); - } - - /** - * Generate a redirect uri when the auth code request is denied by the user. - * - * @return string a correctly formed url to redirect back to - */ - public function authCodeRequestDeniedRedirectUri() - { - $error = new AccessDeniedException(); - - return $this->getRedirectUriGenerator()->make($this->getAuthCodeRequestParam('redirect_uri'), [ - 'error' => $error->errorType, - 'error_description' => $error->getMessage(), - ] - ); - } - - /** - * get the RedirectUri generator instance. - * - * @return RedirectUri - */ - public function getRedirectUriGenerator() - { - if (is_null($this->redirectUriGenerator)) { - $this->redirectUriGenerator = new RedirectUri(); - } - - return $this->redirectUriGenerator; - } - - /** - * Set the RedirectUri generator instance. - * - * @param $redirectUri - */ - public function setRedirectUriGenerator($redirectUri) - { - $this->redirectUriGenerator = $redirectUri; - } - - /** - * Validate a request with an access token in it. - * - * @param bool $httpHeadersOnly whether or not to check only the http headers of the request - * @param string|null $accessToken an access token to validate - * - * @return mixed - */ - public function validateAccessToken($httpHeadersOnly = false, $accessToken = null) - { - return $this->checker->isValidRequest($httpHeadersOnly, $accessToken); - } - - /** - * get the scopes associated with the current request. - * - * @return array - */ - public function getScopes() - { - return $this->getAccessToken()->getScopes(); - } - - /** - * Check if the current request has all the scopes passed. - * - * @param string|array $scope the scope(s) to check for existence - * - * @return bool - */ - public function hasScope($scope) - { - if (is_array($scope)) { - foreach ($scope as $s) { - if ($this->hasScope($s) === false) { - return false; - } - } - - return true; - } - - return $this->getAccessToken()->hasScope($scope); - } - - /** - * Get the resource owner ID of the current request. - * - * @return string - */ - public function getResourceOwnerId() - { - return $this->getAccessToken()->getSession()->getOwnerId(); - } - - /** - * Get the resource owner type of the current request (client or user). - * - * @return string - */ - public function getResourceOwnerType() - { - return $this->getAccessToken()->getSession()->getOwnerType(); - } - - /** - * Get the client id of the current request. - * - * @return string - */ - public function getClientId() - { - return $this->checker->getAccessToken()->getSession()->getClient()->getId(); - } - - /** - * Set the request to use on the issuer and checker. - * - * @param \Symfony\Component\HttpFoundation\Request $request - */ - public function setRequest(Request $request) - { - $this->issuer->setRequest($request); - $this->checker->setRequest($request); - } - - /** - * Set the token type to use. - * - * @param \League\OAuth2\Server\TokenType\TokenTypeInterface $tokenType - */ - public function setTokenType(TokenTypeInterface $tokenType) - { - $this->issuer->setTokenType($tokenType); - $this->checker->setTokenType($tokenType); - } -} diff --git a/src/Exceptions/NoActiveAccessTokenException.php b/src/Exceptions/NoActiveAccessTokenException.php deleted file mode 100644 index 3546c53c..00000000 --- a/src/Exceptions/NoActiveAccessTokenException.php +++ /dev/null @@ -1,24 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Exceptions; - -use Exception; - -/** - * This is the no active access token exception class. - * - * @author Troy Pavlek - */ -class NoActiveAccessTokenException extends Exception -{ - // -} diff --git a/src/Facades/Authorizer.php b/src/Facades/Authorizer.php deleted file mode 100644 index 0ca046d1..00000000 --- a/src/Facades/Authorizer.php +++ /dev/null @@ -1,32 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Facades; - -use Illuminate\Support\Facades\Facade; - -/** - * This is the authorizer facade class. - * - * @author Luca Degasperi - */ -class Authorizer extends Facade -{ - /** - * Get the registered name of the component. - * - * @return string - */ - protected static function getFacadeAccessor() - { - return 'oauth2-server.authorizer'; - } -} diff --git a/src/Lumen/OAuth2ServerServiceProvider.php b/src/Lumen/OAuth2ServerServiceProvider.php deleted file mode 100644 index 897cff99..00000000 --- a/src/Lumen/OAuth2ServerServiceProvider.php +++ /dev/null @@ -1,26 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Lumen; - -use LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider as ServiceProvider; - -/** - * This is the Lumen oauth server service provider class. - * - * @deprecated since version 5.1. Use the base OAuth2ServerServiceProvider instead. - * - * @author Luca Degasperi - */ -class OAuth2ServerServiceProvider extends ServiceProvider -{ - // -} diff --git a/src/Middleware/CheckAuthCodeRequestMiddleware.php b/src/Middleware/CheckAuthCodeRequestMiddleware.php deleted file mode 100644 index 7e3318b9..00000000 --- a/src/Middleware/CheckAuthCodeRequestMiddleware.php +++ /dev/null @@ -1,57 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Middleware; - -use Closure; -use LucaDegasperi\OAuth2Server\Authorizer; - -/** - * This is the check auth code request middleware class. - * - * @author Luca Degasperi - */ -class CheckAuthCodeRequestMiddleware -{ - /** - * The authorizer instance. - * - * @var \LucaDegasperi\OAuth2Server\Authorizer - */ - protected $authorizer; - - /** - * Create a new check auth code request middleware instance. - * - * @param \LucaDegasperi\OAuth2Server\Authorizer $authorizer - */ - public function __construct(Authorizer $authorizer) - { - $this->authorizer = $authorizer; - } - - /** - * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * - * @return mixed - */ - public function handle($request, Closure $next) - { - $this->authorizer->setRequest($request); - - $this->authorizer->checkAuthCodeRequest(); - - return $next($request); - } -} diff --git a/src/Middleware/OAuthClientOwnerMiddleware.php b/src/Middleware/OAuthClientOwnerMiddleware.php deleted file mode 100644 index c1cf55e6..00000000 --- a/src/Middleware/OAuthClientOwnerMiddleware.php +++ /dev/null @@ -1,62 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Middleware; - -use Closure; -use League\OAuth2\Server\Exception\AccessDeniedException; -use LucaDegasperi\OAuth2Server\Authorizer; - -/** - * This is the oauth client middleware class. - * - * @author Vincent Klaiber - */ -class OAuthClientOwnerMiddleware -{ - /** - * The Authorizer instance. - * - * @var \LucaDegasperi\OAuth2Server\Authorizer - */ - protected $authorizer; - - /** - * Create a new oauth client middleware instance. - * - * @param \LucaDegasperi\OAuth2Server\Authorizer $authorizer - */ - public function __construct(Authorizer $authorizer) - { - $this->authorizer = $authorizer; - } - - /** - * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * - * @throws \League\OAuth2\Server\Exception\AccessDeniedException - * - * @return mixed - */ - public function handle($request, Closure $next) - { - $this->authorizer->setRequest($request); - - if ($this->authorizer->getResourceOwnerType() !== 'client') { - throw new AccessDeniedException(); - } - - return $next($request); - } -} diff --git a/src/Middleware/OAuthExceptionHandlerMiddleware.php b/src/Middleware/OAuthExceptionHandlerMiddleware.php deleted file mode 100644 index 003aaddc..00000000 --- a/src/Middleware/OAuthExceptionHandlerMiddleware.php +++ /dev/null @@ -1,46 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Middleware; - -use Closure; -use Illuminate\Http\JsonResponse; -use League\OAuth2\Server\Exception\OAuthException; - -/** - * This is the exception handler middleware class. - * - * @author Luca Degasperi - */ -class OAuthExceptionHandlerMiddleware -{ - /** - * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * - * @return mixed - */ - public function handle($request, Closure $next) - { - try { - return $next($request); - } catch (OAuthException $e) { - $data = [ - 'error' => $e->errorType, - 'error_description' => $e->getMessage(), - ]; - - return new JsonResponse($data, $e->httpStatusCode, $e->getHttpHeaders()); - } - } -} diff --git a/src/Middleware/OAuthMiddleware.php b/src/Middleware/OAuthMiddleware.php deleted file mode 100644 index 9f921a2f..00000000 --- a/src/Middleware/OAuthMiddleware.php +++ /dev/null @@ -1,91 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Middleware; - -use Closure; -use League\OAuth2\Server\Exception\InvalidScopeException; -use LucaDegasperi\OAuth2Server\Authorizer; - -/** - * This is the oauth middleware class. - * - * @author Luca Degasperi - */ -class OAuthMiddleware -{ - /** - * The Authorizer instance. - * - * @var \LucaDegasperi\OAuth2Server\Authorizer - */ - protected $authorizer; - - /** - * Whether or not to check the http headers only for an access token. - * - * @var bool - */ - protected $httpHeadersOnly = false; - - /** - * Create a new oauth middleware instance. - * - * @param \LucaDegasperi\OAuth2Server\Authorizer $authorizer - * @param bool $httpHeadersOnly - */ - public function __construct(Authorizer $authorizer, $httpHeadersOnly = false) - { - $this->authorizer = $authorizer; - $this->httpHeadersOnly = $httpHeadersOnly; - } - - /** - * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $scopesString - * - * @throws \League\OAuth2\Server\Exception\InvalidScopeException - * - * @return mixed - */ - public function handle($request, Closure $next, $scopesString = null) - { - $scopes = []; - - if (!is_null($scopesString)) { - $scopes = explode('+', $scopesString); - } - - $this->authorizer->setRequest($request); - - $this->authorizer->validateAccessToken($this->httpHeadersOnly); - $this->validateScopes($scopes); - - return $next($request); - } - - /** - * Validate the scopes. - * - * @param $scopes - * - * @throws \League\OAuth2\Server\Exception\InvalidScopeException - */ - public function validateScopes($scopes) - { - if (!empty($scopes) && !$this->authorizer->hasScope($scopes)) { - throw new InvalidScopeException(implode(',', $scopes)); - } - } -} diff --git a/src/Middleware/OAuthUserOwnerMiddleware.php b/src/Middleware/OAuthUserOwnerMiddleware.php deleted file mode 100644 index fd05929c..00000000 --- a/src/Middleware/OAuthUserOwnerMiddleware.php +++ /dev/null @@ -1,62 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Middleware; - -use Closure; -use League\OAuth2\Server\Exception\AccessDeniedException; -use LucaDegasperi\OAuth2Server\Authorizer; - -/** - * This is the oauth user middleware class. - * - * @author Vincent Klaiber - */ -class OAuthUserOwnerMiddleware -{ - /** - * The Authorizer instance. - * - * @var \LucaDegasperi\OAuth2Server\Authorizer - */ - protected $authorizer; - - /** - * Create a new oauth user middleware instance. - * - * @param \LucaDegasperi\OAuth2Server\Authorizer $authorizer - */ - public function __construct(Authorizer $authorizer) - { - $this->authorizer = $authorizer; - } - - /** - * Handle an incoming request. - * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * - * @throws \League\OAuth2\Server\Exception\AccessDeniedException - * - * @return mixed - */ - public function handle($request, Closure $next) - { - $this->authorizer->setRequest($request); - - if ($this->authorizer->getResourceOwnerType() !== 'user') { - throw new AccessDeniedException(); - } - - return $next($request); - } -} diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php deleted file mode 100644 index c5fd9dd2..00000000 --- a/src/OAuth2ServerServiceProvider.php +++ /dev/null @@ -1,199 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server; - -use Illuminate\Contracts\Foundation\Application; -use Illuminate\Foundation\Application as LaravelApplication; -use Illuminate\Support\ServiceProvider; -use Laravel\Lumen\Application as LumenApplication; -use League\OAuth2\Server\AuthorizationServer; -use League\OAuth2\Server\ResourceServer; -use League\OAuth2\Server\Storage\AccessTokenInterface; -use League\OAuth2\Server\Storage\AuthCodeInterface; -use League\OAuth2\Server\Storage\ClientInterface; -use League\OAuth2\Server\Storage\RefreshTokenInterface; -use League\OAuth2\Server\Storage\ScopeInterface; -use League\OAuth2\Server\Storage\SessionInterface; -use LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware; -use LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware; -use LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware; -use LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware; - -/** - * This is the oauth2 server service provider class. - * - * @author Luca Degasperi - */ -class OAuth2ServerServiceProvider extends ServiceProvider -{ - /** - * Boot the service provider. - * - * @return void - */ - public function boot() - { - $this->setupConfig($this->app); - $this->setupMigrations($this->app); - } - - /** - * Setup the config. - * - * @param \Illuminate\Contracts\Foundation\Application $app - * - * @return void - */ - protected function setupConfig(Application $app) - { - $source = realpath(__DIR__.'/../config/oauth2.php'); - - if ($app instanceof LaravelApplication && $app->runningInConsole()) { - $this->publishes([$source => config_path('oauth2.php')]); - } elseif ($app instanceof LumenApplication) { - $app->configure('oauth2'); - } - - $this->mergeConfigFrom($source, 'oauth2'); - } - - /** - * Setup the migrations. - * - * @param \Illuminate\Contracts\Foundation\Application $app - * - * @return void - */ - protected function setupMigrations(Application $app) - { - $source = realpath(__DIR__.'/../database/migrations/'); - - if ($app instanceof LaravelApplication && $app->runningInConsole()) { - $this->publishes([$source => database_path('migrations')], 'migrations'); - } - } - - /** - * Register the service provider. - * - * @return void - */ - public function register() - { - $this->registerAuthorizer($this->app); - $this->registerMiddlewareBindings($this->app); - } - - /** - * Register the Authorization server with the IoC container. - * - * @param \Illuminate\Contracts\Foundation\Application $app - * - * @return void - */ - public function registerAuthorizer(Application $app) - { - $app->singleton('oauth2-server.authorizer', function ($app) { - $config = $app['config']->get('oauth2'); - $issuer = $app->make(AuthorizationServer::class) - ->setClientStorage($app->make(ClientInterface::class)) - ->setSessionStorage($app->make(SessionInterface::class)) - ->setAuthCodeStorage($app->make(AuthCodeInterface::class)) - ->setAccessTokenStorage($app->make(AccessTokenInterface::class)) - ->setRefreshTokenStorage($app->make(RefreshTokenInterface::class)) - ->setScopeStorage($app->make(ScopeInterface::class)) - ->requireScopeParam($config['scope_param']) - ->setDefaultScope($config['default_scope']) - ->requireStateParam($config['state_param']) - ->setScopeDelimiter($config['scope_delimiter']) - ->setAccessTokenTTL($config['access_token_ttl']); - - // add the supported grant types to the authorization server - foreach ($config['grant_types'] as $grantIdentifier => $grantParams) { - $grant = $app->make($grantParams['class']); - $grant->setAccessTokenTTL($grantParams['access_token_ttl']); - - if (array_key_exists('callback', $grantParams)) { - list($className, $method) = array_pad(explode('@', $grantParams['callback']), 2, 'verify'); - $verifier = $app->make($className); - $grant->setVerifyCredentialsCallback([$verifier, $method]); - } - - if (array_key_exists('auth_token_ttl', $grantParams)) { - $grant->setAuthTokenTTL($grantParams['auth_token_ttl']); - } - - if (array_key_exists('refresh_token_ttl', $grantParams)) { - $grant->setRefreshTokenTTL($grantParams['refresh_token_ttl']); - } - - if (array_key_exists('rotate_refresh_tokens', $grantParams)) { - $grant->setRefreshTokenRotation($grantParams['rotate_refresh_tokens']); - } - - $issuer->addGrantType($grant); - } - - $checker = $app->make(ResourceServer::class); - - $authorizer = new Authorizer($issuer, $checker); - $authorizer->setRequest($app['request']); - $authorizer->setTokenType($app->make($config['token_type'])); - - $app->refresh('request', $authorizer, 'setRequest'); - - return $authorizer; - }); - - $app->alias('oauth2-server.authorizer', Authorizer::class); - } - - /** - * Register the Middleware to the IoC container because - * some middleware need additional parameters. - * - * @param \Illuminate\Contracts\Foundation\Application $app - * - * @return void - */ - public function registerMiddlewareBindings(Application $app) - { - $app->singleton(CheckAuthCodeRequestMiddleware::class, function ($app) { - return new CheckAuthCodeRequestMiddleware($app['oauth2-server.authorizer']); - }); - - $app->singleton(OAuthMiddleware::class, function ($app) { - $httpHeadersOnly = $app['config']->get('oauth2.http_headers_only'); - - return new OAuthMiddleware($app['oauth2-server.authorizer'], $httpHeadersOnly); - }); - - $app->singleton(OAuthClientOwnerMiddleware::class, function ($app) { - return new OAuthClientOwnerMiddleware($app['oauth2-server.authorizer']); - }); - - $app->singleton(OAuthUserOwnerMiddleware::class, function ($app) { - return new OAuthUserOwnerMiddleware($app['oauth2-server.authorizer']); - }); - } - - /** - * Get the services provided by the provider. - * - * @return string[] - * @codeCoverageIgnore - */ - public function provides() - { - return ['oauth2-server.authorizer']; - } -} diff --git a/src/Storage/AbstractFluentAdapter.php b/src/Storage/AbstractFluentAdapter.php deleted file mode 100644 index 13d52585..00000000 --- a/src/Storage/AbstractFluentAdapter.php +++ /dev/null @@ -1,90 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Illuminate\Database\ConnectionResolverInterface as Resolver; -use League\OAuth2\Server\Storage\AbstractStorage; - -/** - * This is the abstract fluent adapter class. - * - * @author Luca Degasperi - */ -abstract class AbstractFluentAdapter extends AbstractStorage -{ - /** - * The connection resolver instance. - * - * @var \Illuminate\Database\ConnectionResolverInterface - */ - protected $resolver; - - /** - * The connection name. - * - * @var string - */ - protected $connectionName; - - /** - * Create a new abstract fluent adapter instance. - * - * @param \Illuminate\Database\ConnectionResolverInterface $resolver - */ - public function __construct(Resolver $resolver) - { - $this->resolver = $resolver; - $this->connectionName = null; - } - - /** - * Set the resolver. - * - * @param \Illuminate\Database\ConnectionResolverInterface $resolver - */ - public function setResolver(Resolver $resolver) - { - $this->resolver = $resolver; - } - - /** - * Get the resolver. - * - * @return \Illuminate\Database\ConnectionResolverInterface - */ - public function getResolver() - { - return $this->resolver; - } - - /** - * Set the connection name. - * - * @param string $connectionName - * - * @return void - */ - public function setConnectionName($connectionName) - { - $this->connectionName = $connectionName; - } - - /** - * Get the connection. - * - * @return \Illuminate\Database\ConnectionInterface - */ - protected function getConnection() - { - return $this->resolver->connection($this->connectionName); - } -} diff --git a/src/Storage/FluentAccessToken.php b/src/Storage/FluentAccessToken.php deleted file mode 100644 index bcc4b74b..00000000 --- a/src/Storage/FluentAccessToken.php +++ /dev/null @@ -1,149 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Carbon\Carbon; -use League\OAuth2\Server\Entity\AccessTokenEntity; -use League\OAuth2\Server\Entity\ScopeEntity; -use League\OAuth2\Server\Storage\AccessTokenInterface; - -/** - * This is the fluent access token class. - * - * @author Luca Degasperi - */ -class FluentAccessToken extends AbstractFluentAdapter implements AccessTokenInterface -{ - /** - * Get an instance of Entities\AccessToken. - * - * @param string $token The access token - * - * @return null|AbstractTokenEntity - */ - public function get($token) - { - $result = $this->getConnection()->table('oauth_access_tokens') - ->where('oauth_access_tokens.id', $token) - ->first(); - - if (is_null($result)) { - return; - } - - return (new AccessTokenEntity($this->getServer())) - ->setId($result->id) - ->setExpireTime((int) $result->expire_time); - } - - /* - public function getByRefreshToken(RefreshTokenEntity $refreshToken) - { - $result = $this->getConnection()->table('oauth_access_tokens') - ->select('oauth_access_tokens.*') - ->join('oauth_refresh_tokens', 'oauth_access_tokens.id', '=', 'oauth_refresh_tokens.access_token_id') - ->where('oauth_refresh_tokens.id', $refreshToken->getId()) - ->first(); - - if (is_null($result)) { - return null; - } - - return (new AccessTokenEntity($this->getServer())) - ->setId($result->id) - ->setExpireTime((int)$result->expire_time); - } - */ - - /** - * Get the scopes for an access token. - * - * @param \League\OAuth2\Server\Entity\AccessTokenEntity $token The access token - * - * @return array Array of \League\OAuth2\Server\Entity\ScopeEntity - */ - public function getScopes(AccessTokenEntity $token) - { - $result = $this->getConnection()->table('oauth_access_token_scopes') - ->select('oauth_scopes.*') - ->join('oauth_scopes', 'oauth_access_token_scopes.scope_id', '=', 'oauth_scopes.id') - ->where('oauth_access_token_scopes.access_token_id', $token->getId()) - ->get(); - - $scopes = []; - - foreach ($result as $scope) { - $scopes[] = (new ScopeEntity($this->getServer()))->hydrate([ - 'id' => $scope->id, - 'description' => $scope->description, - ]); - } - - return $scopes; - } - - /** - * Creates a new access token. - * - * @param string $token The access token - * @param int $expireTime The expire time expressed as a unix timestamp - * @param string|int $sessionId The session ID - * - * @return \League\OAuth2\Server\Entity\AccessTokenEntity - */ - public function create($token, $expireTime, $sessionId) - { - $this->getConnection()->table('oauth_access_tokens')->insert([ - 'id' => $token, - 'expire_time' => $expireTime, - 'session_id' => $sessionId, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - - return (new AccessTokenEntity($this->getServer())) - ->setId($token) - ->setExpireTime((int) $expireTime); - } - - /** - * Associate a scope with an access token. - * - * @param \League\OAuth2\Server\Entity\AccessTokenEntity $token The access token - * @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope - * - * @return void - */ - public function associateScope(AccessTokenEntity $token, ScopeEntity $scope) - { - $this->getConnection()->table('oauth_access_token_scopes')->insert([ - 'access_token_id' => $token->getId(), - 'scope_id' => $scope->getId(), - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - } - - /** - * Delete an access token. - * - * @param \League\OAuth2\Server\Entity\AccessTokenEntity $token The access token to delete - * - * @return void - */ - public function delete(AccessTokenEntity $token) - { - $this->getConnection()->table('oauth_access_tokens') - ->where('oauth_access_tokens.id', $token->getId()) - ->delete(); - } -} diff --git a/src/Storage/FluentAuthCode.php b/src/Storage/FluentAuthCode.php deleted file mode 100644 index 9f5c94d6..00000000 --- a/src/Storage/FluentAuthCode.php +++ /dev/null @@ -1,130 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Carbon\Carbon; -use League\OAuth2\Server\Entity\AuthCodeEntity; -use League\OAuth2\Server\Entity\ScopeEntity; -use League\OAuth2\Server\Storage\AuthCodeInterface; - -/** - * This is the fluent auth code class. - * - * @author Luca Degasperi - */ -class FluentAuthCode extends AbstractFluentAdapter implements AuthCodeInterface -{ - /** - * Get the auth code. - * - * @param string $code - * - * @return \League\OAuth2\Server\Entity\AuthCodeEntity - */ - public function get($code) - { - $result = $this->getConnection()->table('oauth_auth_codes') - ->where('oauth_auth_codes.id', $code) - ->where('oauth_auth_codes.expire_time', '>=', time()) - ->first(); - - if (is_null($result)) { - return; - } - - return (new AuthCodeEntity($this->getServer())) - ->setId($result->id) - ->setRedirectUri($result->redirect_uri) - ->setExpireTime((int) $result->expire_time); - } - - /** - * Get the scopes for an access token. - * - * @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code - * - * @return array Array of \League\OAuth2\Server\Entity\ScopeEntity - */ - public function getScopes(AuthCodeEntity $token) - { - $result = $this->getConnection()->table('oauth_auth_code_scopes') - ->select('oauth_scopes.*') - ->join('oauth_scopes', 'oauth_auth_code_scopes.scope_id', '=', 'oauth_scopes.id') - ->where('oauth_auth_code_scopes.auth_code_id', $token->getId()) - ->get(); - - $scopes = []; - - foreach ($result as $scope) { - $scopes[] = (new ScopeEntity($this->getServer()))->hydrate([ - 'id' => $scope->id, - 'description' => $scope->description, - ]); - } - - return $scopes; - } - - /** - * Associate a scope with an access token. - * - * @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code - * @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope - * - * @return void - */ - public function associateScope(AuthCodeEntity $token, ScopeEntity $scope) - { - $this->getConnection()->table('oauth_auth_code_scopes')->insert([ - 'auth_code_id' => $token->getId(), - 'scope_id' => $scope->getId(), - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - } - - /** - * Delete an access token. - * - * @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The access token to delete - * - * @return void - */ - public function delete(AuthCodeEntity $token) - { - $this->getConnection()->table('oauth_auth_codes') - ->where('oauth_auth_codes.id', $token->getId()) - ->delete(); - } - - /** - * Create an auth code. - * - * @param string $token The token ID - * @param int $expireTime Token expire time - * @param int $sessionId Session identifier - * @param string $redirectUri Client redirect uri - * - * @return void - */ - public function create($token, $expireTime, $sessionId, $redirectUri) - { - $this->getConnection()->table('oauth_auth_codes')->insert([ - 'id' => $token, - 'session_id' => $sessionId, - 'redirect_uri' => $redirectUri, - 'expire_time' => $expireTime, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - } -} diff --git a/src/Storage/FluentClient.php b/src/Storage/FluentClient.php deleted file mode 100644 index 32df5127..00000000 --- a/src/Storage/FluentClient.php +++ /dev/null @@ -1,190 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Carbon\Carbon; -use Illuminate\Database\ConnectionResolverInterface as Resolver; -use League\OAuth2\Server\Entity\ClientEntity; -use League\OAuth2\Server\Entity\SessionEntity; -use League\OAuth2\Server\Storage\ClientInterface; - -/** - * This is the fluent client class. - * - * @author Luca Degasperi - */ -class FluentClient extends AbstractFluentAdapter implements ClientInterface -{ - /** - * Limit clients to grants. - * - * @var bool - */ - protected $limitClientsToGrants = false; - - /** - * Create a new fluent client instance. - * - * @param \Illuminate\Database\ConnectionResolverInterface $resolver - * @param bool $limitClientsToGrants - */ - public function __construct(Resolver $resolver, $limitClientsToGrants = false) - { - parent::__construct($resolver); - $this->limitClientsToGrants = $limitClientsToGrants; - } - - /** - * Check if clients are limited to grants. - * - * @return bool - */ - public function areClientsLimitedToGrants() - { - return $this->limitClientsToGrants; - } - - /** - * Whether or not to limit clients to grants. - * - * @param bool $limit - */ - public function limitClientsToGrants($limit = false) - { - $this->limitClientsToGrants = $limit; - } - - /** - * Get the client. - * - * @param string $clientId - * @param string $clientSecret - * @param string $redirectUri - * @param string $grantType - * - * @return null|\League\OAuth2\Server\Entity\ClientEntity - */ - public function get($clientId, $clientSecret = null, $redirectUri = null, $grantType = null) - { - $query = null; - - if (!is_null($redirectUri) && is_null($clientSecret)) { - $query = $this->getConnection()->table('oauth_clients') - ->select( - 'oauth_clients.id as id', - 'oauth_clients.secret as secret', - 'oauth_client_endpoints.redirect_uri as redirect_uri', - 'oauth_clients.name as name') - ->join('oauth_client_endpoints', 'oauth_clients.id', '=', 'oauth_client_endpoints.client_id') - ->where('oauth_clients.id', $clientId) - ->where('oauth_client_endpoints.redirect_uri', $redirectUri); - } elseif (!is_null($clientSecret) && is_null($redirectUri)) { - $query = $this->getConnection()->table('oauth_clients') - ->select( - 'oauth_clients.id as id', - 'oauth_clients.secret as secret', - 'oauth_clients.name as name') - ->where('oauth_clients.id', $clientId) - ->where('oauth_clients.secret', $clientSecret); - } elseif (!is_null($clientSecret) && !is_null($redirectUri)) { - $query = $this->getConnection()->table('oauth_clients') - ->select( - 'oauth_clients.id as id', - 'oauth_clients.secret as secret', - 'oauth_client_endpoints.redirect_uri as redirect_uri', - 'oauth_clients.name as name') - ->join('oauth_client_endpoints', 'oauth_clients.id', '=', 'oauth_client_endpoints.client_id') - ->where('oauth_clients.id', $clientId) - ->where('oauth_clients.secret', $clientSecret) - ->where('oauth_client_endpoints.redirect_uri', $redirectUri); - } - - if ($this->limitClientsToGrants === true && !is_null($grantType)) { - $query = $query->join('oauth_client_grants', 'oauth_clients.id', '=', 'oauth_client_grants.client_id') - ->join('oauth_grants', 'oauth_grants.id', '=', 'oauth_client_grants.grant_id') - ->where('oauth_grants.id', $grantType); - } - - $result = $query->first(); - - if (is_null($result)) { - return; - } - - return $this->hydrateEntity($result); - } - - /** - * Get the client associated with a session. - * - * @param \League\OAuth2\Server\Entity\SessionEntity $session The session - * - * @return null|\League\OAuth2\Server\Entity\ClientEntity - */ - public function getBySession(SessionEntity $session) - { - $result = $this->getConnection()->table('oauth_clients') - ->select( - 'oauth_clients.id as id', - 'oauth_clients.secret as secret', - 'oauth_clients.name as name') - ->join('oauth_sessions', 'oauth_sessions.client_id', '=', 'oauth_clients.id') - ->where('oauth_sessions.id', '=', $session->getId()) - ->first(); - - if (is_null($result)) { - return; - } - - return $this->hydrateEntity($result); - } - - /** - * Create a new client. - * - * @param string $name The client's unique name - * @param string $id The client's unique id - * @param string $secret The clients' unique secret - * - * @return string - */ - public function create($name, $id, $secret) - { - return $this->getConnection()->table('oauth_clients')->insertGetId([ - 'id' => $id, - 'name' => $name, - 'secret' => $secret, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - } - - /** - * Hydrate the entity. - * - * @param $result - * - * @return \League\OAuth2\Server\Entity\ClientEntity - */ - protected function hydrateEntity($result) - { - $client = new ClientEntity($this->getServer()); - $client->hydrate([ - 'id' => $result->id, - 'name' => $result->name, - 'secret' => $result->secret, - 'redirectUri' => (isset($result->redirect_uri) ? $result->redirect_uri : null), - ]); - - return $client; - } -} diff --git a/src/Storage/FluentRefreshToken.php b/src/Storage/FluentRefreshToken.php deleted file mode 100644 index 2b0b53a3..00000000 --- a/src/Storage/FluentRefreshToken.php +++ /dev/null @@ -1,87 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Carbon\Carbon; -use League\OAuth2\Server\Entity\RefreshTokenEntity; -use League\OAuth2\Server\Storage\RefreshTokenInterface; - -/** - * This is the fluent refresh token class. - * - * @author Luca Degasperi - */ -class FluentRefreshToken extends AbstractFluentAdapter implements RefreshTokenInterface -{ - /** - * Return a new instance of \League\OAuth2\Server\Entity\RefreshTokenEntity. - * - * @param string $token - * - * @return \League\OAuth2\Server\Entity\RefreshTokenEntity - */ - public function get($token) - { - $result = $this->getConnection()->table('oauth_refresh_tokens') - ->where('oauth_refresh_tokens.id', $token) - ->where('oauth_refresh_tokens.expire_time', '>=', time()) - ->first(); - - if (is_null($result)) { - return; - } - - return (new RefreshTokenEntity($this->getServer())) - ->setId($result->id) - ->setAccessTokenId($result->access_token_id) - ->setExpireTime((int) $result->expire_time); - } - - /** - * Create a new refresh token_name. - * - * @param string $token - * @param int $expireTime - * @param string $accessToken - * - * @return \League\OAuth2\Server\Entity\RefreshTokenEntity - */ - public function create($token, $expireTime, $accessToken) - { - $this->getConnection()->table('oauth_refresh_tokens')->insert([ - 'id' => $token, - 'expire_time' => $expireTime, - 'access_token_id' => $accessToken, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - - return (new RefreshTokenEntity($this->getServer())) - ->setId($token) - ->setAccessTokenId($accessToken) - ->setExpireTime((int) $expireTime); - } - - /** - * Delete the refresh token. - * - * @param \League\OAuth2\Server\Entity\RefreshTokenEntity $token - * - * @return void - */ - public function delete(RefreshTokenEntity $token) - { - $this->getConnection()->table('oauth_refresh_tokens') - ->where('id', $token->getId()) - ->delete(); - } -} diff --git a/src/Storage/FluentScope.php b/src/Storage/FluentScope.php deleted file mode 100644 index 0956fcf4..00000000 --- a/src/Storage/FluentScope.php +++ /dev/null @@ -1,139 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Illuminate\Database\ConnectionResolverInterface as Resolver; -use League\OAuth2\Server\Entity\ScopeEntity; -use League\OAuth2\Server\Storage\ScopeInterface; - -/** - * This is the fluent scope class. - * - * @author Luca Degasperi - */ -class FluentScope extends AbstractFluentAdapter implements ScopeInterface -{ - /* - * Limit clients to scopes. - * - * @var bool - */ - protected $limitClientsToScopes = false; - - /* - * Limit scopes to grants. - * - * @var bool - */ - protected $limitScopesToGrants = false; - - /** - * Create a new fluent scope instance. - * - * @param \Illuminate\Database\ConnectionResolverInterface $resolver - * @param bool|false $limitClientsToScopes - * @param bool|false $limitScopesToGrants - */ - public function __construct(Resolver $resolver, $limitClientsToScopes = false, $limitScopesToGrants = false) - { - parent::__construct($resolver); - $this->limitClientsToScopes = $limitClientsToScopes; - $this->limitScopesToGrants = $limitScopesToGrants; - } - - /** - * Set limit clients to scopes. - * - * @param bool|false $limit - */ - public function limitClientsToScopes($limit = false) - { - $this->limitClientsToScopes = $limit; - } - - /** - * Set limit scopes to grants. - * - * @param bool|false $limit - */ - public function limitScopesToGrants($limit = false) - { - $this->limitScopesToGrants = $limit; - } - - /** - * Check if clients are limited to scopes. - * - * @return bool|false - */ - public function areClientsLimitedToScopes() - { - return $this->limitClientsToScopes; - } - - /** - * Check if scopes are limited to grants. - * - * @return bool|false - */ - public function areScopesLimitedToGrants() - { - return $this->limitScopesToGrants; - } - - /** - * Return information about a scope. - * - * Example SQL query: - * - * - * SELECT * FROM oauth_scopes WHERE scope = :scope - * - * - * @param string $scope The scope - * @param string $grantType The grant type used in the request (default = "null") - * @param string $clientId The client id used for the request (default = "null") - * - * @return \League\OAuth2\Server\Entity\ScopeEntity|null If the scope doesn't exist return false - */ - public function get($scope, $grantType = null, $clientId = null) - { - $query = $this->getConnection()->table('oauth_scopes') - ->select('oauth_scopes.id as id', 'oauth_scopes.description as description') - ->where('oauth_scopes.id', $scope); - - if ($this->limitClientsToScopes === true && !is_null($clientId)) { - $query = $query->join('oauth_client_scopes', 'oauth_scopes.id', '=', 'oauth_client_scopes.scope_id') - ->where('oauth_client_scopes.client_id', $clientId); - } - - if ($this->limitScopesToGrants === true && !is_null($grantType)) { - $query = $query->join('oauth_grant_scopes', 'oauth_scopes.id', '=', 'oauth_grant_scopes.scope_id') - ->join('oauth_grants', 'oauth_grants.id', '=', 'oauth_grant_scopes.grant_id') - ->where('oauth_grants.id', $grantType); - } - - $result = $query->first(); - - if (is_null($result)) { - return; - } - - $scope = new ScopeEntity($this->getServer()); - $scope->hydrate([ - 'id' => $result->id, - 'description' => $result->description, - ]); - - return $scope; - } -} diff --git a/src/Storage/FluentSession.php b/src/Storage/FluentSession.php deleted file mode 100644 index cecc6a0e..00000000 --- a/src/Storage/FluentSession.php +++ /dev/null @@ -1,165 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Carbon\Carbon; -use League\OAuth2\Server\Entity\AccessTokenEntity; -use League\OAuth2\Server\Entity\AuthCodeEntity; -use League\OAuth2\Server\Entity\ScopeEntity; -use League\OAuth2\Server\Entity\SessionEntity; -use League\OAuth2\Server\Storage\SessionInterface; - -/** - * This is the fluent session class. - * - * @author Luca Degasperi - */ -class FluentSession extends AbstractFluentAdapter implements SessionInterface -{ - /** - * Get a session from it's identifier. - * - * @param string $sessionId - * - * @return \League\OAuth2\Server\Entity\SessionEntity - */ - public function get($sessionId) - { - $result = $this->getConnection()->table('oauth_sessions') - ->where('oauth_sessions.id', $sessionId) - ->first(); - - if (is_null($result)) { - return; - } - - return (new SessionEntity($this->getServer())) - ->setId($result->id) - ->setOwner($result->owner_type, $result->owner_id); - } - - /** - * Get a session from an access token. - * - * @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token - * - * @return \League\OAuth2\Server\Entity\SessionEntity - */ - public function getByAccessToken(AccessTokenEntity $accessToken) - { - $result = $this->getConnection()->table('oauth_sessions') - ->select('oauth_sessions.*') - ->join('oauth_access_tokens', 'oauth_sessions.id', '=', 'oauth_access_tokens.session_id') - ->where('oauth_access_tokens.id', $accessToken->getId()) - ->first(); - - if (is_null($result)) { - return; - } - - return (new SessionEntity($this->getServer())) - ->setId($result->id) - ->setOwner($result->owner_type, $result->owner_id); - } - - /** - * Get a session's scopes. - * - * @param \League\OAuth2\Server\Entity\SessionEntity - * - * @return array Array of \League\OAuth2\Server\Entity\ScopeEntity - */ - public function getScopes(SessionEntity $session) - { - // TODO: Check this before pushing - $result = $this->getConnection()->table('oauth_session_scopes') - ->select('oauth_scopes.*') - ->join('oauth_scopes', 'oauth_session_scopes.scope_id', '=', 'oauth_scopes.id') - ->where('oauth_session_scopes.session_id', $session->getId()) - ->get(); - - $scopes = []; - - foreach ($result as $scope) { - $scopes[] = (new ScopeEntity($this->getServer()))->hydrate([ - 'id' => $scope->id, - 'description' => $scope->description, - ]); - } - - return $scopes; - } - - /** - * Create a new session. - * - * @param string $ownerType Session owner's type (user, client) - * @param string $ownerId Session owner's ID - * @param string $clientId Client ID - * @param string $clientRedirectUri Client redirect URI (default = null) - * - * @return int The session's ID - */ - public function create($ownerType, $ownerId, $clientId, $clientRedirectUri = null) - { - return $this->getConnection()->table('oauth_sessions')->insertGetId([ - 'client_id' => $clientId, - 'owner_type' => $ownerType, - 'owner_id' => $ownerId, - 'client_redirect_uri' => $clientRedirectUri, - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - } - - /** - * Associate a scope with a session. - * - * @param \League\OAuth2\Server\Entity\SessionEntity $session - * @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scopes ID might be an integer or string - * - * @return void - */ - public function associateScope(SessionEntity $session, ScopeEntity $scope) - { - $this->getConnection()->table('oauth_session_scopes')->insert([ - 'session_id' => $session->getId(), - 'scope_id' => $scope->getId(), - 'created_at' => Carbon::now(), - 'updated_at' => Carbon::now(), - ]); - } - - /** - * Get a session from an auth code. - * - * @param \League\OAuth2\Server\Entity\AuthCodeEntity $authCode The auth code - * - * @return \League\OAuth2\Server\Entity\SessionEntity - */ - public function getByAuthCode(AuthCodeEntity $authCode) - { - $result = $this->getConnection()->table('oauth_sessions') - ->select('oauth_sessions.*') - ->join('oauth_auth_codes', 'oauth_sessions.id', '=', 'oauth_auth_codes.session_id') - ->where('oauth_auth_codes.id', $authCode->getId()) - ->first(); - - if (is_null($result)) { - return; - } - - return (new SessionEntity($this->getServer())) - ->setId($result->id) - ->setOwner($result->owner_type, $result->owner_id); - } -} diff --git a/src/Storage/FluentStorageServiceProvider.php b/src/Storage/FluentStorageServiceProvider.php deleted file mode 100644 index 18b61421..00000000 --- a/src/Storage/FluentStorageServiceProvider.php +++ /dev/null @@ -1,132 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Storage; - -use Illuminate\Contracts\Foundation\Application; -use Illuminate\Support\ServiceProvider; -use League\OAuth2\Server\Storage\AccessTokenInterface; -use League\OAuth2\Server\Storage\AuthCodeInterface; -use League\OAuth2\Server\Storage\ClientInterface; -use League\OAuth2\Server\Storage\RefreshTokenInterface; -use League\OAuth2\Server\Storage\ScopeInterface; -use League\OAuth2\Server\Storage\SessionInterface; - -/** - * This is the fluent storage service provider class. - * - * @author Luca Degasperi - */ -class FluentStorageServiceProvider extends ServiceProvider -{ - /** - * Bootstrap the application events. - * - * @return void - */ - public function boot() - { - // - } - - /** - * Register the service provider. - * - * @return void - */ - public function register() - { - $this->registerStorageBindings($this->app); - $this->registerInterfaceBindings($this->app); - } - - /** - * Bind the storage implementations to the IoC container. - * - * @param \Illuminate\Contracts\Foundation\Application $app - * - * @return void - */ - public function registerStorageBindings(Application $app) - { - $provider = $this; - - $app->singleton(FluentAccessToken::class, function () use ($provider) { - $storage = new FluentAccessToken($provider->app['db']); - $storage->setConnectionName($provider->getConnectionName()); - - return $storage; - }); - - $app->singleton(FluentAuthCode::class, function () use ($provider) { - $storage = new FluentAuthCode($provider->app['db']); - $storage->setConnectionName($provider->getConnectionName()); - - return $storage; - }); - - $app->singleton(FluentClient::class, function ($app) use ($provider) { - $limitClientsToGrants = $app['config']->get('oauth2.limit_clients_to_grants'); - $storage = new FluentClient($provider->app['db'], $limitClientsToGrants); - $storage->setConnectionName($provider->getConnectionName()); - - return $storage; - }); - - $app->singleton(FluentRefreshToken::class, function () use ($provider) { - $storage = new FluentRefreshToken($provider->app['db']); - $storage->setConnectionName($provider->getConnectionName()); - - return $storage; - }); - - $app->singleton(FluentScope::class, function ($app) use ($provider) { - $limitClientsToScopes = $app['config']->get('oauth2.limit_clients_to_scopes'); - $limitScopesToGrants = $app['config']->get('oauth2.limit_scopes_to_grants'); - $storage = new FluentScope($provider->app['db'], $limitClientsToScopes, $limitScopesToGrants); - $storage->setConnectionName($provider->getConnectionName()); - - return $storage; - }); - - $app->singleton(FluentSession::class, function () use ($provider) { - $storage = new FluentSession($provider->app['db']); - $storage->setConnectionName($provider->getConnectionName()); - - return $storage; - }); - } - - /** - * Bind the interfaces to their implementations. - * - * @param \Illuminate\Contracts\Foundation\Application $app - * - * @return void - */ - public function registerInterfaceBindings(Application $app) - { - $app->bind(ClientInterface::class, FluentClient::class); - $app->bind(ScopeInterface::class, FluentScope::class); - $app->bind(SessionInterface::class, FluentSession::class); - $app->bind(AuthCodeInterface::class, FluentAuthCode::class); - $app->bind(AccessTokenInterface::class, FluentAccessToken::class); - $app->bind(RefreshTokenInterface::class, FluentRefreshToken::class); - } - - /** - * @return string - */ - public function getConnectionName() - { - return ($this->app['config']->get('oauth2.database') !== 'default') ? $this->app['config']->get('oauth2.database') : null; - } -} diff --git a/tests/AbstractTestCase.php b/tests/AbstractTestCase.php deleted file mode 100644 index c0bc342a..00000000 --- a/tests/AbstractTestCase.php +++ /dev/null @@ -1,46 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Orchestra\Testbench\TestCase as OrchestraTestCase; - -abstract class AbstractTestCase extends OrchestraTestCase -{ - public function setUp() - { - parent::setUp(); - } - - /** - * Get base path. - * - * @return string - */ - protected function getBasePath() - { - // reset base path to point to our package's src directory - return __DIR__.'/../vendor/orchestra/testbench/fixture'; - } - - protected function getPackageProviders($app) - { - return [ - 'LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider', - 'LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider', - ]; - } - - protected function getPackageAliases($app) - { - return [ - 'Authorizer' => 'LucaDegasperi\OAuth2Server\Facades\Authorizer', - ]; - } -} diff --git a/tests/Database/Seeders/AccessTokensTableSeeder.php b/tests/Database/Seeders/AccessTokensTableSeeder.php deleted file mode 100644 index 10f27cea..00000000 --- a/tests/Database/Seeders/AccessTokensTableSeeder.php +++ /dev/null @@ -1,45 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class AccessTokensTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_access_tokens')->delete(); - - $datetime = Carbon::now(); - - $tokens = [ - [ - 'id' => 'totallyanaccesstoken1', - 'session_id' => 1, - 'expire_time' => time() + 60, - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'id' => 'totallyanaccesstoken2', - 'session_id' => 2, - 'expire_time' => time() + 120, - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_access_tokens')->insert($tokens); - } -} diff --git a/tests/Database/Seeders/AuthCodesTableSeeder.php b/tests/Database/Seeders/AuthCodesTableSeeder.php deleted file mode 100644 index 4ff71776..00000000 --- a/tests/Database/Seeders/AuthCodesTableSeeder.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class AuthCodesTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_auth_codes')->delete(); - - $datetime = Carbon::now(); - - $codes = [ - [ - 'id' => 'totallyanauthcode1', - 'session_id' => 1, - 'redirect_uri' => 'https://example1.com/', - 'expire_time' => time() + 60, - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'id' => 'totallyanauthcode2', - 'session_id' => 2, - 'redirect_uri' => 'https://example2.com/', - 'expire_time' => time() + 120, - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_auth_codes')->insert($codes); - } -} diff --git a/tests/Database/Seeders/ClientsTableSeeder.php b/tests/Database/Seeders/ClientsTableSeeder.php deleted file mode 100644 index 98b3c9b4..00000000 --- a/tests/Database/Seeders/ClientsTableSeeder.php +++ /dev/null @@ -1,64 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class ClientsTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_clients')->delete(); - - $datetime = Carbon::now(); - - $clients = [ - [ - 'id' => 'client1id', - 'secret' => 'client1secret', - 'name' => 'client1', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'id' => 'client2id', - 'secret' => 'client2secret', - 'name' => 'client2', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_clients')->insert($clients); - - DB::table('oauth_client_endpoints')->delete(); - - $clientEndpoints = [ - [ - 'client_id' => 'client1id', - 'redirect_uri' => 'http://example1.com/callback', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'client_id' => 'client2id', - 'redirect_uri' => 'http://example2.com/callback', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_client_endpoints')->insert($clientEndpoints); - } -} diff --git a/tests/Database/Seeders/GrantsTableSeeder.php b/tests/Database/Seeders/GrantsTableSeeder.php deleted file mode 100644 index e938893c..00000000 --- a/tests/Database/Seeders/GrantsTableSeeder.php +++ /dev/null @@ -1,60 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class GrantsTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_grants')->delete(); - - $datetime = Carbon::now(); - - $grants = [ - [ - 'id' => 'grant1', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'id' => 'grant2', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_grants')->insert($grants); - - DB::table('oauth_client_grants')->delete(); - - $clientGrants = [ - [ - 'client_id' => 'client1id', - 'grant_id' => 'grant1', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'client_id' => 'client2id', - 'grant_id' => 'grant2', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_client_grants')->insert($clientGrants); - } -} diff --git a/tests/Database/Seeders/OAuth2DatabaseSeeder.php b/tests/Database/Seeders/OAuth2DatabaseSeeder.php deleted file mode 100644 index 3c256c94..00000000 --- a/tests/Database/Seeders/OAuth2DatabaseSeeder.php +++ /dev/null @@ -1,43 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\App; - -class OAuth2DatabaseSeeder extends Seeder -{ - /** - * Run the database seeds. - * - * @return void - */ - public function run() - { - if (App::environment() === 'production') { - exit('I just stopped you getting fired. Love Luca'); - } - - Model::unguard(); - - $this->call(ClientsTableSeeder::class); - $this->call(GrantsTableSeeder::class); - $this->call(ScopesTableSeeder::class); - $this->call(SessionsTableSeeder::class); - $this->call(AuthCodesTableSeeder::class); - $this->call(AccessTokensTableSeeder::class); - $this->call(RefreshTokensTableSeeder::class); - - Model::reguard(); - } -} diff --git a/tests/Database/Seeders/RefreshTokensTableSeeder.php b/tests/Database/Seeders/RefreshTokensTableSeeder.php deleted file mode 100644 index 351232ff..00000000 --- a/tests/Database/Seeders/RefreshTokensTableSeeder.php +++ /dev/null @@ -1,38 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class RefreshTokensTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_refresh_tokens')->delete(); - - $datetime = Carbon::now(); - - $tokens = [ - [ - 'id' => 'totallyarefreshtoken1', - 'access_token_id' => 'totallyanaccesstoken1', - 'expire_time' => time() + 60, - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_refresh_tokens')->insert($tokens); - } -} diff --git a/tests/Database/Seeders/ScopesTableSeeder.php b/tests/Database/Seeders/ScopesTableSeeder.php deleted file mode 100644 index b8b6bc48..00000000 --- a/tests/Database/Seeders/ScopesTableSeeder.php +++ /dev/null @@ -1,81 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class ScopesTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_scopes')->delete(); - - $datetime = Carbon::now(); - - $scopes = [ - [ - 'id' => 'scope1', - 'description' => 'Scope 1 Description', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'id' => 'scope2', - 'description' => 'Scope 2 Description', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_scopes')->insert($scopes); - - DB::table('oauth_client_scopes')->delete(); - - $clientScopes = [ - [ - 'client_id' => 'client1id', - 'scope_id' => 'scope1', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'client_id' => 'client2id', - 'scope_id' => 'scope2', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_client_scopes')->insert($clientScopes); - - DB::table('oauth_grant_scopes')->delete(); - - $grantScopes = [ - [ - 'grant_id' => 'grant1', - 'scope_id' => 'scope1', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'grant_id' => 'grant2', - 'scope_id' => 'scope2', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_grant_scopes')->insert($grantScopes); - } -} diff --git a/tests/Database/Seeders/SessionsTableSeeder.php b/tests/Database/Seeders/SessionsTableSeeder.php deleted file mode 100644 index 7e36cc0f..00000000 --- a/tests/Database/Seeders/SessionsTableSeeder.php +++ /dev/null @@ -1,45 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace LucaDegasperi\OAuth2Server\Tests\Database\Seeders; - -use Carbon\Carbon; -use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; - -class SessionsTableSeeder extends Seeder -{ - public function run() - { - DB::table('oauth_sessions')->delete(); - - $datetime = Carbon::now(); - - $sessions = [ - [ - 'client_id' => 'client1id', - 'owner_id' => '1', - 'owner_type' => 'user', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - [ - 'client_id' => 'client2id', - 'owner_id' => '2', - 'owner_type' => 'user', - 'created_at' => $datetime, - 'updated_at' => $datetime, - ], - ]; - - DB::table('oauth_sessions')->insert($sessions); - } -} diff --git a/tests/functional/bootstrap/FeatureContext.php b/tests/functional/bootstrap/FeatureContext.php deleted file mode 100644 index 9b010a11..00000000 --- a/tests/functional/bootstrap/FeatureContext.php +++ /dev/null @@ -1,161 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Behat\Behat\Exception\PendingException; -use League\OAuth2\Server\Grant\ClientCredentialsGrant; -use LucaDegasperi\OAuth2Server\Tests\Database\Seeders\OAuth2DatabaseSeeder; -use Orchestra\Testbench\BehatFeatureContext; -use PHPUnit_Framework_Assert as PHPUnit; - -/** - * Features context. - */ -class FeatureContext extends BehatFeatureContext -{ - /** @BeforeScenario */ - public function up() - { - $this->migrateAndSeed(); - } - - /** @AfterScenario */ - public function down() - { - $this->resetMigrations(); - } - - /** - * @Given /^An authorization server exists that supports the "([^"]*)" grant type$/ - */ - public function anAuthorizationServerExistsThatSupportsTheGrantType($arg1) - { - $clientCredentialsGrant = new ClientCredentialsGrant(); - $this->app['oauth2-server.authorizer']->getIssuer()->addGrantType($clientCredentialsGrant); - - $this->app['router']->enableFilters(); - $this->app['router']->post('oauth/access_token', 'OAuthController@postAccessToken'); - } - - /** - * @Given /^I have invalid client credentials$/ - */ - public function iHaveInvalidClientCredentials() - { - //throw new PendingException(); - } - - /** - * @When /^I post to the "([^"]*)" page "([^"]*)" "([^"]*)" "([^"]*)"$/ - */ - public function iPostToThePage($pageName, $grantType, $clientId, $clientSecret) - { - $params = [ - 'grant_type' => $grantType, - 'client_id' => $clientId, - 'client_secret' => $clientSecret, - ]; - $this->app['env'] = 'functional'; - $this->call('POST', $pageName, $params); - } - - /** - * @Then /^I should get an "([^"]*)" error$/ - */ - public function iShouldGetAnError($arg1) - { - $this->assertResponseStatus(401); - $content = json_decode($this->client->getResponse()->getContent()); - PHPUnit::assertEquals('invalid_client', $content->error); - } - - /** - * @Given /^I have valid client credentials$/ - */ - public function iHaveValidClientCredentials() - { - //throw new PendingException(); - } - - /** - * @Then /^I should get an access token\.$/ - */ - public function iShouldGetAnAccessToken() - { - $this->assertResponseStatus(200); - $content = json_decode($this->client->getResponse()->getContent(), true); - PHPUnit::assertArrayHasKey('access_token', $content); - PHPUnit::assertArrayHasKey('expires_in', $content); - PHPUnit::assertArrayHasKey('token_type', $content); - PHPUnit::assertEquals('Bearer', $content['token_type']); - } - - protected $artisan; - - /** - * Get package aliases. - * - * @return array - */ - protected function getPackageAliases() - { - return [ - 'Authorizer' => 'LucaDegasperi\OAuth2Server\Facades\AuthorizerFacade', - ]; - } - - /** - * Get package providers. - * - * @return array - */ - protected function getPackageProviders() - { - return [ - 'LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider', - 'LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider', - ]; - } - - /** - * Define environment setup. - * - * @param \Illuminate\Foundation\Application $app - * - * @return void - */ - protected function getEnvironmentSetUp($app) - { - $app['path.base'] = __DIR__.'/../../../src'; - $app['config']->set('database.default', 'testbench'); - $app['config']->set('database.connections.testbench', [ - 'driver' => 'sqlite', - 'database' => ':memory:', - 'prefix' => '', - ]); - $this->artisan = $app->make('artisan'); - } - - public function migrateAndSeed() - { - $this->artisan->call('migrate', [ - '--database' => 'testbench', - '--path' => '../src/migrations', - ]); - $this->artisan->call('db:seed', [ - '--class' => OAuth2DatabaseSeeder::class, - ]); - } - - public function resetMigrations() - { - $this->artisan->call('migrate:reset'); - } -} diff --git a/tests/functional/bootstrap/OAuthController.php b/tests/functional/bootstrap/OAuthController.php deleted file mode 100644 index f0ca2851..00000000 --- a/tests/functional/bootstrap/OAuthController.php +++ /dev/null @@ -1,55 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Illuminate\Routing\Controller; -use LucaDegasperi\OAuth2Server\Authorizer; - -class OAuthController extends Controller -{ - protected $authorizer; - - public function __construct(Authorizer $authorizer) - { - $this->authorizer = $authorizer; - - $this->beforeFilter('auth', ['only' => ['getAuthorize', 'postAuthorize']]); - $this->beforeFilter('csrf', ['only' => 'postAuthorize']); - $this->beforeFilter('check-authorization-params', ['only' => ['getAuthorize', 'postAuthorize']]); - } - - public function postAccessToken() - { - return Response::json($this->authorizer->issueAccessToken()); - } - - public function getAuthorize() - { - return View::make('authorization-form', $this->authorizer->getAuthCodeRequestParams()); - } - - public function postAuthorize() - { - // get the user id - $params['user_id'] = Auth::user()->id; - - $redirectUri = ''; - - if (Input::get('approve') !== null) { - $redirectUri = $this->authorizer->issueAuthCode('user', $params['user_id'], $params); - } - - if (Input::get('deny') !== null) { - $redirectUri = $this->authorizer->authCodeRequestDeniedRedirectUri(); - } - - return Redirect::to($redirectUri); - } -} diff --git a/tests/functional/clientcredentials.feature b/tests/functional/clientcredentials.feature deleted file mode 100644 index feeebc1f..00000000 --- a/tests/functional/clientcredentials.feature +++ /dev/null @@ -1,25 +0,0 @@ -Feature: Client Credentials Authorization - In order to gain access to an api - As a client - I want to be able to exchange my credentials for an access token - - Background: - Given An authorization server exists that supports the "client_credentials" grant type - - Scenario Outline: With invalid credentials I won't get an access token - Given I have invalid client credentials - When I post to the "oauth/access_token" page - Then I should get an "invalid_client" error - - Examples: - | grant_type | client_id | client_secret | - | "client_credentials" | "invalid" | "invalid" | - - Scenario Outline: With valid client credentials I should get an access token - Given I have valid client credentials - When I post to the "oauth/access_token" page - Then I should get an access token. - - Examples: - | grant_type | client_id | client_secret | - | "client_credentials" | "client1id" | "client1secret" | \ No newline at end of file diff --git a/tests/integration/AbstractDBTestCase.php b/tests/integration/AbstractDBTestCase.php deleted file mode 100644 index 4414a865..00000000 --- a/tests/integration/AbstractDBTestCase.php +++ /dev/null @@ -1,48 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Tests\Database\Seeders\OAuth2DatabaseSeeder; - -abstract class AbstractDBTestCase extends AbstractTestCase -{ - protected $artisan; - - public function setUp() - { - parent::setUp(); - - $this->artisan = $this->app->make('Illuminate\Contracts\Console\Kernel'); - $this->artisan->call('migrate', [ - '--database' => 'testbench', - '--path' => '../../../../database/migrations', - ]); - $this->artisan->call('db:seed', [ - '--class' => OAuth2DatabaseSeeder::class, - ]); - } - - protected function getEnvironmentSetUp($app) - { - parent::getEnvironmentSetUp($app); - - $app['config']->set('database.default', 'testbench'); - $app['config']->set('database.connections.testbench', [ - 'driver' => 'sqlite', - 'database' => ':memory:', - 'prefix' => '', - ]); - } - - public function tearDown() - { - //$this->artisan->call('migrate:reset'); - } -} diff --git a/tests/integration/FluentAccessTokenTest.php b/tests/integration/FluentAccessTokenTest.php deleted file mode 100644 index 18e136c7..00000000 --- a/tests/integration/FluentAccessTokenTest.php +++ /dev/null @@ -1,129 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Storage\FluentAccessToken; -use Mockery as m; - -class FluentAccessTokenTest extends AbstractDBTestCase -{ - public function getAccessTokenRepository() - { - $server = m::mock('League\OAuth2\Server\AbstractServer'); - $repo = new FluentAccessToken($this->app['db']); - $repo->setServer($server); - - return $repo; - } - - public function test_it_fetches_an_access_token_object_with_a_valid_token() - { - $repo = $this->getAccessTokenRepository(); - - $result = $repo->get('totallyanaccesstoken1'); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\AccessTokenEntity', $result); - $this->assertEquals('totallyanaccesstoken1', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - } - - public function test_it_returns_null_with_an_invalid_token() - { - $repo = $this->getAccessTokenRepository(); - - $result = $repo->get('invalid_auth_code'); - - $this->assertNull($result); - } - - /*public function test_it_fetches_an_access_token_object_with_a_valid_refresh_token() - { - $token = m::mock('League\OAuth2\Server\Entity\RefreshTokenEntity'); - $token->shouldReceive('getId')->once()->andReturn('totallyarefreshtoken1'); - - $repo = $this->getAccessTokenRepository(); - - $result = $repo->getByRefreshToken($token); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\AccessTokenEntity', $result); - $this->assertEquals('totallyanaccesstoken1', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - } - - public function test_it_returns_null_with_an_invalid_refresh_token() - { - $token = m::mock('League\OAuth2\Server\Entity\RefreshTokenEntity'); - $token->shouldReceive('getId')->once()->andReturn('notarefreshtoken'); - - $repo = $this->getAccessTokenRepository(); - - $result = $repo->getByRefreshToken($token); - - $this->assertNull($result); - }*/ - - public function test_it_deletes_an_access_token() - { - $token = m::mock('League\OAuth2\Server\Entity\AccessTokenEntity'); - $token->shouldReceive('getId')->once()->andReturn('totallyanaccesstoken1'); - - $repo = $this->getAccessTokenRepository(); - - $repo->delete($token); - $result = $repo->get('totallyanaccesstoken1'); - - $this->assertNull($result); - } - - public function test_it_associates_scopes() - { - $token = m::mock('League\OAuth2\Server\Entity\AccessTokenEntity'); - $token->shouldReceive('getId')->times(4)->andReturn('totallyanaccesstoken1'); - - $scope1 = m::mock('League\OAuth2\Server\Entity\ScopeEntity'); - $scope1->shouldReceive('getId')->once()->andReturn('scope1'); - - $scope2 = m::mock('League\OAuth2\Server\Entity\ScopeEntity'); - $scope2->shouldReceive('getId')->once()->andReturn('scope2'); - - $repo = $this->getAccessTokenRepository(); - - $result1 = $repo->getScopes($token); - - $repo->associateScope($token, $scope1); - $repo->associateScope($token, $scope1); - - $result2 = $repo->getScopes($token); - - $this->assertInternalType('array', $result1); - $this->assertEquals(0, count($result1)); - - $this->assertInternalType('array', $result2); - $this->assertEquals(2, count($result2)); - - $first = $result2[0]; - - $this->assertInstanceOf('League\OAuth2\Server\Entity\ScopeEntity', $first); - $this->assertEquals('scope1', $first->getId()); - } - - public function test_it_creates_an_access_token() - { - $repo = $this->getAccessTokenRepository(); - - $time = time() + 120; - $result = $repo->create('accesstoken', $time, 1); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\AccessTokenEntity', $result); - $this->assertEquals('accesstoken', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - $this->assertEquals($time, $result->getExpireTime()); - } -} diff --git a/tests/integration/FluentAuthCodeTest.php b/tests/integration/FluentAuthCodeTest.php deleted file mode 100644 index e443a840..00000000 --- a/tests/integration/FluentAuthCodeTest.php +++ /dev/null @@ -1,105 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Storage\FluentAuthCode; -use Mockery as m; - -class FluentAuthCodeTest extends AbstractDBTestCase -{ - public function getAuthCodeRepository() - { - $server = m::mock('League\OAuth2\Server\AbstractServer'); - $repo = new FluentAuthCode($this->app['db']); - $repo->setServer($server); - - return $repo; - } - - public function test_it_fetches_an_auth_code_with_a_valid_code() - { - $repo = $this->getAuthCodeRepository(); - - $result = $repo->get('totallyanauthcode1'); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\AuthCodeEntity', $result); - $this->assertEquals('totallyanauthcode1', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - } - - public function test_it_returns_null_with_an_invalid_code() - { - $repo = $this->getAuthCodeRepository(); - - $result = $repo->get('invalid_auth_code'); - - $this->assertNull($result); - } - - public function test_it_deletes_an_auth_code() - { - $code = m::mock('League\OAuth2\Server\Entity\AuthCodeEntity'); - $code->shouldReceive('getId')->once()->andReturn('totallyanauthcode1'); - - $repo = $this->getAuthCodeRepository(); - - $repo->delete($code); - $result = $repo->get('totallyanauthcode1'); - - $this->assertNull($result); - } - - public function test_it_associates_scopes() - { - $code = m::mock('League\OAuth2\Server\Entity\AuthCodeEntity'); - $code->shouldReceive('getId')->times(4)->andReturn('totallyanauthcode1'); - - $scope1 = m::mock('League\OAuth2\Server\Entity\ScopeEntity'); - $scope1->shouldReceive('getId')->once()->andReturn('scope1'); - - $scope2 = m::mock('League\OAuth2\Server\Entity\ScopeEntity'); - $scope2->shouldReceive('getId')->once()->andReturn('scope2'); - - $repo = $this->getAuthCodeRepository(); - - $result1 = $repo->getScopes($code); - - $repo->associateScope($code, $scope1); - $repo->associateScope($code, $scope1); - - $result2 = $repo->getScopes($code); - - $this->assertInternalType('array', $result1); - $this->assertEquals(0, count($result1)); - - $this->assertInternalType('array', $result2); - $this->assertEquals(2, count($result2)); - - $first = $result2[0]; - - $this->assertInstanceOf('League\OAuth2\Server\Entity\ScopeEntity', $first); - $this->assertEquals('scope1', $first->getId()); - } - - public function test_it_creates_an_auth_code() - { - $repo = $this->getAuthCodeRepository(); - - $time = time() + 120; - $repo->create('newauthcode', $time, 1, 'http://example1.com'); - $result = $repo->get('newauthcode'); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\AuthCodeEntity', $result); - $this->assertEquals('newauthcode', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - $this->assertEquals($time, $result->getExpireTime()); - $this->assertEquals('http://example1.com', $result->getRedirectUri()); - } -} diff --git a/tests/integration/FluentClientTest.php b/tests/integration/FluentClientTest.php deleted file mode 100644 index 6a97324d..00000000 --- a/tests/integration/FluentClientTest.php +++ /dev/null @@ -1,124 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Storage\FluentClient; -use Mockery as m; - -class FluentClientTest extends AbstractDBTestCase -{ - public function getClientRepository() - { - $server = m::mock('League\OAuth2\Server\AbstractServer'); - $repo = new FluentClient($this->app['db']); - $repo->setServer($server); - - return $repo; - } - - public function test_get_client_with_secret_only() - { - // arrange - $repo = $this->getClientRepository(); - - // act - $client = $repo->get('client1id', 'client1secret'); - - // assert - $this->assertIsClient($client, false); - } - - public function test_get_client_with_redirect_uri_only() - { - $repo = $this->getClientRepository(); - $client = $repo->get('client1id', null, 'http://example1.com/callback'); - - $this->assertIsClient($client); - } - - public function test_get_client_with_secret_and_redirect_uri() - { - $repo = $this->getClientRepository(); - - $client = $repo->get('client1id', 'client1secret', 'http://example1.com/callback'); - - $this->assertIsClient($client); - } - - public function test_null_is_returned_with_unexisting_client() - { - $repo = $this->getClientRepository(); - - $result1 = $repo->get('client3id', 'client3secret'); - $result2 = $repo->get('client3id', null, 'http://example3.com/callback'); - $result3 = $repo->get('client3id', 'client3secret', 'http://example3.com/callback'); - - $this->assertNull($result1); - $this->assertNull($result2); - $this->assertNull($result3); - } - - public function test_false_is_returned_with_invalid_grant() - { - $repo = $this->getClientRepository(); - $repo->limitClientsToGrants(true); - - $result = $repo->get('client1id', 'client1secret', 'http://example1.com/callback', 'grant2'); - - $this->assertTrue($repo->areClientsLimitedToGrants()); - $this->assertNull($result); - } - - public function test_client_is_returned_with_valid_grant() - { - $repo = $this->getClientRepository(); - $repo->limitClientsToGrants(true); - - $client = $repo->get('client1id', 'client1secret', 'http://example1.com/callback', 'grant1'); - - $this->assertTrue($repo->areClientsLimitedToGrants()); - $this->assertIsClient($client); - } - - public function test_it_returns_a_client_associated_with_a_valid_session() - { - $repo = $this->getClientRepository(); - - $session = m::mock('League\OAuth2\Server\Entity\SessionEntity'); - $session->shouldReceive('getId')->once()->andReturn(1); - - $result = $repo->getBySession($session); - $this->assertIsClient($result, false); - } - - public function test_it_returns_null_with_an_invalid_session() - { - $repo = $this->getClientRepository(); - - $session = m::mock('League\OAuth2\Server\Entity\SessionEntity'); - $session->shouldReceive('getId')->once()->andReturn(20); - - $result = $repo->getBySession($session); - $this->assertNull($result); - } - - public function assertIsClient($client, $redirectUri = true) - { - $this->assertInstanceOf('League\OAuth2\Server\Entity\ClientEntity', $client); - $this->assertEquals('client1id', $client->getId()); - $this->assertEquals('client1secret', $client->getSecret()); - $this->assertEquals('client1', $client->getName()); - if ($redirectUri) { - $this->assertEquals('http://example1.com/callback', $client->getRedirectUri()); - } else { - $this->assertNull($client->getRedirectUri()); - } - } -} diff --git a/tests/integration/FluentRefreshTokenTest.php b/tests/integration/FluentRefreshTokenTest.php deleted file mode 100644 index 245fbe71..00000000 --- a/tests/integration/FluentRefreshTokenTest.php +++ /dev/null @@ -1,71 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Storage\FluentRefreshToken; -use Mockery as m; - -class FluentRefreshTokenTest extends AbstractDBTestCase -{ - public function getRefreshTokenRepository() - { - $server = m::mock('League\OAuth2\Server\AbstractServer'); - $repo = new FluentRefreshToken($this->app['db']); - $repo->setServer($server); - - return $repo; - } - - public function test_it_fetches_a_refresh_token_with_a_valid_token() - { - $repo = $this->getRefreshTokenRepository(); - - $result = $repo->get('totallyarefreshtoken1'); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\RefreshTokenEntity', $result); - $this->assertEquals('totallyarefreshtoken1', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - } - - public function test_it_returns_null_with_an_invalid_token() - { - $repo = $this->getRefreshTokenRepository(); - - $result = $repo->get('invalid_refresh_token'); - - $this->assertNull($result); - } - - public function test_it_deletes_a_refresh_token() - { - $token = m::mock('League\OAuth2\Server\Entity\RefreshTokenEntity'); - $token->shouldReceive('getId')->once()->andReturn('totallyarefreshtoken1'); - - $repo = $this->getRefreshTokenRepository(); - - $repo->delete($token); - $result = $repo->get('totallyarefreshtoken1'); - - $this->assertNull($result); - } - - public function test_it_creates_a_refresh_token() - { - $repo = $this->getRefreshTokenRepository(); - - $time = time() + 120; - $result = $repo->create('newrefreshtoken', $time, 'totallyanaccesstoken2'); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\RefreshTokenEntity', $result); - $this->assertEquals('newrefreshtoken', $result->getId()); - $this->assertInternalType('int', $result->getExpireTime()); - $this->assertEquals($time, $result->getExpireTime()); - } -} diff --git a/tests/integration/FluentScopeTest.php b/tests/integration/FluentScopeTest.php deleted file mode 100644 index b4654bdb..00000000 --- a/tests/integration/FluentScopeTest.php +++ /dev/null @@ -1,108 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Storage\FluentScope; -use Mockery as m; - -class FluentScopeTest extends AbstractDBTestCase -{ - public function getScopeRepository() - { - $server = m::mock('League\OAuth2\Server\AbstractServer'); - $repo = new FluentScope($this->app['db']); - $repo->setServer($server); - - return $repo; - } - - public function test_get_unexisting_scope() - { - $repo = $this->getScopeRepository(); - $repo->limitClientsToScopes(true); - $repo->limitScopesToGrants(true); - - $result = $repo->get('scope3', 'grant3', 'client3id'); - - $this->assertTrue($repo->areClientsLimitedToScopes()); - $this->assertTrue($repo->areScopesLimitedToGrants()); - $this->assertNull($result); - } - - public function test_get_scope_with_client_only() - { - $repo = $this->getScopeRepository(); - $repo->limitClientsToScopes(true); - - $result = $repo->get('scope1', null, 'client1id'); - - $this->assertIsScope($result); - } - - public function test_get_scope_with_invalid_client_only() - { - $repo = $this->getScopeRepository(); - $repo->limitClientsToScopes(true); - - $result = $repo->get('scope1', null, 'invalidclientid'); - - $this->assertTrue($repo->areClientsLimitedToScopes()); - $this->assertNull($result); - } - - public function test_get_scope_with_grant_only() - { - $repo = $this->getScopeRepository(); - $repo->limitScopesToGrants(true); - - $result = $repo->get('scope1', 'grant1'); - - $this->assertIsScope($result); - } - - public function test_get_scope_with_invalid_grant_only() - { - $repo = $this->getScopeRepository(); - $repo->limitScopesToGrants(true); - - $result = $repo->get('scope1', 'invalidgrant'); - - $this->assertTrue($repo->areScopesLimitedToGrants()); - $this->assertNull($result); - } - - public function test_get_scope_with_client_and_grant() - { - $repo = $this->getScopeRepository(); - $repo->limitClientsToScopes(true); - $repo->limitScopesToGrants(true); - - $result = $repo->get('scope1', 'grant1', 'client1id'); - - $this->assertTrue($repo->areClientsLimitedToScopes()); - $this->assertTrue($repo->areScopesLimitedToGrants()); - $this->assertIsScope($result); - } - - public function test_get_scope() - { - $repo = $this->getScopeRepository(); - $result = $repo->get('scope1'); - - $this->assertIsScope($result); - } - - public function assertIsScope($result) - { - $this->assertInstanceOf('League\OAuth2\Server\Entity\ScopeEntity', $result); - $this->assertEquals('scope1', $result->getId()); - $this->assertEquals('Scope 1 Description', $result->getDescription()); - } -} diff --git a/tests/integration/FluentSessionTest.php b/tests/integration/FluentSessionTest.php deleted file mode 100644 index 83c55a8a..00000000 --- a/tests/integration/FluentSessionTest.php +++ /dev/null @@ -1,138 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use LucaDegasperi\OAuth2Server\Storage\FluentSession; -use Mockery as m; - -class FluentSessionTest extends AbstractDBTestCase -{ - public function getSessionRepository() - { - $emitter = m::mock('League\Event\Emitter'); - $emitter->shouldReceive('emit')->once(); - $server = m::mock('League\OAuth2\Server\AbstractServer'); - $server->shouldReceive('getEventEmitter')->once()->andReturn($emitter); - $repo = new FluentSession($this->app['db']); - $repo->setServer($server); - - return $repo; - } - - public function test_session_is_created() - { - $repo = $this->getSessionRepository(); - - $id = $repo->create('user', '1', 'client1'); - $session = $repo->get($id); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\SessionEntity', $session); - $this->assertEquals('user', $session->getOwnerType()); - $this->assertEquals('1', $session->getOwnerId()); - } - - public function test_null_is_returned_when_invalid_session_is_requested() - { - $repo = $this->getSessionRepository(); - $session = $repo->get(20); - $this->assertNull($session); - } - - public function test_scope_is_associated() - { - $session = m::mock('League\OAuth2\Server\Entity\SessionEntity'); - $session->shouldReceive('getId')->twice()->andReturn(1); - - $scope1 = m::mock('League\OAuth2\Server\Entity\ScopeEntity'); - $scope1->shouldReceive('getId')->once()->andReturn('scope1'); - - $scope2 = m::mock('League\OAuth2\Server\Entity\ScopeEntity'); - $scope2->shouldReceive('getId')->once()->andReturn('scope2'); - - $repo = $this->getSessionRepository(); - - $repo->associateScope($session, $scope1); - $repo->associateScope($session, $scope2); - - $result = $repo->getScopes($session); - - $this->assertInternalType('array', $result); - $this->assertEquals(2, count($result)); - $first = $result[0]; - $this->assertInstanceOf('League\OAuth2\Server\Entity\ScopeEntity', $first); - } - - public function test_null_is_returned_when_session_is_requested_by_invalid_auth_code() - { - $authCode = m::mock('League\OAuth2\Server\Entity\AuthCodeEntity'); - $authCode->shouldReceive('getId')->once()->andReturn('unexistingcode'); - - $repo = $this->getSessionRepository(); - - $result = $repo->getByAuthCode($authCode); - - $this->assertNull($result); - } - - public function test_a_session_is_returned_when_session_is_requested_by_valid_auth_code() - { - $authCode = m::mock('League\OAuth2\Server\Entity\AuthCodeEntity'); - $authCode->shouldReceive('getId')->once()->andReturn('totallyanauthcode1'); - - $repo = $this->getSessionRepository(); - - $session = $repo->getByAuthCode($authCode); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\SessionEntity', $session); - $this->assertEquals('user', $session->getOwnerType()); - $this->assertEquals('1', $session->getOwnerId()); - } - - public function test_null_is_returned_when_session_is_requested_by_invalid_access_token() - { - $accessToken = m::mock('League\OAuth2\Server\Entity\AccessTokenEntity'); - $accessToken->shouldReceive('getId')->once()->andReturn('unexistingaccesstoken'); - - $repo = $this->getSessionRepository(); - - $result = $repo->getByAccessToken($accessToken); - - $this->assertNull($result); - } - - public function test_a_session_is_returned_when_session_is_requested_by_valid_access_token() - { - $accessToken = m::mock('League\OAuth2\Server\Entity\AccessTokenEntity'); - $accessToken->shouldReceive('getId')->once()->andReturn('totallyanaccesstoken1'); - - $repo = $this->getSessionRepository(); - - $session = $repo->getByAccessToken($accessToken); - - $this->assertInstanceOf('League\OAuth2\Server\Entity\SessionEntity', $session); - $this->assertEquals('user', $session->getOwnerType()); - $this->assertEquals('1', $session->getOwnerId()); - } - - /*public function test_session_is_deleted() - { - $repo = new FluentSession(); - - $repo->delete('client1id', 'user', '1'); - - $session = DB::table('oauth_sessions') - ->where('client_id', '=', 'client1id') - ->where('owner_type', '=', 'user') - ->where('owner_id', '=', '1') - ->first(); - - $this->assertNull($session, 'no session found'); - }*/ -} diff --git a/tests/unit/LucaDegasperi/OAuth2Server/AuthorizerSpec.php b/tests/unit/LucaDegasperi/OAuth2Server/AuthorizerSpec.php deleted file mode 100644 index 57b3c68c..00000000 --- a/tests/unit/LucaDegasperi/OAuth2Server/AuthorizerSpec.php +++ /dev/null @@ -1,189 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace unit\LucaDegasperi\OAuth2Server; - -use League\OAuth2\Server\AuthorizationServer; -use League\OAuth2\Server\Entity\AccessTokenEntity; -use League\OAuth2\Server\Entity\ClientEntity; -use League\OAuth2\Server\Entity\SessionEntity; -use League\OAuth2\Server\Grant\AuthCodeGrant; -use League\OAuth2\Server\ResourceServer; -use League\OAuth2\Server\Util\RedirectUri; -use LucaDegasperi\OAuth2Server\Exceptions\NoActiveAccessTokenException; -use PhpSpec\ObjectBehavior; -use Symfony\Component\HttpFoundation\Request; - -class AuthorizerSpec extends ObjectBehavior -{ - public function let(AuthorizationServer $issuer, ResourceServer $checker) - { - $this->beConstructedWith($issuer, $checker); - } - - public function it_is_initializable() - { - $this->shouldHaveType('LucaDegasperi\OAuth2Server\Authorizer'); - } - - public function it_issues_an_access_token(AuthorizationServer $issuer) - { - $issuer->issueAccessToken()->willReturn('foo')->shouldBeCalled(); - - $this->issueAccessToken()->shouldReturn('foo'); - } - - public function it_checks_the_auth_code_request_parameters(AuthorizationServer $issuer, AuthCodeGrant $authCodeGrant) - { - $authCodeGrant->checkAuthorizeParams()->willReturn(['foo' => 'bar'])->shouldBeCalled(); - $issuer->getGrantType('authorization_code')->willReturn($authCodeGrant)->shouldBeCalled(); - - $this->checkAuthCodeRequest()->shouldReturn(null); - $this->getAuthCodeRequestParams()->shouldBe(['foo' => 'bar']); - $this->getAuthCodeRequestParam('foo')->shouldBe('bar'); - } - - public function it_issues_an_auth_code(AuthorizationServer $issuer, AuthCodeGrant $authCodeGrant) - { - $authCodeGrant->newAuthorizeRequest('user', '1', ['foo' => 'bar'])->willReturn('baz')->shouldBeCalled(); - $issuer->getGrantType('authorization_code')->willReturn($authCodeGrant)->shouldBeCalled(); - - $this->issueAuthCode('user', '1', ['foo' => 'bar'])->shouldReturn('baz'); - } - - public function it_returns_the_current_scopes(ResourceServer $checker, AccessTokenEntity $accessTokenEntity) - { - $accessTokenEntity->getScopes()->willReturn(['foo', 'bar']); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->getScopes()->shouldReturn(['foo', 'bar']); - } - - public function it_throws_exception_if_current_scopes_accessed_without_active_access_token(ResourceServer $checker) - { - $checker->getAccessToken()->willReturn(null); - $this->shouldThrow(NoActiveAccessTokenException::class)->during('getScopes'); - } - - public function it_checks_if_a_scope_is_included_into_the_current_ones(ResourceServer $checker, AccessTokenEntity $accessTokenEntity) - { - $accessTokenEntity->hasScope('foo')->willReturn(true)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->hasScope('foo')->shouldReturn(true); - - $accessTokenEntity->hasScope('foo')->willReturn(false)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->hasScope('foo')->shouldReturn(false); - } - - public function it_checks_if_multiple_invalid_scopes_are_included_into_the_current_ones(ResourceServer $checker, AccessTokenEntity $accessTokenEntity) - { - $accessTokenEntity->hasScope('foo')->willReturn(false)->shouldBecalled(); - $accessTokenEntity->hasScope('bar')->willReturn(false)->shouldNotBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->hasScope(['foo', 'bar'])->shouldReturn(false); - } - - public function it_checks_if_multiple_mixed_scopes_are_included_into_the_current_ones(ResourceServer $checker, AccessTokenEntity $accessTokenEntity) - { - $accessTokenEntity->hasScope('foo')->willReturn(true)->shouldBecalled(); - $accessTokenEntity->hasScope('bar')->willReturn(false)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalledTimes(2); - $this->hasScope(['foo', 'bar'])->shouldReturn(false); - } - - public function it_checks_if_multiple_valid_scopes_are_included_into_the_current_ones(ResourceServer $checker, AccessTokenEntity $accessTokenEntity) - { - $accessTokenEntity->hasScope('foo')->willReturn(true)->shouldBecalled(); - $accessTokenEntity->hasScope('bar')->willReturn(true)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalledTimes(2); - $this->hasScope(['foo', 'bar'])->shouldReturn(true); - } - - public function it_throws_if_scopes_are_checked_without_active_access_token(ResourceServer $checker) - { - $checker->getAccessToken()->willReturn(null); - $this->shouldThrow(NoActiveAccessTokenException::class)->during('hasScope', ['foo']); - } - - public function it_returns_the_resource_owner_id(ResourceServer $checker, AccessTokenEntity $accessTokenEntity, SessionEntity $sessionEntity) - { - $sessionEntity->getOwnerId()->willReturn('1')->shouldBeCalled(); - $accessTokenEntity->getSession()->willReturn($sessionEntity)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->getResourceOwnerId()->shouldReturn('1'); - } - - public function it_throws_exception_if_resource_owner_id_accessed_without_active_session(ResourceServer $checker) - { - $checker->getAccessToken()->willReturn(null); - $this->shouldThrow(NoActiveAccessTokenException::class)->during('getResourceOwnerId'); - } - - public function it_returns_the_resource_owner_type(ResourceServer $checker, AccessTokenEntity $accessTokenEntity, SessionEntity $sessionEntity) - { - $sessionEntity->getOwnerType()->willReturn('user')->shouldBeCalled(); - $accessTokenEntity->getSession()->willReturn($sessionEntity)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->getResourceOwnerType()->shouldReturn('user'); - } - - public function test_it_throws_exception_if_resource_owner_type_accessed_without_active_session(ResourceServer $checker) - { - $checker->getAccessToken()->willReturn(null); - $this->shouldThrow(NoActiveAccessTokenException::class)->during('getResourceOwnerType'); - } - - public function it_returns_the_client_id(ResourceServer $checker, AccessTokenEntity $accessTokenEntity, SessionEntity $sessionEntity, ClientEntity $clientEntity) - { - $clientEntity->getId()->willReturn('1')->shouldBeCalled(); - $sessionEntity->getClient()->willReturn($clientEntity)->shouldBeCalled(); - $accessTokenEntity->getSession()->willReturn($sessionEntity)->shouldBeCalled(); - $checker->getAccessToken()->willReturn($accessTokenEntity)->shouldBeCalled(); - $this->getClientId()->shouldReturn('1'); - } - - public function it_returns_the_issuer(AuthorizationServer $issuer) - { - $this->getIssuer()->shouldReturn($issuer); - } - - public function it_returns_the_checker(ResourceServer $checker) - { - $this->getChecker()->shouldReturn($checker); - } - - public function it_sets_the_request_to_the_issuer_and_checker(AuthorizationServer $issuer, ResourceServer $checker, Request $request) - { - $issuer->setRequest($request)->shouldBeCalled(); - $checker->setRequest($request)->shouldBeCalled(); - - $this->setRequest($request); - } - - public function it_validates_an_access_token(ResourceServer $checker) - { - $checker->isValidRequest(false, null)->shouldBeCalled(); - - $this->validateAccessToken(false, null); - } - - public function it_generates_a_redirect_uri_when_the_user_denies_the_auth_code() - { - $this->authCodeRequestDeniedRedirectUri()->shouldReturn('?error=access_denied&error_description=The+resource+owner+or+authorization+server+denied+the+request.'); - } - - public function it_sets_a_redirect_uri_generator(RedirectUri $redirectUri) - { - $this->setRedirectUriGenerator($redirectUri); - - $this->getRedirectUriGenerator()->shouldReturn($redirectUri); - } -} diff --git a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/CheckAuthCodeRequestMiddlewareSpec.php b/tests/unit/LucaDegasperi/OAuth2Server/Middleware/CheckAuthCodeRequestMiddlewareSpec.php deleted file mode 100644 index ab6a22d7..00000000 --- a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/CheckAuthCodeRequestMiddlewareSpec.php +++ /dev/null @@ -1,61 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace unit\LucaDegasperi\OAuth2Server\Middleware; - -use Illuminate\Http\Request; -use League\OAuth2\Server\Exception\InvalidRequestException; -use LucaDegasperi\OAuth2Server\Authorizer; -use PhpSpec\ObjectBehavior; - -class CheckAuthCodeRequestMiddlewareSpec extends ObjectBehavior -{ - private $next = null; - - public function __construct() - { - $this->next = (function () { - throw new MiddlewareException('Called execution of $next'); - }); - } - - public function let(Authorizer $authorizer) - { - $this->beConstructedWith($authorizer); - } - - public function it_is_initializable() - { - $this->shouldHaveType('LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware'); - } - - public function it_calls_the_next_middleware_on_success(Request $request, Authorizer $authorizer) - { - $authorizer->checkAuthCodeRequest()->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } - - public function it_exits_on_error(Request $request, Authorizer $authorizer) - { - $authorizer->checkAuthCodeRequest()->willThrow(new InvalidRequestException('client_id'))->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldNotThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } -} - -class MiddlewareException extends \Exception -{ -} diff --git a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthClientOwnerMiddlewareSpec.php b/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthClientOwnerMiddlewareSpec.php deleted file mode 100644 index f990dc1c..00000000 --- a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthClientOwnerMiddlewareSpec.php +++ /dev/null @@ -1,65 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace unit\LucaDegasperi\OAuth2Server\Middleware; - -use Illuminate\Http\Request; -use League\OAuth2\Server\Exception\AccessDeniedException; -use LucaDegasperi\OAuth2Server\Authorizer; -use PhpSpec\ObjectBehavior; - -/** - * This is the oauth client middleware spec class. - * - * @author Vincent Klaiber - */ -class OAuthClientOwnerMiddlewareSpec extends ObjectBehavior -{ - private $next = null; - - public function __construct() - { - $this->next = (function () { - throw new MiddlewareException('Called execution of $next'); - }); - } - - public function let(Authorizer $authorizer) - { - $this->beConstructedWith($authorizer); - } - - public function it_is_initializable() - { - $this->shouldHaveType('LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware'); - } - - public function it_passes_if_resource_owners_are_allowed(Request $request, Authorizer $authorizer) - { - $authorizer->getResourceOwnerType()->willReturn('client')->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } - - public function it_blocks_if_resource_owners_are_not_allowed(Request $request, Authorizer $authorizer) - { - $authorizer->getResourceOwnerType()->willReturn('user')->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldThrow(new AccessDeniedException()) - ->during('handle', [$request, $this->next]); - - $this->shouldNotThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } -} diff --git a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthMiddlewareSpec.php b/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthMiddlewareSpec.php deleted file mode 100644 index c36b97be..00000000 --- a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthMiddlewareSpec.php +++ /dev/null @@ -1,84 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace unit\LucaDegasperi\OAuth2Server\Middleware; - -use Illuminate\Http\Request; -use League\OAuth2\Server\Exception\AccessDeniedException; -use League\OAuth2\Server\Exception\InvalidScopeException; -use LucaDegasperi\OAuth2Server\Authorizer; -use PhpSpec\ObjectBehavior; - -class OAuthMiddlewareSpec extends ObjectBehavior -{ - private $next = null; - - public function __construct() - { - $this->next = (function () { - throw new MiddlewareException('Called execution of $next'); - }); - } - - public function let(Authorizer $authorizer) - { - $this->beConstructedWith($authorizer, false); - } - - public function it_is_initializable() - { - $this->shouldHaveType('LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware'); - } - - public function it_blocks_invalid_access_tokens(Request $request, Authorizer $authorizer) - { - $authorizer->validateAccessToken(false)->willThrow(new AccessDeniedException())->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldNotThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } - - public function it_passes_with_valid_access_token(Request $request, Authorizer $authorizer) - { - $authorizer->validateAccessToken(false)->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } - - public function it_block_invalid_scopes(Request $request, Authorizer $authorizer) - { - $authorizer->validateAccessToken(false)->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - $authorizer->hasScope(['baz'])->willReturn(false)->shouldBeCalled(); - - $this->shouldThrow(new InvalidScopeException('baz')) - ->during('handle', [$request, $this->next, 'baz']); - - $this->shouldNotThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next, 'baz']); - } - - public function it_passes_with_valid_scopes(Request $request, Authorizer $authorizer) - { - $authorizer->validateAccessToken(false)->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - $authorizer->hasScope(['baz'])->willReturn(true)->shouldBeCalled(); - - $this->shouldNotThrow(new InvalidScopeException('baz')) - ->during('handle', [$request, $this->next, 'baz']); - - $this->shouldThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next, 'baz']); - } -} diff --git a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthUserOwnerMiddlewareSpec.php b/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthUserOwnerMiddlewareSpec.php deleted file mode 100644 index cfc026e4..00000000 --- a/tests/unit/LucaDegasperi/OAuth2Server/Middleware/OAuthUserOwnerMiddlewareSpec.php +++ /dev/null @@ -1,65 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace unit\LucaDegasperi\OAuth2Server\Middleware; - -use Illuminate\Http\Request; -use League\OAuth2\Server\Exception\AccessDeniedException; -use LucaDegasperi\OAuth2Server\Authorizer; -use PhpSpec\ObjectBehavior; - -/** - * This is the oauth user middleware spec class. - * - * @author Vincent Klaiber - */ -class OAuthUserOwnerMiddlewareSpec extends ObjectBehavior -{ - private $next = null; - - public function __construct() - { - $this->next = (function () { - throw new MiddlewareException('Called execution of $next'); - }); - } - - public function let(Authorizer $authorizer) - { - $this->beConstructedWith($authorizer); - } - - public function it_is_initializable() - { - $this->shouldHaveType('LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware'); - } - - public function it_passes_if_resource_owners_are_allowed(Request $request, Authorizer $authorizer) - { - $authorizer->getResourceOwnerType()->willReturn('user')->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } - - public function it_blocks_if_resource_owners_are_not_allowed(Request $request, Authorizer $authorizer) - { - $authorizer->getResourceOwnerType()->willReturn('client')->shouldBeCalled(); - $authorizer->setRequest($request)->shouldBeCalled(); - - $this->shouldThrow(new AccessDeniedException()) - ->during('handle', [$request, $this->next]); - - $this->shouldNotThrow(new MiddlewareException('Called execution of $next')) - ->during('handle', [$request, $this->next]); - } -} From f4b82aa019468fcc2535869e53ff04a67d83bb4c Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 7 Jan 2016 11:21:58 +0100 Subject: [PATCH 03/61] folders for v6 --- config/.gitkeep | 0 database/.gitkeep | 0 src/.gitkeep | 0 tests/.gitkeep | 0 4 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 config/.gitkeep create mode 100644 database/.gitkeep create mode 100644 src/.gitkeep create mode 100644 tests/.gitkeep diff --git a/config/.gitkeep b/config/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/database/.gitkeep b/database/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/.gitkeep b/tests/.gitkeep new file mode 100644 index 00000000..e69de29b From a5a1bd18f95c95c338dba04ee792a8dd192293e1 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 30 Mar 2016 09:15:37 +0200 Subject: [PATCH 04/61] composer --- composer.json | 3 +- src/Guard.php | 187 ++++++++++++++++++++++++++++ src/OAuth2ServerServiceProvider.php | 63 ++++++++++ src/{ => Repositories}/.gitkeep | 0 4 files changed, 252 insertions(+), 1 deletion(-) create mode 100644 src/Guard.php create mode 100644 src/OAuth2ServerServiceProvider.php rename src/{ => Repositories}/.gitkeep (100%) diff --git a/composer.json b/composer.json index 9edaa0ac..b6671978 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,8 @@ "illuminate/http": "5.2.*", "illuminate/support": "5.2.*", "illuminate/config": "5.2.*", - "league/oauth2-server": "5.0.x-dev" + "league/oauth2-server": "5.0.0-RC1", + "symfony/psr-http-message-bridge": "^0.2.0" }, "require-dev": { "orchestra/testbench": "3.2.*", diff --git a/src/Guard.php b/src/Guard.php new file mode 100644 index 00000000..007c7edc --- /dev/null +++ b/src/Guard.php @@ -0,0 +1,187 @@ +provider = $provider; + $this->request = $request; + $this->resourceServer = $resourceServer; + } + + /** + * Get the currently authenticated user. + * + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function user() + { + if (!is_null($this->user)) { + return $this->user; + } + + $this->parseRequest(); + + return $this->user; + } + + /** + * Validate a user's credentials. + * + * @param array $credentials + * @return bool + */ + public function validate(array $credentials = []) + { + $user = $this->provider->retrieveByCredentials($credentials); + + if ($this->hasValidCredentials($user, $credentials)) { + return true; + } + + return false; + } + + /** + * Determine if the user matches the credentials. + * + * @param mixed $user + * @param array $credentials + * + * @return bool + */ + protected function hasValidCredentials($user, $credentials) + { + return !is_null($user) && $this->provider->validateCredentials($user, $credentials); + } + + + public function scopes() + { + if (!is_null($this->scopes)) { + return $this->scopes; + } + + $this->parseRequest(); + + return $this->scopes; + } + + public function accessToken() + { + if (!is_null($this->accessToken)) { + return $this->accessToken; + } + + $this->parseRequest(); + + return $this->accessToken; + } + + + /** + * Get the client doing the request + */ + public function client() + { + if (!is_null($this->client)) { + return $this->client; + } + + $this->parseRequest(); + } + + public function setClient(ClientEntityInterface $client) + { + $this->client = $client; + return $this; + } + + /** + * Set the current request instance. + * + * @param Request $request + * @return $this + */ + public function setRequest(Request $request) + { + $this->request = $request; + return $this; + } + + protected function parseRequest() + { + try { + + $this->request = $this->resourceServer->validateAuthenticatedRequest($this->request); + + $this->user = $this->provider->retrieveById($this->request->getAttribute('oauth_user_id')); + + // TODO: parse client into entity + $this->client = $this->request->getAttribute('oauth_client_id'); + $this->scopes = $this->request->getAttribute('oauth_scopes', []); + + } catch (OAuthServerException $exception) { + $this->user = null; + $this->client = null; + $this->accessToken = null; + } + } + + public function getResourceServer() + { + return $this->resourceServer; + } + + public function setResourceServer(ResourceServer $server) + { + $this->resourceServer = $server; + return $this; + } +} \ No newline at end of file diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php new file mode 100644 index 00000000..dcaa254c --- /dev/null +++ b/src/OAuth2ServerServiceProvider.php @@ -0,0 +1,63 @@ +registerGrantTypes(); + $this->registerServer(); + } + + /** + * Boot the authentication services for the application. + * + * @return void + */ + public function boot() + { + + } + + protected function registerServer() + { + $this->app->singleton(Server::class, function ($app) { + $server = new Server( + $app->make(ClientRepositoryInterface::class), + $app->make(AccessTokenRepositoryInterface::class), + $app->make(ScopeRepositoryInterface::class), + $app['config']->get('oauth2.private_key_path'), + $app['config']->get('oauth2.public_key_path'), + $app->make($app['config']->get('oauth2.response_type')), + $app->make($app['config']->get('oauth2.authorization_validator')) + ); + + foreach ($app['config']->get('oauth2.grant_types') as $grantType) { + $server->enableGrantType( + $app->make($grantType['class']), + new DateInterval('PT' . $grantType['ttl'] . 'S') + ); + } + + }); + } + + protected function registerGrantTypes() + { + + } +} \ No newline at end of file diff --git a/src/.gitkeep b/src/Repositories/.gitkeep similarity index 100% rename from src/.gitkeep rename to src/Repositories/.gitkeep From 88954d308b19a21e2f3f48c4c041fc4b0eecabc4 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 31 Mar 2016 15:32:24 +0200 Subject: [PATCH 05/61] Initial work on V6 --- config/oauth2.php | 127 +++++++++++++ src/Entities/AccessToken.php | 175 ++++++++++++++++++ src/Entities/AuthCode.php | 167 +++++++++++++++++ src/Entities/Client.php | 92 +++++++++ src/Entities/RefreshToken.php | 97 ++++++++++ src/Entities/Scope.php | 51 +++++ src/Guard.php | 11 ++ src/OAuth2ServerServiceProvider.php | 60 +++++- src/Repositories/AccessTokenRepository.php | 43 +++++ src/Repositories/AuthCodeRepository.php | 43 +++++ src/Repositories/ClientRepository.php | 30 +++ src/Repositories/RefreshTokenRepository.php | 43 +++++ .../RepositoriesServiceProvider.php | 31 ++++ src/Repositories/ScopeRepository.php | 46 +++++ src/Repositories/UserRepository.php | 29 +++ 15 files changed, 1043 insertions(+), 2 deletions(-) create mode 100644 config/oauth2.php create mode 100644 src/Entities/AccessToken.php create mode 100644 src/Entities/AuthCode.php create mode 100644 src/Entities/Client.php create mode 100644 src/Entities/RefreshToken.php create mode 100644 src/Entities/Scope.php create mode 100644 src/Repositories/AccessTokenRepository.php create mode 100644 src/Repositories/AuthCodeRepository.php create mode 100644 src/Repositories/ClientRepository.php create mode 100644 src/Repositories/RefreshTokenRepository.php create mode 100644 src/Repositories/RepositoriesServiceProvider.php create mode 100644 src/Repositories/ScopeRepository.php create mode 100644 src/Repositories/UserRepository.php diff --git a/config/oauth2.php b/config/oauth2.php new file mode 100644 index 00000000..63a78f67 --- /dev/null +++ b/config/oauth2.php @@ -0,0 +1,127 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +return [ + /* + |-------------------------------------------------------------------------- + | Supported Grant Types + |-------------------------------------------------------------------------- + | + | Your OAuth2 Server can issue an access token based on different grant + | types you can even provide your own grant type. + | + | To choose which grant type suits your scenario, see + | http://oauth2.thephpleague.com/authorization-server/which-grant + | + | Please see this link to find available grant types + | http://git.io/vJLAv + | + */ + 'grant_types' => [ + + ], + /* + |-------------------------------------------------------------------------- + | Output Response Type + |-------------------------------------------------------------------------- + | + | This will tell the authorization server the output format for the access + | token and the resource server how to parse the access token used. + | + | Default value is League\OAuth2\Server\ResponseTypes\BearerTokenResponse + | + */ + 'response_type' => 'League\OAuth2\Server\ResponseTypes\BearerTokenResponse', + /* + |-------------------------------------------------------------------------- + | State Parameter + |-------------------------------------------------------------------------- + | + | Whether or not the state parameter is required in the query string. + | + */ + 'state_param' => false, + /* + |-------------------------------------------------------------------------- + | Scope Parameter + |-------------------------------------------------------------------------- + | + | Whether or not the scope parameter is required in the query string. + | + */ + 'scope_param' => false, + /* + |-------------------------------------------------------------------------- + | Scope Delimiter + |-------------------------------------------------------------------------- + | + | Which character to use to split the scope parameter in the query string. + | + */ + 'scope_delimiter' => ',', + /* + |-------------------------------------------------------------------------- + | Default Scope + |-------------------------------------------------------------------------- + | + | The default scope to use if not present in the query string. + | + */ + 'default_scope' => null, + /* + |-------------------------------------------------------------------------- + | Access Token TTL + |-------------------------------------------------------------------------- + | + | For how long the issued access token is valid (in seconds) this can be + | also set on a per grant-type basis. + | + */ + 'access_token_ttl' => 3600, + /* + |-------------------------------------------------------------------------- + | Limit clients to specific grants + |-------------------------------------------------------------------------- + | + | Whether or not to limit clients to specific grant types. This is useful + | to allow only trusted clients to access your API differently. + | + */ + 'limit_clients_to_grants' => false, + /* + |-------------------------------------------------------------------------- + | Limit clients to specific scopes + |-------------------------------------------------------------------------- + | + | Whether or not to limit clients to specific scopes. This is useful to + | only allow specific clients to use some scopes. + | + */ + 'limit_clients_to_scopes' => false, + /* + |-------------------------------------------------------------------------- + | Limit scopes to specific grants + |-------------------------------------------------------------------------- + | + | Whether or not to limit scopes to specific grants. This is useful to + | allow certain scopes to be used only with certain grant types. + | + */ + 'limit_scopes_to_grants' => false, + /* + |-------------------------------------------------------------------------- + | HTTP Header Only + |-------------------------------------------------------------------------- + | + | This will tell the resource server where to check for the access_token. + | By default it checks both the query string and the http headers. + | + */ + 'http_headers_only' => false, +]; \ No newline at end of file diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php new file mode 100644 index 00000000..d292c9d9 --- /dev/null +++ b/src/Entities/AccessToken.php @@ -0,0 +1,175 @@ +setAudience($this->getClient()->getIdentifier()) + ->setId($this->getIdentifier(), true) + ->setIssuedAt(time()) + ->setNotBefore(time()) + ->setExpiration($this->getExpiryDateTime()->getTimestamp()) + ->setSubject($this->getUserIdentifier()) + ->set('scopes', $this->getScopes()) + ->sign(new Sha256(), new Key($privateKeyPath)) + ->getToken(); + } + + /** + * Get the token's identifier. + * + * @return string + */ + public function getIdentifier() + { + return $this->token; + } + + /** + * Set the token's identifier. + * + * @param $identifier + */ + public function setIdentifier($identifier) + { + $this->token = $identifier; + } + + /** + * Get the token's expiry date time. + * + * @return \DateTime + */ + public function getExpiryDateTime() + { + return $this->expires_at; + } + + /** + * Set the date time when the token expires. + * + * @param \DateTime $dateTime + */ + public function setExpiryDateTime(\DateTime $dateTime) + { + $this->expires_at = Carbon::instance($dateTime); + } + + /** + * Set the identifier of the user associated with the token. + * + * @param string|int $identifier The identifier of the user + */ + public function setUserIdentifier($identifier) + { + $this->user_id = $identifier; + } + + /** + * Get the token user's identifier. + * + * @return string|int + */ + public function getUserIdentifier() + { + return $this->user_id; + } + + /** + * Get the client that the token was issued to. + * + * @return ClientEntityInterface + */ + public function getClient() + { + return $this->client; + } + + /** + * Set the client that the token was issued to. + * + * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $client + */ + public function setClient(ClientEntityInterface $client) + { + $this->client()->save($client); + } + + /** + * Associate a scope with the token. + * + * @param \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface $scope + */ + public function addScope(ScopeEntityInterface $scope) + { + $this->scopes()->attach($scope); + } + + /** + * Return an array of scopes associated with the token. + * + * @return ScopeEntityInterface[] + */ + public function getScopes() + { + return $this->scopes; + } + + /** + * Has the token expired? + * + * @return bool + */ + public function isExpired() + { + return $this->expires_at->lt(new Carbon()); + } + + public function client() + { + return $this->belongsTo(Client::class); + } + + public function scopes() + { + return $this->belongsToMany(Scope::class, 'oauth_access_token_scopes'); + } + + public function refreshToken() + { + return $this->hasOne(RefreshToken::class); + } +} \ No newline at end of file diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php new file mode 100644 index 00000000..989a6b8d --- /dev/null +++ b/src/Entities/AuthCode.php @@ -0,0 +1,167 @@ +redirect_uri; + } + + /** + * @param string $uri + */ + public function setRedirectUri($uri) + { + $this->redirect_uri = $uri; + } + + /** + * Get the token's identifier. + * + * @return string + */ + public function getIdentifier() + { + return $this->code; + } + + /** + * Set the token's identifier. + * + * @param $identifier + */ + public function setIdentifier($identifier) + { + $this->code = $identifier; + } + + /** + * Get the token's expiry date time. + * + * @return \DateTime + */ + public function getExpiryDateTime() + { + return $this->expires_at; + } + + /** + * Set the date time when the token expires. + * + * @param \DateTime $dateTime + */ + public function setExpiryDateTime(\DateTime $dateTime) + { + $this->expires_at = Carbon::instance($dateTime); + } + + /** + * Set the identifier of the user associated with the token. + * + * @param string|int $identifier The identifier of the user + */ + public function setUserIdentifier($identifier) + { + $this->user_id = $identifier; + } + + /** + * Get the token user's identifier. + * + * @return string|int + */ + public function getUserIdentifier() + { + return $this->user->getIdentifier(); + } + + /** + * Get the client that the token was issued to. + * + * @return ClientEntityInterface + */ + public function getClient() + { + return $this->client; + } + + /** + * Set the client that the token was issued to. + * + * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $client + */ + public function setClient(ClientEntityInterface $client) + { + $this->client()->save($client); + } + + /** + * Associate a scope with the token. + * + * @param \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface $scope + */ + public function addScope(ScopeEntityInterface $scope) + { + $this->scopes()->attach($scope); + } + + /** + * Return an array of scopes associated with the token. + * + * @return ScopeEntityInterface[] + */ + public function getScopes() + { + return $this->scopes; + } + + /** + * Has the token expired? + * + * @return bool + */ + public function isExpired() + { + return $this->expires_at->lt(new Carbon()); + } + + public function client() + { + return $this->belongsTo(Client::class); + } + + public function user() + { + return $this->belongsTo(User::class); + } + + public function scopes() + { + return $this->belongsToMany(Scope::class, 'oauth_auth_code_scopes'); + } +} \ No newline at end of file diff --git a/src/Entities/Client.php b/src/Entities/Client.php new file mode 100644 index 00000000..c8eb5324 --- /dev/null +++ b/src/Entities/Client.php @@ -0,0 +1,92 @@ +identifier; + } + + /** + * Set the client's identifier. + * + * @param $identifier + */ + public function setIdentifier($identifier) + { + $this->identifier = $identifier; + } + + /** + * Get the client's name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set the client's name. + * + * @param string $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * Set the client's redirect uri. + * + * @param string $redirectUri + */ + public function setRedirectUri($redirectUri) + { + $this->redirect_uri = $redirectUri; + } + + /** + * Returns the registered redirect URI. + * + * @return string + */ + public function getRedirectUri() + { + return $this->redirect_uri; + } + + public function accessTokens() + { + return $this->hasMany(AccessToken::class); + } + + public function authCodes() + { + return $this->hasMany(AuthCode::class); + } + + public function scopes() + { + return $this->belongsToMany(Scope::class, 'oauth_client_scopes'); + } +} \ No newline at end of file diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php new file mode 100644 index 00000000..2e226794 --- /dev/null +++ b/src/Entities/RefreshToken.php @@ -0,0 +1,97 @@ +token; + } + + /** + * Set the token's identifier. + * + * @param $identifier + */ + public function setIdentifier($identifier) + { + $this->token = $identifier; + } + + /** + * Get the token's expiry date time. + * + * @return \DateTime + */ + public function getExpiryDateTime() + { + return $this->expires_at; + } + + /** + * Set the date time when the token expires. + * + * @param \DateTime $dateTime + */ + public function setExpiryDateTime(\DateTime $dateTime) + { + $this->expires_at = Carbon::instance($dateTime); + } + + /** + * Set the access token that the refresh token was associated with. + * + * @param \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface $accessToken + */ + public function setAccessToken(AccessTokenEntityInterface $accessToken) + { + $this->accessToken()->save($accessToken); + } + + /** + * Get the access token that the refresh token was originally associated with. + * + * @return \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Has the token expired? + * + * @return bool + */ + public function isExpired() + { + return $this->expires_at->lt(new Carbon()); + } + + + public function accessToken() + { + return $this->belongsTo(AccessToken::class); + } +} \ No newline at end of file diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php new file mode 100644 index 00000000..16e25195 --- /dev/null +++ b/src/Entities/Scope.php @@ -0,0 +1,51 @@ +identifier; + } + + /** + * Set the scope's identifier. + * + * @param $identifier + */ + public function setIdentifier($identifier) + { + $this->identifier = $identifier; + } + + public function accessTokens() + { + return $this->belongsToMany(AccessToken::class, 'oauth_access_token_scopes'); + } + + public function authCodes() + { + return $this->belongsToMany(AuthCode::class, 'oauth_auth_code_scopes'); + } + + public function clients() + { + return $this->belongsToMany(Client::class, 'oauth_client_scopes'); + } +} \ No newline at end of file diff --git a/src/Guard.php b/src/Guard.php index 007c7edc..39dd857a 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -36,6 +36,11 @@ class Guard implements IlluminateGuard */ private $accessToken = null; + /** + * @var OAuthServerException + */ + private $exception = null; + /** * @var ResourceServer */ @@ -171,9 +176,15 @@ protected function parseRequest() $this->user = null; $this->client = null; $this->accessToken = null; + $this->exception = $exception; } } + public function getException() + { + return $this->exception; + } + public function getResourceServer() { return $this->resourceServer; diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index dcaa254c..e0091b7f 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -5,6 +5,13 @@ use DateInterval; use Illuminate\Support\ServiceProvider; +use League\OAuth2\Server\Grant\AuthCodeGrant; +use League\OAuth2\Server\Grant\ImplicitGrant; +use League\OAuth2\Server\Grant\PasswordGrant; +use League\OAuth2\Server\Grant\RefreshTokenGrant; +use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface; +use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; +use League\OAuth2\Server\Repositories\UserRepositoryInterface; use League\OAuth2\Server\Server; use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; @@ -30,7 +37,7 @@ public function register() */ public function boot() { - + $this->bootGuard(); } protected function registerServer() @@ -48,7 +55,7 @@ protected function registerServer() foreach ($app['config']->get('oauth2.grant_types') as $grantType) { $server->enableGrantType( - $app->make($grantType['class']), + $app->make($grantType['class'], $grantType), new DateInterval('PT' . $grantType['ttl'] . 'S') ); } @@ -58,6 +65,55 @@ protected function registerServer() protected function registerGrantTypes() { + $this->app->bind(AuthCodeGrant::class, function ($app, $parameters = []) { + + return new AuthCodeGrant( + $app->make(AuthCodeRepositoryInterface::class), + $app->make(RefreshTokenRepositoryInterface::class), + $app->make(UserRepositoryInterface::class), + new DateInterval('PT' . $parameters['auth_code_ttl'] . 'S') + ); + + }); + + $this->app->bind(ImplicitGrant::class, function ($app, $parameters = []) { + + return new ImplicitGrant( + $app->make(UserRepositoryInterface::class) + ); + + }); + + $this->app->bind(PasswordGrant::class, function ($app, $parameters = []) { + + return new PasswordGrant( + $app->make(UserRepositoryInterface::class), + $app->make(RefreshTokenRepositoryInterface::class) + ); + + }); + + $this->app->bind(RefreshTokenGrant::class, function ($app, $parameters = []) { + + return new RefreshTokenGrant( + $app->make(RefreshTokenRepositoryInterface::class) + ); + + }); + } + + protected function bootGuard() + { + $this->app['auth']->extend('oauth', function ($app, $name, array $config) { + $guard = new Guard( + $app['auth']->createUserProvider($config['provider']), + $app->make(Server::class), + $app['request'] + ); + + $app->refresh('request', $guard, 'setRequest'); + return $guard; + }); } } \ No newline at end of file diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php new file mode 100644 index 00000000..0cf9e981 --- /dev/null +++ b/src/Repositories/AccessTokenRepository.php @@ -0,0 +1,43 @@ +save(); + } + + /** + * Revoke an access token. + * + * @param string $tokenId + */ + public function revokeAccessToken($tokenId) + { + AccessToken::where('token', $tokenId)->delete(); + } + + /** + * Check if the access token has been revoked. + * + * @param string $tokenId + * + * @return bool Return true if this token has been revoked + */ + public function isAccessTokenRevoked($tokenId) + { + return AccessToken::where('token', $tokenId)->count() === 0; + } +} \ No newline at end of file diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php new file mode 100644 index 00000000..9ac24f28 --- /dev/null +++ b/src/Repositories/AuthCodeRepository.php @@ -0,0 +1,43 @@ +save(); + } + + /** + * Revoke an auth code. + * + * @param string $codeId + */ + public function revokeAuthCode($codeId) + { + AuthCode::where('code', $codeId)->delete(); + } + + /** + * Check if the auth code has been revoked. + * + * @param string $codeId + * + * @return bool Return true if this code has been revoked + */ + public function isAuthCodeRevoked($codeId) + { + return AuthCode::where('code', $codeId)->count() === 0; + } +} \ No newline at end of file diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php new file mode 100644 index 00000000..88602d68 --- /dev/null +++ b/src/Repositories/ClientRepository.php @@ -0,0 +1,30 @@ +where('secret', $clientSecret); + } + + return $query->first(); + } +} \ No newline at end of file diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php new file mode 100644 index 00000000..e39f3c61 --- /dev/null +++ b/src/Repositories/RefreshTokenRepository.php @@ -0,0 +1,43 @@ +save(); + } + + /** + * Revoke the refresh token. + * + * @param string $tokenId + */ + public function revokeRefreshToken($tokenId) + { + RefreshToken::where('token', $tokenId)->delete(); + } + + /** + * Check if the refresh token has been revoked. + * + * @param string $tokenId + * + * @return bool Return true if this token has been revoked + */ + public function isRefreshTokenRevoked($tokenId) + { + return RefreshToken::where('token', $tokenId)->count() === 0; + } +} \ No newline at end of file diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php new file mode 100644 index 00000000..e4dbaa8e --- /dev/null +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -0,0 +1,31 @@ +app->bind(AccessTokenRepositoryInterface::class, AccessTokenRepository::class); + $this->app->bind(AuthCodeRepositoryInterface::class, AuthCodeRepository::class); + $this->app->bind(ClientRepositoryInterface::class, ClientRepository::class); + $this->app->bind(RefreshTokenRepositoryInterface::class, RefreshTokenRepository::class); + $this->app->bind(ScopeRepositoryInterface::class, ScopeRepository::class); + $this->app->bind(UserRepositoryInterface::class, UserRepositoryInterface::class); + } +} diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php new file mode 100644 index 00000000..978e47b4 --- /dev/null +++ b/src/Repositories/ScopeRepository.php @@ -0,0 +1,46 @@ +first(); + } + + /** + * Given a client, grant type and optional user identifier validate the set of scopes requested are valid and optionally + * append additional scopes or remove requested scopes. + * + * @param ScopeEntityInterface[] $scopes + * @param string $grantType + * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $clientEntity + * @param null|string $userIdentifier + * + * @return \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface[] + */ + public function finalizeScopes( + array $scopes, + $grantType, + ClientEntityInterface $clientEntity, + $userIdentifier = null + ) { + if (!$clientEntity->has('scopes')) { + return $scopes; + } + } +} \ No newline at end of file diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php new file mode 100644 index 00000000..c20002ea --- /dev/null +++ b/src/Repositories/UserRepository.php @@ -0,0 +1,29 @@ + Date: Sat, 2 Apr 2016 17:58:57 +0200 Subject: [PATCH 06/61] Migrations --- composer.json | 6 +- config/oauth2.php | 101 ++++++------------ database/.gitkeep | 0 ...04_02_000001_create_oauth_scopes_table.php | 46 ++++++++ ...4_02_000002_create_oauth_clients_table.php | 48 +++++++++ ...00003_create_oauth_client_scopes_table.php | 56 ++++++++++ ...2_000004_create_oauth_auth_codes_table.php | 56 ++++++++++ ...00005_create_oauth_access_tokens_table.php | 55 ++++++++++ ...06_create_oauth_auth_code_scopes_table.php | 56 ++++++++++ ...create_oauth_access_token_scopes_table.php | 56 ++++++++++ ...0008_create_oauth_refresh_tokens_table.php | 52 +++++++++ src/Entities/AccessToken.php | 8 ++ src/Entities/AuthCode.php | 8 ++ src/Entities/Client.php | 9 ++ src/Entities/RefreshToken.php | 8 ++ src/Entities/Scope.php | 8 ++ src/Guard.php | 8 ++ src/OAuth2ServerServiceProvider.php | 12 ++- src/Repositories/AccessTokenRepository.php | 8 ++ src/Repositories/AuthCodeRepository.php | 8 ++ src/Repositories/ClientRepository.php | 8 ++ src/Repositories/RefreshTokenRepository.php | 8 ++ .../RepositoriesServiceProvider.php | 9 +- src/Repositories/ScopeRepository.php | 27 ++++- src/Repositories/UserRepository.php | 38 ++++++- 25 files changed, 620 insertions(+), 79 deletions(-) delete mode 100644 database/.gitkeep create mode 100644 database/migrations/2016_04_02_000001_create_oauth_scopes_table.php create mode 100644 database/migrations/2016_04_02_000002_create_oauth_clients_table.php create mode 100644 database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php create mode 100644 database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php create mode 100644 database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php create mode 100644 database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php create mode 100644 database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php create mode 100644 database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php diff --git a/composer.json b/composer.json index b6671978..0c36e950 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "lucadegasperi/oauth2-server-laravel", - "description": "An OAuth 2.0 bridge for Laravel and Lumen", - "keywords": ["oauth2", "oauth", "server", "api", "laravel", "lumen"], + "description": "An OAuth 2.0 bridge for Laravel", + "keywords": ["oauth2", "oauth", "server", "api", "laravel", "league", "authentication", "authorization"], "license": "MIT", "authors": [ { @@ -21,7 +21,7 @@ "illuminate/http": "5.2.*", "illuminate/support": "5.2.*", "illuminate/config": "5.2.*", - "league/oauth2-server": "5.0.0-RC1", + "league/oauth2-server": "^5.0", "symfony/psr-http-message-bridge": "^0.2.0" }, "require-dev": { diff --git a/config/oauth2.php b/config/oauth2.php index 63a78f67..ddb78e99 100644 --- a/config/oauth2.php +++ b/config/oauth2.php @@ -1,4 +1,5 @@ [ - + [ + 'class' => \League\OAuth2\Server\Grant\PasswordGrant::class, + 'access_token_ttl' => '', + ] ], + + /* |-------------------------------------------------------------------------- - | Output Response Type + | Private Key Path |-------------------------------------------------------------------------- | | This will tell the authorization server the output format for the access | token and the resource server how to parse the access token used. | - | Default value is League\OAuth2\Server\ResponseTypes\BearerTokenResponse - | - */ - 'response_type' => 'League\OAuth2\Server\ResponseTypes\BearerTokenResponse', - /* - |-------------------------------------------------------------------------- - | State Parameter - |-------------------------------------------------------------------------- - | - | Whether or not the state parameter is required in the query string. - | */ - 'state_param' => false, - /* - |-------------------------------------------------------------------------- - | Scope Parameter - |-------------------------------------------------------------------------- - | - | Whether or not the scope parameter is required in the query string. - | - */ - 'scope_param' => false, - /* - |-------------------------------------------------------------------------- - | Scope Delimiter - |-------------------------------------------------------------------------- - | - | Which character to use to split the scope parameter in the query string. - | - */ - 'scope_delimiter' => ',', - /* - |-------------------------------------------------------------------------- - | Default Scope - |-------------------------------------------------------------------------- - | - | The default scope to use if not present in the query string. - | - */ - 'default_scope' => null, + 'private_key_path' => 'file://path_to_private_key/private.key', + + /* |-------------------------------------------------------------------------- - | Access Token TTL + | Public Key Path |-------------------------------------------------------------------------- | - | For how long the issued access token is valid (in seconds) this can be - | also set on a per grant-type basis. + | This will tell the authorization server the output format for the access + | token and the resource server how to parse the access token used. | */ - 'access_token_ttl' => 3600, + 'public_key_path' => 'file://path_to_private_key/public.key', + /* |-------------------------------------------------------------------------- - | Limit clients to specific grants + | Output Response Type |-------------------------------------------------------------------------- | - | Whether or not to limit clients to specific grant types. This is useful - | to allow only trusted clients to access your API differently. - | - */ - 'limit_clients_to_grants' => false, - /* - |-------------------------------------------------------------------------- - | Limit clients to specific scopes - |-------------------------------------------------------------------------- + | This will tell the authorization server the output format for the access + | token and the resource server how to parse the access token used. | - | Whether or not to limit clients to specific scopes. This is useful to - | only allow specific clients to use some scopes. + | Default value is \League\OAuth2\Server\ResponseTypes\BearerTokenResponse | */ - 'limit_clients_to_scopes' => false, + 'response_type' => \League\OAuth2\Server\ResponseTypes\BearerTokenResponse::class, + + /* |-------------------------------------------------------------------------- - | Limit scopes to specific grants + | Authorization Validator |-------------------------------------------------------------------------- | - | Whether or not to limit scopes to specific grants. This is useful to - | allow certain scopes to be used only with certain grant types. + | This will tell the resource server the validator to use to validate an incoming request | - */ - 'limit_scopes_to_grants' => false, - /* - |-------------------------------------------------------------------------- - | HTTP Header Only - |-------------------------------------------------------------------------- - | - | This will tell the resource server where to check for the access_token. - | By default it checks both the query string and the http headers. + | Default value is \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::class | */ - 'http_headers_only' => false, + 'authorization_validator' => \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::class + ]; \ No newline at end of file diff --git a/database/.gitkeep b/database/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php new file mode 100644 index 00000000..74e6d9e0 --- /dev/null +++ b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthScopesTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_scopes', function (Blueprint $table) { + $table->primary('id'); + $table->string('identifier')->unique(); + $table->string('name'); + $table->string('description'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_scopes'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php new file mode 100644 index 00000000..6df49e79 --- /dev/null +++ b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthClientsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_clients', function (Blueprint $table) { + $table->primary('id'); + $table->string('identifier')->unique(); + $table->string('secret'); + $table->string('name'); + $table->string('description'); + $table->string('redirect_uri'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_scopes'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php new file mode 100644 index 00000000..4146db88 --- /dev/null +++ b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthClientScopesTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_client_scopes', function (Blueprint $table) { + + $table->primary('id'); + $table->integer('client_id')->unsigned(); + $table->integer('scope_id')->unsigned(); + + $table->index('client_id'); + $table->index('scope_id'); + + $table->foreign('client_id') + ->references('id')->on('oauth_clients') + ->onDelete('cascade'); + + $table->foreign('scope_id') + ->references('id')->on('oauth_scopes') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_client_scopes'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php new file mode 100644 index 00000000..0d765b8d --- /dev/null +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthAuthCodesTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_auth_codes', function (Blueprint $table) { + + $table->primary('id'); + $table->string('code')->unique(); + $table->string('redirect_uri'); + + $table->integer('client_id')->unsigned(); + + // use a string for the user identifier + $table->string('user_id'); + + // TODO: make it the current timestamp + $table->timestamp('expires_at')->default('CURRENT_TIMESTAMP'); + $table->timestamps(); + + $table->foreign('client_id')->references('id')->on('oauth_clients')->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_client_scopes'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php new file mode 100644 index 00000000..966b2d45 --- /dev/null +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthAccessTokensTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_access_tokens', function (Blueprint $table) { + + $table->primary('id'); + $table->string('token')->unique(); + + $table->integer('client_id')->unsigned(); + + // use a string for the user identifier + $table->string('user_id'); + + // TODO: make it the current timestamp + $table->timestamp('expires_at')->useCurrent(); + $table->timestamps(); + + $table->foreign('client_id')->references('id')->on('oauth_clients')->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_access_tokens'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php new file mode 100644 index 00000000..d2ce4fe1 --- /dev/null +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthAuthCodeScopesTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_auth_codes_scopes', function (Blueprint $table) { + + $table->primary('id'); + $table->integer('auth_code_id')->unsigned(); + $table->integer('scope_id')->unsigned(); + + $table->index('auth_code_id'); + $table->index('scope_id'); + + $table->foreign('auth_code_id') + ->references('id')->on('oauth_auth_codes') + ->onDelete('cascade'); + + $table->foreign('scope_id') + ->references('id')->on('oauth_scopes') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_auth_codes_scopes'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php new file mode 100644 index 00000000..95c29fbc --- /dev/null +++ b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthAccessTokenScopesTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_access_token_scopes', function (Blueprint $table) { + + $table->primary('id'); + $table->integer('access_token_id')->unsigned(); + $table->integer('scope_id')->unsigned(); + + $table->index('access_token_id'); + $table->index('scope_id'); + + $table->foreign('access_token_id') + ->references('id')->on('oauth_access_tokens') + ->onDelete('cascade'); + + $table->foreign('scope_id') + ->references('id')->on('oauth_scopes') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_access_token_scopes'); + } +} \ No newline at end of file diff --git a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php new file mode 100644 index 00000000..1a13bc42 --- /dev/null +++ b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthRefreshTokensTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_refresh_tokens', function (Blueprint $table) { + + $table->primary('id'); + $table->string('token')->unique(); + + $table->integer('access_token_id')->unsigned(); + + // TODO: make it the current timestamp + $table->timestamp('expires_at')->useCurrent(); + $table->timestamps(); + + $table->foreign('access_token_id')->references('id')->on('oauth_access_tokens')->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_refresh_tokens'); + } +} \ No newline at end of file diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index d292c9d9..64df8587 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Entities; diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 989a6b8d..3bd3c452 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Entities; diff --git a/src/Entities/Client.php b/src/Entities/Client.php index c8eb5324..8efdbbfb 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Entities; @@ -75,6 +83,7 @@ public function getRedirectUri() return $this->redirect_uri; } + public function accessTokens() { return $this->hasMany(AccessToken::class); diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index 2e226794..ba91f0d9 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Entities; diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php index 16e25195..3b637c37 100644 --- a/src/Entities/Scope.php +++ b/src/Entities/Scope.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Entities; diff --git a/src/Guard.php b/src/Guard.php index 39dd857a..8ca8c4ce 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server; diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index e0091b7f..0d363d6a 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -1,5 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server; @@ -43,6 +50,7 @@ public function boot() protected function registerServer() { $this->app->singleton(Server::class, function ($app) { + $server = new Server( $app->make(ClientRepositoryInterface::class), $app->make(AccessTokenRepositoryInterface::class), @@ -56,7 +64,7 @@ protected function registerServer() foreach ($app['config']->get('oauth2.grant_types') as $grantType) { $server->enableGrantType( $app->make($grantType['class'], $grantType), - new DateInterval('PT' . $grantType['ttl'] . 'S') + new DateInterval('PT' . $grantType['access_token_ttl'] . 'S') ); } diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index 0cf9e981..27d075d6 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php index 9ac24f28..7e5ec20e 100644 --- a/src/Repositories/AuthCodeRepository.php +++ b/src/Repositories/AuthCodeRepository.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php index 88602d68..3ba95c1f 100644 --- a/src/Repositories/ClientRepository.php +++ b/src/Repositories/ClientRepository.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php index e39f3c61..f2420b2f 100644 --- a/src/Repositories/RefreshTokenRepository.php +++ b/src/Repositories/RefreshTokenRepository.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index e4dbaa8e..9c8418f8 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -1,5 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index 978e47b4..78106913 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -1,4 +1,12 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; @@ -19,7 +27,7 @@ class ScopeRepository implements ScopeRepositoryInterface */ public function getScopeEntityByIdentifier($identifier) { - Scope::where('identifier', $identifier)->first(); + return Scope::where('identifier', $identifier)->first(); } /** @@ -42,5 +50,22 @@ public function finalizeScopes( if (!$clientEntity->has('scopes')) { return $scopes; } + + $clientScopes = $clientEntity->scopes; + + // TODO: this can be simplified imho. + $scopes = array_filter($scopes, function($scope) use ($clientScopes) { + + $identifier = $scope->getItentifier(); + + return $clientScopes->contains(function($key, $value) use ($identifier) { + $value->getIdentifer() == $identifier; + }); + + }); + + // TODO: add possibility to append scopes from clients or grants + + return $scopes; } } \ No newline at end of file diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index c20002ea..4169c929 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -1,13 +1,33 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace LucaDegasperi\OAuth2Server\Repositories; +use Illuminate\Contracts\Auth\UserProvider; use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; class UserRepository implements UserRepositoryInterface { + /** + * @var UserProvider + */ + private $provider; + + public function __construct(UserProvider $provider) + { + + $this->provider = $provider; + } + /** * Get a user entity. * @@ -24,6 +44,22 @@ public function getUserEntityByUserCredentials( $grantType, ClientEntityInterface $clientEntity ) { - // TODO: Implement getUserEntityByUserCredentials() method. + + $credentials = [ + 'username' => $username, + 'password' => $password, + ]; + + $user = $this->provider->retrieveByCredentials($credentials); + + if (is_null($user)) { + + return null; + } + + // TODO: validate grant type and client for user + + return $this->provider->validateCredentials($user, $credentials) ? $user : null; + } } \ No newline at end of file From a2296b1fe953f204efeee5d0cd1b7c5741694082 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 12:40:11 +0200 Subject: [PATCH 07/61] Improvements --- ...4_02_000002_create_oauth_clients_table.php | 1 - ...00005_create_oauth_access_tokens_table.php | 2 +- ...reate_oauth_client_redirect_uris_table.php | 49 +++++++++++++++++++ src/Entities/AccessToken.php | 38 +++----------- src/Entities/AuthCode.php | 10 ++-- src/Entities/Client.php | 18 +++++-- src/Entities/RedirectUri.php | 29 +++++++++++ src/Entities/RefreshToken.php | 8 +-- src/Entities/Scope.php | 2 +- src/Guard.php | 2 +- src/Repositories/AccessTokenRepository.php | 27 +++++++++- src/Repositories/AuthCodeRepository.php | 14 +++++- src/Repositories/ClientRepository.php | 2 +- src/Repositories/RefreshTokenRepository.php | 13 ++++- src/Repositories/ScopeRepository.php | 10 ++-- src/Repositories/UserRepository.php | 6 +-- 16 files changed, 169 insertions(+), 62 deletions(-) create mode 100644 database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php create mode 100644 src/Entities/RedirectUri.php diff --git a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php index 6df49e79..bb595bbb 100644 --- a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php +++ b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php @@ -31,7 +31,6 @@ public function up() $table->string('secret'); $table->string('name'); $table->string('description'); - $table->string('redirect_uri'); $table->timestamps(); }); } diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php index 966b2d45..a51fad48 100644 --- a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -33,7 +33,7 @@ public function up() $table->integer('client_id')->unsigned(); // use a string for the user identifier - $table->string('user_id'); + $table->string('user_id')->nullable(); // TODO: make it the current timestamp $table->timestamp('expires_at')->useCurrent(); diff --git a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php new file mode 100644 index 00000000..2d5c9f9e --- /dev/null +++ b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +/** + * This is the create oauth scopes table migration class. + * + * @author Luca Degasperi + */ +class CreateOauthClientRedirectUrisTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('oauth_client_redirect_uris', function (Blueprint $table) { + + $table->primary('id'); + $table->string('uri')->unique(); + $table->integer('client_id')->unsigned(); + + $table->timestamps(); + + $table->foreign('client_id')->references('id')->on('oauth_clients')->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('oauth_client_redirect_uris'); + } +} \ No newline at end of file diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index 64df8587..d9d5a43c 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -10,14 +10,12 @@ namespace LucaDegasperi\OAuth2Server\Entities; -use Lcobucci\JWT\Builder; -use Lcobucci\JWT\Signer\Key; -use Lcobucci\JWT\Signer\Rsa\Sha256; use Illuminate\Database\Eloquent\Model; -use League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface; -use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; -use League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface; +use League\OAuth2\Server\Entities\AccessTokenEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; +use League\OAuth2\Server\Entities\ScopeEntityInterface; use Carbon\Carbon; +use League\OAuth2\Server\Entities\Traits\AccessTokenTrait; /** * @property mixed client @@ -30,32 +28,12 @@ */ class AccessToken extends Model implements AccessTokenEntityInterface { + use AccessTokenTrait; protected $table = 'oauth_access_tokens'; protected $dates = ['expires_at']; - /** - * Generate a JWT from the access token - * - * @param string $privateKeyPath - * - * @return string - */ - public function convertToJWT($privateKeyPath) - { - return (new Builder()) - ->setAudience($this->getClient()->getIdentifier()) - ->setId($this->getIdentifier(), true) - ->setIssuedAt(time()) - ->setNotBefore(time()) - ->setExpiration($this->getExpiryDateTime()->getTimestamp()) - ->setSubject($this->getUserIdentifier()) - ->set('scopes', $this->getScopes()) - ->sign(new Sha256(), new Key($privateKeyPath)) - ->getToken(); - } - /** * Get the token's identifier. * @@ -129,7 +107,7 @@ public function getClient() /** * Set the client that the token was issued to. * - * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $client + * @param \League\OAuth2\Server\Entities\ClientEntityInterface $client */ public function setClient(ClientEntityInterface $client) { @@ -139,7 +117,7 @@ public function setClient(ClientEntityInterface $client) /** * Associate a scope with the token. * - * @param \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface $scope + * @param \League\OAuth2\Server\Entities\ScopeEntityInterface $scope */ public function addScope(ScopeEntityInterface $scope) { @@ -153,7 +131,7 @@ public function addScope(ScopeEntityInterface $scope) */ public function getScopes() { - return $this->scopes; + return $this->scopes->toArray(); } /** diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 3bd3c452..ea595778 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -13,9 +13,9 @@ use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User; -use League\OAuth2\Server\Entities\Interfaces\AuthCodeEntityInterface; -use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; -use League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface; +use League\OAuth2\Server\Entities\AuthCodeEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; +use League\OAuth2\Server\Entities\ScopeEntityInterface; /** * @property mixed redirect_uri @@ -121,7 +121,7 @@ public function getClient() /** * Set the client that the token was issued to. * - * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $client + * @param \League\OAuth2\Server\Entities\ClientEntityInterface $client */ public function setClient(ClientEntityInterface $client) { @@ -131,7 +131,7 @@ public function setClient(ClientEntityInterface $client) /** * Associate a scope with the token. * - * @param \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface $scope + * @param \League\OAuth2\Server\Entities\ScopeEntityInterface $scope */ public function addScope(ScopeEntityInterface $scope) { diff --git a/src/Entities/Client.php b/src/Entities/Client.php index 8efdbbfb..db6a9e2b 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -11,13 +11,14 @@ namespace LucaDegasperi\OAuth2Server\Entities; use Illuminate\Database\Eloquent\Model; -use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; /** * @property mixed id * @property mixed name * @property string redirect_uri * @property string identifier + * @property mixed redirectUris */ class Client extends Model implements ClientEntityInterface { @@ -74,13 +75,17 @@ public function setRedirectUri($redirectUri) } /** - * Returns the registered redirect URI. + * Returns the registered redirect URI (as a string). * - * @return string + * Alternatively return an indexed array of redirect URIs. + * + * @return string|string[] */ public function getRedirectUri() { - return $this->redirect_uri; + return $this->redirectUris->map(function($item, $key){ + return $item->uri; + })->toArray(); } @@ -98,4 +103,9 @@ public function scopes() { return $this->belongsToMany(Scope::class, 'oauth_client_scopes'); } + + public function redirectUris() + { + return $this->hasMany(RedirectUri::class); + } } \ No newline at end of file diff --git a/src/Entities/RedirectUri.php b/src/Entities/RedirectUri.php new file mode 100644 index 00000000..5d9a2a63 --- /dev/null +++ b/src/Entities/RedirectUri.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace LucaDegasperi\OAuth2Server\Entities; + +use Illuminate\Database\Eloquent\Model; + +/** + * @property mixed id + * @property mixed identifier + */ +class RedirectUri extends Model +{ + + protected $table = 'oauth_client_redirect_uris'; + + + public function client() + { + return $this->belongsTo(Client::class); + } +} \ No newline at end of file diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index ba91f0d9..5049df70 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -11,8 +11,8 @@ namespace LucaDegasperi\OAuth2Server\Entities; use Illuminate\Database\Eloquent\Model; -use League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface; -use League\OAuth2\Server\Entities\Interfaces\RefreshTokenEntityInterface; +use League\OAuth2\Server\Entities\AccessTokenEntityInterface; +use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; use Carbon\Carbon; /** @@ -70,7 +70,7 @@ public function setExpiryDateTime(\DateTime $dateTime) /** * Set the access token that the refresh token was associated with. * - * @param \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface $accessToken + * @param \League\OAuth2\Server\Entities\AccessTokenEntityInterface $accessToken */ public function setAccessToken(AccessTokenEntityInterface $accessToken) { @@ -80,7 +80,7 @@ public function setAccessToken(AccessTokenEntityInterface $accessToken) /** * Get the access token that the refresh token was originally associated with. * - * @return \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface + * @return \League\OAuth2\Server\Entities\AccessTokenEntityInterface */ public function getAccessToken() { diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php index 3b637c37..b2b1f619 100644 --- a/src/Entities/Scope.php +++ b/src/Entities/Scope.php @@ -11,7 +11,7 @@ namespace LucaDegasperi\OAuth2Server\Entities; use Illuminate\Database\Eloquent\Model; -use League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface; +use League\OAuth2\Server\Entities\ScopeEntityInterface; /** * @property mixed id diff --git a/src/Guard.php b/src/Guard.php index 8ca8c4ce..02a1d9e1 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -15,7 +15,7 @@ use Illuminate\Contracts\Auth\Guard as IlluminateGuard; use Illuminate\Contracts\Auth\UserProvider; use Psr\Http\Message\ServerRequestInterface as Request; -use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Server as ResourceServer; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index 27d075d6..55fc1219 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -10,17 +10,40 @@ namespace LucaDegasperi\OAuth2Server\Repositories; -use League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface; +use League\OAuth2\Server\Entities\AccessTokenEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\AccessToken; class AccessTokenRepository implements AccessTokenRepositoryInterface { + /** + * Create a new access token + * + * @param \League\OAuth2\Server\Entities\ClientEntityInterface $clientEntity + * @param \League\OAuth2\Server\Entities\ScopeEntityInterface[] $scopes + * @param mixed $userIdentifier + * + * @return AccessTokenEntityInterface + */ + public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null) + { + $accessToken = new AccessToken(); + $accessToken->setClient($clientEntity); + + foreach($scopes as $scope) { + $accessToken->addScope($scope); + } + + $accessToken->setUserIdentifier($userIdentifier); + + return $accessToken; + } /** * Persists a new access token to permanent storage. * - * @param \League\OAuth2\Server\Entities\Interfaces\AccessTokenEntityInterface $accessTokenEntity + * @param \League\OAuth2\Server\Entities\AccessTokenEntityInterface $accessTokenEntity */ public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity) { diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php index 7e5ec20e..16cf5d0f 100644 --- a/src/Repositories/AuthCodeRepository.php +++ b/src/Repositories/AuthCodeRepository.php @@ -10,17 +10,27 @@ namespace LucaDegasperi\OAuth2Server\Repositories; -use League\OAuth2\Server\Entities\Interfaces\AuthCodeEntityInterface; +use League\OAuth2\Server\Entities\AuthCodeEntityInterface; use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\AuthCode; class AuthCodeRepository implements AuthCodeRepositoryInterface { + /** + * Creates a new AuthCode + * + * @return \League\OAuth2\Server\Entities\AuthCodeEntityInterface + */ + public function getNewAuthCode() + { + return new AuthCode(); + } + /** * Persists a new auth code to permanent storage. * - * @param \League\OAuth2\Server\Entities\Interfaces\AuthCodeEntityInterface $authCodeEntity + * @param \League\OAuth2\Server\Entities\AuthCodeEntityInterface $authCodeEntity */ public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity) { diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php index 3ba95c1f..112ef054 100644 --- a/src/Repositories/ClientRepository.php +++ b/src/Repositories/ClientRepository.php @@ -23,7 +23,7 @@ class ClientRepository implements ClientRepositoryInterface * @param string $grantType The grant type used * @param null|string $clientSecret The client's secret (if sent) * - * @return \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface + * @return \League\OAuth2\Server\Entities\ClientEntityInterface */ public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null) { diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php index f2420b2f..9454a212 100644 --- a/src/Repositories/RefreshTokenRepository.php +++ b/src/Repositories/RefreshTokenRepository.php @@ -10,17 +10,26 @@ namespace LucaDegasperi\OAuth2Server\Repositories; -use League\OAuth2\Server\Entities\Interfaces\RefreshTokenEntityInterface; +use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\RefreshToken; class RefreshTokenRepository implements RefreshTokenRepositoryInterface { + /** + * Creates a new refresh token + * + * @return RefreshTokenEntityInterface + */ + public function getNewRefreshToken() + { + return new RefreshToken(); + } /** * Create a new refresh token_name. * - * @param \League\OAuth2\Server\Entities\Interfaces\RefreshTokenEntityInterface $refreshTokenEntity + * @param \League\OAuth2\Server\Entities\RefreshTokenEntityInterface $refreshTokenEntity */ public function persistNewRefreshToken(RefreshTokenEntityInterface $refreshTokenEntity) { diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index 78106913..ab645e40 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -10,8 +10,8 @@ namespace LucaDegasperi\OAuth2Server\Repositories; -use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; -use League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; +use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\Scope; @@ -23,7 +23,7 @@ class ScopeRepository implements ScopeRepositoryInterface * * @param string $identifier The scope identifier * - * @return \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface + * @return \League\OAuth2\Server\Entities\ScopeEntityInterface */ public function getScopeEntityByIdentifier($identifier) { @@ -36,10 +36,10 @@ public function getScopeEntityByIdentifier($identifier) * * @param ScopeEntityInterface[] $scopes * @param string $grantType - * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $clientEntity + * @param \League\OAuth2\Server\Entities\ClientEntityInterface $clientEntity * @param null|string $userIdentifier * - * @return \League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface[] + * @return \League\OAuth2\Server\Entities\ScopeEntityInterface[] */ public function finalizeScopes( array $scopes, diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index 4169c929..416ae573 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -11,7 +11,7 @@ namespace LucaDegasperi\OAuth2Server\Repositories; use Illuminate\Contracts\Auth\UserProvider; -use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; class UserRepository implements UserRepositoryInterface @@ -34,9 +34,9 @@ public function __construct(UserProvider $provider) * @param string $username * @param string $password * @param string $grantType The grant type used - * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $clientEntity + * @param \League\OAuth2\Server\Entities\ClientEntityInterface $clientEntity * - * @return \League\OAuth2\Server\Entities\Interfaces\UserEntityInterface + * @return \League\OAuth2\Server\Entities\UserEntityInterface */ public function getUserEntityByUserCredentials( $username, From b5ac4e080157f0f74a4b87a336ed30d37c7ee714 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 13:55:01 +0200 Subject: [PATCH 08/61] Publishing --- src/OAuth2ServerServiceProvider.php | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index 0d363d6a..f6e37c9b 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -44,6 +44,9 @@ public function register() */ public function boot() { + $this->bootConfigPublishing(); + $this->bootMigrationPublishing(); + $this->bootGuard(); } @@ -124,4 +127,32 @@ protected function bootGuard() return $guard; }); } + + /** + * Setup the migrations. + * + * @return void + */ + protected function bootMigrationPublishing() + { + $source = realpath(__DIR__ . '/../database/migrations/'); + + if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { + $this->publishes([$source => database_path('migrations')], 'migrations'); + } + } + + /** + * Setup the config. + * + * @return void + */ + protected function bootConfigPublishing() + { + $source = realpath(__DIR__ . '/../config/oauth2.php'); + if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { + $this->publishes([$source => config_path('oauth2.php')]); + } + $this->mergeConfigFrom($source, 'oauth2'); + } } \ No newline at end of file From 34a3feeb9d47e602d31cfa25be55d2b743581915 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 14:13:19 +0200 Subject: [PATCH 09/61] Fix --- src/OAuth2ServerServiceProvider.php | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index f6e37c9b..f6f9a676 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -136,10 +136,7 @@ protected function bootGuard() protected function bootMigrationPublishing() { $source = realpath(__DIR__ . '/../database/migrations/'); - - if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { - $this->publishes([$source => database_path('migrations')], 'migrations'); - } + $this->publishes([$source => database_path('migrations')], 'migrations'); } /** @@ -150,9 +147,7 @@ protected function bootMigrationPublishing() protected function bootConfigPublishing() { $source = realpath(__DIR__ . '/../config/oauth2.php'); - if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { - $this->publishes([$source => config_path('oauth2.php')]); - } + $this->publishes([$source => config_path('oauth2.php')]); $this->mergeConfigFrom($source, 'oauth2'); } } \ No newline at end of file From 7a4114d9f06c715c0b6ec82f91f86d4ddf9d65c8 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 14:44:44 +0200 Subject: [PATCH 10/61] Certificate Keys --- config/oauth2.php | 14 ++++++++++---- src/OAuth2ServerServiceProvider.php | 5 +++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/config/oauth2.php b/config/oauth2.php index ddb78e99..b28aa01a 100644 --- a/config/oauth2.php +++ b/config/oauth2.php @@ -39,8 +39,6 @@ | Private Key Path |-------------------------------------------------------------------------- | - | This will tell the authorization server the output format for the access - | token and the resource server how to parse the access token used. | */ 'private_key_path' => 'file://path_to_private_key/private.key', @@ -51,12 +49,20 @@ | Public Key Path |-------------------------------------------------------------------------- | - | This will tell the authorization server the output format for the access - | token and the resource server how to parse the access token used. | */ 'public_key_path' => 'file://path_to_private_key/public.key', + /* + |-------------------------------------------------------------------------- + | Key Passphrase + |-------------------------------------------------------------------------- + | + | Default value is null, put your passphrase here if the key has one + | + */ + 'key_passphrase' => null, + /* |-------------------------------------------------------------------------- | Output Response Type diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index f6f9a676..67c2feb1 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -12,6 +12,7 @@ use DateInterval; use Illuminate\Support\ServiceProvider; +use League\OAuth2\Server\CryptKey; use League\OAuth2\Server\Grant\AuthCodeGrant; use League\OAuth2\Server\Grant\ImplicitGrant; use League\OAuth2\Server\Grant\PasswordGrant; @@ -58,8 +59,8 @@ protected function registerServer() $app->make(ClientRepositoryInterface::class), $app->make(AccessTokenRepositoryInterface::class), $app->make(ScopeRepositoryInterface::class), - $app['config']->get('oauth2.private_key_path'), - $app['config']->get('oauth2.public_key_path'), + new CryptKey($app['config']->get('oauth2.private_key_path'), $app['config']->get('oauth2.key_passphrase')), + new CryptKey($app['config']->get('oauth2.public_key_path'), $app['config']->get('oauth2.key_passphrase')), $app->make($app['config']->get('oauth2.response_type')), $app->make($app['config']->get('oauth2.authorization_validator')) ); From 7c40000c60ddee1d29f9002c488019f3d6474476 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 15:15:44 +0200 Subject: [PATCH 11/61] psr to httpfoundation --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 0c36e950..ae8f158b 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,8 @@ "illuminate/support": "5.2.*", "illuminate/config": "5.2.*", "league/oauth2-server": "^5.0", - "symfony/psr-http-message-bridge": "^0.2.0" + "symfony/psr-http-message-bridge": "^0.2.0", + "zendframework/zend-diactoros": "^1.3" }, "require-dev": { "orchestra/testbench": "3.2.*", From 45babd9635fa9fc70eabbdcd528d1f0810ce0668 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 15:18:26 +0200 Subject: [PATCH 12/61] fix --- src/Repositories/RepositoriesServiceProvider.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index 9c8418f8..6ebebdd0 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -33,6 +33,6 @@ public function register() $this->app->bind(ClientRepositoryInterface::class, ClientRepository::class); $this->app->bind(RefreshTokenRepositoryInterface::class, RefreshTokenRepository::class); $this->app->bind(ScopeRepositoryInterface::class, ScopeRepository::class); - $this->app->bind(UserRepositoryInterface::class, UserRepositoryInterface::class); + $this->app->bind(UserRepositoryInterface::class, UserRepository::class); } } From 6fc522419556212b07ca1527195f68beb7989b27 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 15:35:20 +0200 Subject: [PATCH 13/61] Fixing --- src/Repositories/UserRepository.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index 416ae573..1d7170fd 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -10,7 +10,7 @@ namespace LucaDegasperi\OAuth2Server\Repositories; -use Illuminate\Contracts\Auth\UserProvider; +use Illuminate\Auth\AuthManager; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; @@ -18,14 +18,14 @@ class UserRepository implements UserRepositoryInterface { /** - * @var UserProvider + * @var AuthManager */ - private $provider; + private $authManager; - public function __construct(UserProvider $provider) + public function __construct(AuthManager $authManager) { - $this->provider = $provider; + $this->authManager = $authManager; } /** @@ -50,7 +50,7 @@ public function getUserEntityByUserCredentials( 'password' => $password, ]; - $user = $this->provider->retrieveByCredentials($credentials); + $user = $this->authManager->getProvider()->retrieveByCredentials($credentials); if (is_null($user)) { @@ -59,7 +59,7 @@ public function getUserEntityByUserCredentials( // TODO: validate grant type and client for user - return $this->provider->validateCredentials($user, $credentials) ? $user : null; + return $this->authManager->getProvider()->validateCredentials($user, $credentials) ? $user : null; } } \ No newline at end of file From dbb8921b60fe3ff3584608e35d7784dd7b9e3b63 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 15:39:19 +0200 Subject: [PATCH 14/61] missing return --- src/OAuth2ServerServiceProvider.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index 67c2feb1..fbe24e17 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -72,6 +72,8 @@ protected function registerServer() ); } + return $server; + }); } From c711ddc399b7e843da28e1c657a7417ad37e06e6 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 18:00:16 +0200 Subject: [PATCH 15/61] Fix method --- .../migrations/2016_04_02_000001_create_oauth_scopes_table.php | 2 +- .../migrations/2016_04_02_000002_create_oauth_clients_table.php | 2 +- .../2016_04_02_000003_create_oauth_client_scopes_table.php | 2 +- .../2016_04_02_000004_create_oauth_auth_codes_table.php | 2 +- .../2016_04_02_000005_create_oauth_access_tokens_table.php | 2 +- .../2016_04_02_000006_create_oauth_auth_code_scopes_table.php | 2 +- ...2016_04_02_000007_create_oauth_access_token_scopes_table.php | 2 +- .../2016_04_02_000008_create_oauth_refresh_tokens_table.php | 2 +- ...016_04_02_000010_create_oauth_client_redirect_uris_table.php | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php index 74e6d9e0..8a5c635e 100644 --- a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php +++ b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php @@ -26,7 +26,7 @@ class CreateOauthScopesTable extends Migration public function up() { Schema::create('oauth_scopes', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->string('identifier')->unique(); $table->string('name'); $table->string('description'); diff --git a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php index bb595bbb..340208d7 100644 --- a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php +++ b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php @@ -26,7 +26,7 @@ class CreateOauthClientsTable extends Migration public function up() { Schema::create('oauth_clients', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->string('identifier')->unique(); $table->string('secret'); $table->string('name'); diff --git a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php index 4146db88..38dab307 100644 --- a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php +++ b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_client_scopes', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->integer('client_id')->unsigned(); $table->integer('scope_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index 0d765b8d..0d7959c4 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_auth_codes', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->string('code')->unique(); $table->string('redirect_uri'); diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php index a51fad48..66eb0933 100644 --- a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_access_tokens', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->string('token')->unique(); $table->integer('client_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php index d2ce4fe1..95f9ff03 100644 --- a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_auth_codes_scopes', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->integer('auth_code_id')->unsigned(); $table->integer('scope_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php index 95c29fbc..6337631f 100644 --- a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php +++ b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_access_token_scopes', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->integer('access_token_id')->unsigned(); $table->integer('scope_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php index 1a13bc42..8002e52a 100644 --- a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_refresh_tokens', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->string('token')->unique(); $table->integer('access_token_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php index 2d5c9f9e..10c0ebbd 100644 --- a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php +++ b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php @@ -27,7 +27,7 @@ public function up() { Schema::create('oauth_client_redirect_uris', function (Blueprint $table) { - $table->primary('id'); + $table->increments('id'); $table->string('uri')->unique(); $table->integer('client_id')->unsigned(); From 07c077baece8cc962501a47d6314e431419589d6 Mon Sep 17 00:00:00 2001 From: Luca Date: Mon, 11 Apr 2016 18:17:50 +0200 Subject: [PATCH 16/61] Fix --- .../2016_04_02_000004_create_oauth_auth_codes_table.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index 0d7959c4..d18f47f6 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -37,7 +37,7 @@ public function up() $table->string('user_id'); // TODO: make it the current timestamp - $table->timestamp('expires_at')->default('CURRENT_TIMESTAMP'); + $table->timestamp('expires_at')->useCurrent(); $table->timestamps(); $table->foreign('client_id')->references('id')->on('oauth_clients')->onDelete('cascade'); From 0286f19c2be3feb3e59a2301ae3c23892b935bc5 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 11:19:00 +0200 Subject: [PATCH 17/61] Begin manual testing --- config/.gitkeep | 0 ...4_02_000002_create_oauth_clients_table.php | 2 +- ...00003_create_oauth_client_scopes_table.php | 2 +- ...2_000004_create_oauth_auth_codes_table.php | 2 +- ...00005_create_oauth_access_tokens_table.php | 2 +- ...06_create_oauth_auth_code_scopes_table.php | 2 +- ...create_oauth_access_token_scopes_table.php | 2 +- ...0008_create_oauth_refresh_tokens_table.php | 2 +- ...reate_oauth_client_redirect_uris_table.php | 2 +- src/Entities/AccessToken.php | 10 --------- src/Entities/AuthCode.php | 10 --------- src/Entities/RefreshToken.php | 11 ---------- src/Guard.php | 6 ++++-- src/OAuth2ServerServiceProvider.php | 21 +++++++++++++++---- src/Repositories/.gitkeep | 0 15 files changed, 29 insertions(+), 45 deletions(-) delete mode 100644 config/.gitkeep delete mode 100644 src/Repositories/.gitkeep diff --git a/config/.gitkeep b/config/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php index 340208d7..b6bde03d 100644 --- a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php +++ b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth clients table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php index 38dab307..b505a78a 100644 --- a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php +++ b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth client scopes table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index d18f47f6..c928b495 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth auth codes table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php index 66eb0933..2e024065 100644 --- a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth access tokens table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php index 95f9ff03..14a9af44 100644 --- a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth auth codes scopes table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php index 6337631f..40c7f16e 100644 --- a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php +++ b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth access token scopes table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php index 8002e52a..192520f2 100644 --- a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth refresh tokens table migration class. * * @author Luca Degasperi */ diff --git a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php index 10c0ebbd..fdf2becd 100644 --- a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php +++ b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php @@ -12,7 +12,7 @@ use Illuminate\Support\Facades\Schema; /** - * This is the create oauth scopes table migration class. + * This is the create oauth client redirect uris table migration class. * * @author Luca Degasperi */ diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index d9d5a43c..8a11bfec 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -134,16 +134,6 @@ public function getScopes() return $this->scopes->toArray(); } - /** - * Has the token expired? - * - * @return bool - */ - public function isExpired() - { - return $this->expires_at->lt(new Carbon()); - } - public function client() { return $this->belongsTo(Client::class); diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index ea595778..f841c2e9 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -148,16 +148,6 @@ public function getScopes() return $this->scopes; } - /** - * Has the token expired? - * - * @return bool - */ - public function isExpired() - { - return $this->expires_at->lt(new Carbon()); - } - public function client() { return $this->belongsTo(Client::class); diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index 5049df70..82f13f51 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -87,17 +87,6 @@ public function getAccessToken() return $this->accessToken; } - /** - * Has the token expired? - * - * @return bool - */ - public function isExpired() - { - return $this->expires_at->lt(new Carbon()); - } - - public function accessToken() { return $this->belongsTo(AccessToken::class); diff --git a/src/Guard.php b/src/Guard.php index 02a1d9e1..079a8a4f 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -17,7 +17,7 @@ use Psr\Http\Message\ServerRequestInterface as Request; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; -use League\OAuth2\Server\Server as ResourceServer; +use League\OAuth2\Server\ResourceServer; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; class Guard implements IlluminateGuard @@ -64,8 +64,8 @@ class Guard implements IlluminateGuard public function __construct(UserProvider $provider, ResourceServer $resourceServer, Request $request) { $this->provider = $provider; - $this->request = $request; $this->resourceServer = $resourceServer; + $this->request = $request; } /** @@ -148,6 +148,8 @@ public function client() } $this->parseRequest(); + + return $this->client; } public function setClient(ClientEntityInterface $client) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index fbe24e17..12a5b7a6 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -20,7 +20,8 @@ use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface; use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; -use League\OAuth2\Server\Server; +use League\OAuth2\Server\AuthorizationServer; +use League\OAuth2\Server\ResourceServer; use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; @@ -53,9 +54,9 @@ public function boot() protected function registerServer() { - $this->app->singleton(Server::class, function ($app) { + $this->app->singleton(AuthorizationServer::class, function ($app) { - $server = new Server( + $server = new AuthorizationServer( $app->make(ClientRepositoryInterface::class), $app->make(AccessTokenRepositoryInterface::class), $app->make(ScopeRepositoryInterface::class), @@ -75,6 +76,18 @@ protected function registerServer() return $server; }); + + $this->app->singleton(ResourceServer::class, function ($app) { + + $server = new ResourceServer( + $app->make(AccessTokenRepositoryInterface::class), + new CryptKey($app['config']->get('oauth2.public_key_path'), $app['config']->get('oauth2.key_passphrase')), + $app->make($app['config']->get('oauth2.authorization_validator')) + ); + + return $server; + + }); } protected function registerGrantTypes() @@ -121,7 +134,7 @@ protected function bootGuard() $this->app['auth']->extend('oauth', function ($app, $name, array $config) { $guard = new Guard( $app['auth']->createUserProvider($config['provider']), - $app->make(Server::class), + $app->make(ResourceServer::class), $app['request'] ); diff --git a/src/Repositories/.gitkeep b/src/Repositories/.gitkeep deleted file mode 100644 index e69de29b..00000000 From f6c00e890775d6e3aca847c706ddc7619b0ef370 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 11:31:52 +0200 Subject: [PATCH 18/61] Adhere to interface --- src/Repositories/ClientRepository.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php index 112ef054..babbf53f 100644 --- a/src/Repositories/ClientRepository.php +++ b/src/Repositories/ClientRepository.php @@ -22,14 +22,17 @@ class ClientRepository implements ClientRepositoryInterface * @param string $clientIdentifier The client's identifier * @param string $grantType The grant type used * @param null|string $clientSecret The client's secret (if sent) + * @param bool $mustValidateSecret If true the client must attempt to validate the secret unless the client + * is confidential * * @return \League\OAuth2\Server\Entities\ClientEntityInterface */ - public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null) + public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true) { + // TODO: check if the client can use the $grantType $query = Client::where('identifier', $clientIdentifier); - if (!is_null($clientSecret)) { + if ($mustValidateSecret) { $query->where('secret', $clientSecret); } From 0438163eb466884911385bc83b2fae01ba456ac2 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 11:59:36 +0200 Subject: [PATCH 19/61] Temporary workaround for user retrival --- src/Repositories/UserRepository.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index 1d7170fd..a0b9befb 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -45,8 +45,9 @@ public function getUserEntityByUserCredentials( ClientEntityInterface $clientEntity ) { + // TODO: allow developer to choose which credentials key to use $credentials = [ - 'username' => $username, + 'email' => $username, 'password' => $password, ]; From 8285b4e2e20e9a62e17bdf732f49483377cdd633 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 12:43:59 +0200 Subject: [PATCH 20/61] Attempt at fixing things --- src/Entities/AccessToken.php | 2 +- src/Repositories/AccessTokenRepository.php | 11 +---------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index 8a11bfec..495c70a7 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -111,7 +111,7 @@ public function getClient() */ public function setClient(ClientEntityInterface $client) { - $this->client()->save($client); + $this->client()->associate($client); } /** diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index 55fc1219..f0375bf2 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -28,16 +28,7 @@ class AccessTokenRepository implements AccessTokenRepositoryInterface */ public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null) { - $accessToken = new AccessToken(); - $accessToken->setClient($clientEntity); - - foreach($scopes as $scope) { - $accessToken->addScope($scope); - } - - $accessToken->setUserIdentifier($userIdentifier); - - return $accessToken; + return new AccessToken(); } /** From 92351ff2d6ea918d056508274999ab68e90083b8 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 12:47:35 +0200 Subject: [PATCH 21/61] another fix --- src/Entities/RefreshToken.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index 82f13f51..6b973a9b 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -74,7 +74,7 @@ public function setExpiryDateTime(\DateTime $dateTime) */ public function setAccessToken(AccessTokenEntityInterface $accessToken) { - $this->accessToken()->save($accessToken); + $this->accessToken()->associate($accessToken); } /** From a11ae6e591c8688f2caadccf5ab644030e303fe4 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 16:40:24 +0200 Subject: [PATCH 22/61] moving controller logic to a trait to ease user's work --- src/OAuth2ServerServiceProvider.php | 10 +++- src/Traits/OAuthControllerTrait.php | 82 +++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 src/Traits/OAuthControllerTrait.php diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index 12a5b7a6..70427421 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -94,13 +94,19 @@ protected function registerGrantTypes() { $this->app->bind(AuthCodeGrant::class, function ($app, $parameters = []) { - return new AuthCodeGrant( + $grant = new AuthCodeGrant( $app->make(AuthCodeRepositoryInterface::class), $app->make(RefreshTokenRepositoryInterface::class), - $app->make(UserRepositoryInterface::class), new DateInterval('PT' . $parameters['auth_code_ttl'] . 'S') ); + if(array_key_exists($parameters['code_exchange_proof'])) { + if($parameters['code_exchange_proof'] === true) { + $grant->enableCodeExchangeProof(); + } + } + + return $grant; }); $this->app->bind(ImplicitGrant::class, function ($app, $parameters = []) { diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php new file mode 100644 index 00000000..6ab433cb --- /dev/null +++ b/src/Traits/OAuthControllerTrait.php @@ -0,0 +1,82 @@ +respondToAccessTokenRequest($request, $response); + } catch (OAuthServerException $e) { + return $e->generateHttpResponse($response); + } catch (\Exception $e) { + // Unknown exception + $body = new Stream('php://temp', 'r+'); + $body->write($e->getMessage()); + + return $response->withStatus(500)->withBody($body); + } + } + + public function doAuthorize(ServerRequestInterface $request, AuthorizationServer $server) + { + $response = new Response(); + try { + // Validate the HTTP request and return an AuthorizationRequest object. + // The auth request object can be serialized into a user's session + $authRequest = $server->validateAuthorizationRequest($request); + // Once the user has logged in set the user on the AuthorizationRequest + if (strtolower($request->getMethod()) === 'post') { + $authRequest->setUser(Auth::user()); + + // (true = approved, false = denied) + $authRequest->setAuthorizationApproved($this->getAuthorizationApprovedAttribute($request)); + + // Return the HTTP redirect response + return $server->completeAuthorizationRequest($authRequest, $response); + } else { + return $this->getAuthorizationView($authRequest, $request->getUri()->getQuery()); + } + + } catch (OAuthServerException $exception) { + return $exception->generateHttpResponse($response); + } catch (\Exception $exception) { + $body = new Stream('php://temp', 'r+'); + $body->write($exception->getMessage()); + return $response->withStatus(500)->withBody($body); + } + } + + public function getAuthorizationView(AuthorizationRequest $authRequest, $queryString) + { + $view = property_exists($this, 'authorizationView') ? $this->authorizationView : 'auth.authorize'; + return view($view) + ->with('authRequest', $authRequest) + ->with('queryString', $queryString); + } + + public function getAuthorizationApprovedAttribute(ServerRequestInterface $request) + { + $attribute = property_exists($this, + 'authorizationApprovedAttribute') ? $this->authorizationApprovedAttribute : 'authorize'; + return $request->getAttribute($attribute, false); + } +} \ No newline at end of file From cf5488a959f82e1c0b43d4d253186db22f47c84b Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 16:49:39 +0200 Subject: [PATCH 23/61] Loading a default view for ease of use --- src/OAuth2ServerServiceProvider.php | 2 ++ src/Traits/OAuthControllerTrait.php | 2 +- views/authorize.blade.php | 0 3 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 views/authorize.blade.php diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index 70427421..5a10202e 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -50,6 +50,8 @@ public function boot() $this->bootMigrationPublishing(); $this->bootGuard(); + + $this->loadViewsFrom(__DIR__ . '/../views', 'oauth2server'); } protected function registerServer() diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index 6ab433cb..e018563d 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -67,7 +67,7 @@ public function doAuthorize(ServerRequestInterface $request, AuthorizationServer public function getAuthorizationView(AuthorizationRequest $authRequest, $queryString) { - $view = property_exists($this, 'authorizationView') ? $this->authorizationView : 'auth.authorize'; + $view = property_exists($this, 'authorizationView') ? $this->authorizationView : 'oauth2server::authorize'; return view($view) ->with('authRequest', $authRequest) ->with('queryString', $queryString); diff --git a/views/authorize.blade.php b/views/authorize.blade.php new file mode 100644 index 00000000..e69de29b From 17f1c2bcc8aa8be4bfb7d8bc807d5764b2580838 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 21:23:34 +0200 Subject: [PATCH 24/61] wrong syntax --- src/OAuth2ServerServiceProvider.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index 5a10202e..b59ec7bc 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -102,7 +102,7 @@ protected function registerGrantTypes() new DateInterval('PT' . $parameters['auth_code_ttl'] . 'S') ); - if(array_key_exists($parameters['code_exchange_proof'])) { + if(array_key_exists('code_exchange_proof', $parameters)) { if($parameters['code_exchange_proof'] === true) { $grant->enableCodeExchangeProof(); } From 868b3236415417f6ba86d0a82aba212a49f55204 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 21:54:32 +0200 Subject: [PATCH 25/61] Some files --- src/Traits/OAuthControllerTrait.php | 12 +++-- views/app.blade.php | 82 +++++++++++++++++++++++++++++ views/authorize.blade.php | 45 ++++++++++++++++ 3 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 views/app.blade.php diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index e018563d..1765449d 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -75,8 +75,14 @@ public function getAuthorizationView(AuthorizationRequest $authRequest, $querySt public function getAuthorizationApprovedAttribute(ServerRequestInterface $request) { - $attribute = property_exists($this, - 'authorizationApprovedAttribute') ? $this->authorizationApprovedAttribute : 'authorize'; - return $request->getAttribute($attribute, false); + $attribute = property_exists($this, 'authorizationApprovedAttribute') ? $this->authorizationApprovedAttribute : 'authorize'; + return $this->getRequestParameter($attribute, $request, false); + } + + protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null) + { + $requestParameters = (array)$request->getParsedBody(); + + return isset($requestParameters[$parameter]) ? $requestParameters[$parameter] : $default; } } \ No newline at end of file diff --git a/views/app.blade.php b/views/app.blade.php new file mode 100644 index 00000000..59bc34d4 --- /dev/null +++ b/views/app.blade.php @@ -0,0 +1,82 @@ + + + + + + + + Laravel + + + + + + + + {{-- --}} + + + + + + +@yield('content') + + + + +{{-- --}} + + diff --git a/views/authorize.blade.php b/views/authorize.blade.php index e69de29b..0d39f08c 100644 --- a/views/authorize.blade.php +++ b/views/authorize.blade.php @@ -0,0 +1,45 @@ +@extends('oauth2server::app') + +@section('content') +
+
+
+
+
Authorize App
+
+
+ {{ csrf_field() }} + + + +
+
+ + +
+
+
+ +
+ {{ csrf_field() }} + + + +
+
+ + +
+
+
+ +
+
+
+
+
+@endsection From 487056c015310991bae92133ec8d22853a57f07a Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 21:58:29 +0200 Subject: [PATCH 26/61] boolean casting --- src/Traits/OAuthControllerTrait.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index 1765449d..7196ff53 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -76,7 +76,7 @@ public function getAuthorizationView(AuthorizationRequest $authRequest, $querySt public function getAuthorizationApprovedAttribute(ServerRequestInterface $request) { $attribute = property_exists($this, 'authorizationApprovedAttribute') ? $this->authorizationApprovedAttribute : 'authorize'; - return $this->getRequestParameter($attribute, $request, false); + return (bool)$this->getRequestParameter($attribute, $request, false); } protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null) From 59283e60be4c328eab2d51dab82f605393c1dac3 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 22:02:05 +0200 Subject: [PATCH 27/61] relationship save fix --- src/Entities/AuthCode.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index f841c2e9..90c35419 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -125,7 +125,7 @@ public function getClient() */ public function setClient(ClientEntityInterface $client) { - $this->client()->save($client); + $this->client()->associate($client); } /** @@ -145,7 +145,7 @@ public function addScope(ScopeEntityInterface $scope) */ public function getScopes() { - return $this->scopes; + return $this->scopes->toArray(); } public function client() From 01d1cfc784627509df594e9c54a4b704fe7be494 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 22:10:56 +0200 Subject: [PATCH 28/61] redirect uris can be null when default one for client is used --- .../2016_04_02_000004_create_oauth_auth_codes_table.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index c928b495..a6f724cf 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -29,7 +29,7 @@ public function up() $table->increments('id'); $table->string('code')->unique(); - $table->string('redirect_uri'); + $table->string('redirect_uri')->nullable(); $table->integer('client_id')->unsigned(); From 514dfa7f6821b48d0302048e7772e85205204931 Mon Sep 17 00:00:00 2001 From: Luca Date: Wed, 29 Jun 2016 22:14:56 +0200 Subject: [PATCH 29/61] renaming and fixes --- .../2016_04_02_000006_create_oauth_auth_code_scopes_table.php | 4 ++-- src/Entities/AuthCode.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php index 14a9af44..dabd16f5 100644 --- a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -25,7 +25,7 @@ class CreateOauthAuthCodeScopesTable extends Migration */ public function up() { - Schema::create('oauth_auth_codes_scopes', function (Blueprint $table) { + Schema::create('oauth_auth_code_scopes', function (Blueprint $table) { $table->increments('id'); $table->integer('auth_code_id')->unsigned(); @@ -51,6 +51,6 @@ public function up() */ public function down() { - Schema::drop('oauth_auth_codes_scopes'); + Schema::drop('oauth_auth_code_scopes'); } } \ No newline at end of file diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 90c35419..455a978f 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -105,7 +105,7 @@ public function setUserIdentifier($identifier) */ public function getUserIdentifier() { - return $this->user->getIdentifier(); + return $this->user_id; } /** From 5ca77ede6a1a2d1df3c996e734f0632d1fa119ff Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 10:19:59 +0200 Subject: [PATCH 30/61] Improved guard --- src/Guard.php | 7 +++++-- src/OAuth2ServerServiceProvider.php | 2 +- src/Traits/OAuthControllerTrait.php | 12 +++-------- views/authorize.blade.php | 25 +++++++---------------- views/{app.blade.php => layout.blade.php} | 0 5 files changed, 16 insertions(+), 30 deletions(-) rename views/{app.blade.php => layout.blade.php} (100%) diff --git a/src/Guard.php b/src/Guard.php index 079a8a4f..cee73cc9 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -19,6 +19,7 @@ use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\ResourceServer; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; +use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory; class Guard implements IlluminateGuard { @@ -65,7 +66,8 @@ public function __construct(UserProvider $provider, ResourceServer $resourceServ { $this->provider = $provider; $this->resourceServer = $resourceServer; - $this->request = $request; + $psr7Factory = new DiactorosFactory(); + $this->request = $psr7Factory->createRequest($request); } /** @@ -166,7 +168,8 @@ public function setClient(ClientEntityInterface $client) */ public function setRequest(Request $request) { - $this->request = $request; + $psr7Factory = new DiactorosFactory(); + $this->request = $psr7Factory->createRequest($request); return $this; } diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index b59ec7bc..fe7c29c1 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -139,7 +139,7 @@ protected function registerGrantTypes() protected function bootGuard() { - $this->app['auth']->extend('oauth', function ($app, $name, array $config) { + $this->app['auth']->extend('oauth2', function ($app, $name, array $config) { $guard = new Guard( $app['auth']->createUserProvider($config['provider']), $app->make(ResourceServer::class), diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index 7196ff53..e37b9986 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -27,12 +27,8 @@ public function postAccessToken(ServerRequestInterface $request, AuthorizationSe return $server->respondToAccessTokenRequest($request, $response); } catch (OAuthServerException $e) { return $e->generateHttpResponse($response); - } catch (\Exception $e) { - // Unknown exception - $body = new Stream('php://temp', 'r+'); - $body->write($e->getMessage()); - - return $response->withStatus(500)->withBody($body); + } catch (\Exception $exception) { + return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))->generateHttpResponse($response); } } @@ -59,9 +55,7 @@ public function doAuthorize(ServerRequestInterface $request, AuthorizationServer } catch (OAuthServerException $exception) { return $exception->generateHttpResponse($response); } catch (\Exception $exception) { - $body = new Stream('php://temp', 'r+'); - $body->write($exception->getMessage()); - return $response->withStatus(500)->withBody($body); + return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))->generateHttpResponse($response); } } diff --git a/views/authorize.blade.php b/views/authorize.blade.php index 0d39f08c..e931d4bb 100644 --- a/views/authorize.blade.php +++ b/views/authorize.blade.php @@ -1,4 +1,4 @@ -@extends('oauth2server::app') +@extends('oauth2server::layout') @section('content')
@@ -7,30 +7,19 @@
Authorize App
-
+ {{ csrf_field() }} - + {{ $authRequest->getClient()->name }}
- -
-
-
- -
- {{ csrf_field() }} - - - -
-
-
diff --git a/views/app.blade.php b/views/layout.blade.php similarity index 100% rename from views/app.blade.php rename to views/layout.blade.php From 76eb55ed13aedbfe2fadd1e9bd378f5a2488d1d8 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 10:57:25 +0200 Subject: [PATCH 31/61] Use illuminate request and do conversion inside --- src/Guard.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Guard.php b/src/Guard.php index cee73cc9..f283001f 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -14,7 +14,7 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Guard as IlluminateGuard; use Illuminate\Contracts\Auth\UserProvider; -use Psr\Http\Message\ServerRequestInterface as Request; +use Illuminate\Http\Request; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\ResourceServer; @@ -191,6 +191,7 @@ protected function parseRequest() $this->accessToken = null; $this->exception = $exception; } + // TODO: catch other exceptions as well. } public function getException() From b19bb3f95af16c0e6f8f78fbc5763d414e41f202 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 11:25:32 +0200 Subject: [PATCH 32/61] added access token parameter --- src/Guard.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Guard.php b/src/Guard.php index f283001f..3c86751b 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -184,6 +184,7 @@ protected function parseRequest() // TODO: parse client into entity $this->client = $this->request->getAttribute('oauth_client_id'); $this->scopes = $this->request->getAttribute('oauth_scopes', []); + $this->accessToken = $this->request->getAttribute('oauth_access_token_id'); } catch (OAuthServerException $exception) { $this->user = null; From 76cb94e0160d79daa34bbee862b4cf6f843de887 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 16:04:44 +0200 Subject: [PATCH 33/61] casting client to entity --- src/Guard.php | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Guard.php b/src/Guard.php index 3c86751b..506c8349 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -54,6 +54,10 @@ class Guard implements IlluminateGuard * @var ResourceServer */ private $resourceServer; + /** + * @var ClientRepositoryInterface + */ + private $clientRepository; /** * Guard constructor. @@ -61,13 +65,20 @@ class Guard implements IlluminateGuard * @param UserProvider $provider * @param ResourceServer $resourceServer * @param Request $request + * @param ClientRepositoryInterface $clientRepository */ - public function __construct(UserProvider $provider, ResourceServer $resourceServer, Request $request) + public function __construct( + UserProvider $provider, + ResourceServer $resourceServer, + Request $request, + ClientRepositoryInterface $clientRepository + ) { $this->provider = $provider; $this->resourceServer = $resourceServer; $psr7Factory = new DiactorosFactory(); $this->request = $psr7Factory->createRequest($request); + $this->clientRepository = $clientRepository; } /** @@ -180,9 +191,7 @@ protected function parseRequest() $this->request = $this->resourceServer->validateAuthenticatedRequest($this->request); $this->user = $this->provider->retrieveById($this->request->getAttribute('oauth_user_id')); - - // TODO: parse client into entity - $this->client = $this->request->getAttribute('oauth_client_id'); + $this->client = $this->clientRepository->getClientEntity($this->request->getAttribute('oauth_client_id')); $this->scopes = $this->request->getAttribute('oauth_scopes', []); $this->accessToken = $this->request->getAttribute('oauth_access_token_id'); From 69924e7d90b055e8366b6bd04edc23d811ce0734 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 16:07:00 +0200 Subject: [PATCH 34/61] Fix constructor --- src/OAuth2ServerServiceProvider.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index fe7c29c1..ebdc8990 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -143,7 +143,8 @@ protected function bootGuard() $guard = new Guard( $app['auth']->createUserProvider($config['provider']), $app->make(ResourceServer::class), - $app['request'] + $app['request'], + $app->make(ClientRepositoryInterface::class) ); $app->refresh('request', $guard, 'setRequest'); From 1163b03df5d30872fbd8f5a404fea26e21d6fa53 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 16:09:45 +0200 Subject: [PATCH 35/61] added use statement --- src/Guard.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Guard.php b/src/Guard.php index 506c8349..d1f1efe6 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -17,6 +17,7 @@ use Illuminate\Http\Request; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; +use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\ResourceServer; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory; From a34dd1d8023fe52ebacc2656d598c8149ab3ba39 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 16:11:52 +0200 Subject: [PATCH 36/61] workaround --- src/Guard.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Guard.php b/src/Guard.php index d1f1efe6..6affd1b3 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -192,7 +192,7 @@ protected function parseRequest() $this->request = $this->resourceServer->validateAuthenticatedRequest($this->request); $this->user = $this->provider->retrieveById($this->request->getAttribute('oauth_user_id')); - $this->client = $this->clientRepository->getClientEntity($this->request->getAttribute('oauth_client_id')); + $this->client = $this->clientRepository->getClientEntity($this->request->getAttribute('oauth_client_id'), null); $this->scopes = $this->request->getAttribute('oauth_scopes', []); $this->accessToken = $this->request->getAttribute('oauth_access_token_id'); From 6031edf683b848e6dba71a7f14d80debef38f823 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 30 Jun 2016 16:15:18 +0200 Subject: [PATCH 37/61] second fix --- src/Guard.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Guard.php b/src/Guard.php index 6affd1b3..a924910e 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -192,7 +192,8 @@ protected function parseRequest() $this->request = $this->resourceServer->validateAuthenticatedRequest($this->request); $this->user = $this->provider->retrieveById($this->request->getAttribute('oauth_user_id')); - $this->client = $this->clientRepository->getClientEntity($this->request->getAttribute('oauth_client_id'), null); + // TODO: open PR for the null workaround + $this->client = $this->clientRepository->getClientEntity($this->request->getAttribute('oauth_client_id'), null, null, false); $this->scopes = $this->request->getAttribute('oauth_scopes', []); $this->accessToken = $this->request->getAttribute('oauth_access_token_id'); From 1336dbcd631bb6a9d5544abe60ee3b6bd2ff34d8 Mon Sep 17 00:00:00 2001 From: Luca Date: Tue, 5 Jul 2016 13:47:46 +0200 Subject: [PATCH 38/61] Working on scopes --- src/Guard.php | 1 + src/Repositories/RepositoriesServiceProvider.php | 4 +++- src/Repositories/ScopeRepository.php | 10 ++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Guard.php b/src/Guard.php index a924910e..92bba690 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -55,6 +55,7 @@ class Guard implements IlluminateGuard * @var ResourceServer */ private $resourceServer; + /** * @var ClientRepositoryInterface */ diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index 6ebebdd0..feffc5b4 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -32,7 +32,9 @@ public function register() $this->app->bind(AuthCodeRepositoryInterface::class, AuthCodeRepository::class); $this->app->bind(ClientRepositoryInterface::class, ClientRepository::class); $this->app->bind(RefreshTokenRepositoryInterface::class, RefreshTokenRepository::class); - $this->app->bind(ScopeRepositoryInterface::class, ScopeRepository::class); $this->app->bind(UserRepositoryInterface::class, UserRepository::class); + $this->app->bind(ScopeRepositoryInterface::class, function ($app) { + return new ScopeRepository($app['config']->get('oauth2.default_scopes', [])); + }); } } diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index ab645e40..6b3137d3 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -17,6 +17,16 @@ class ScopeRepository implements ScopeRepositoryInterface { + /** + * @var string + */ + private $defaultScopes; + + public function __construct($defaultScopes = []) + { + + $this->defaultScopes = $defaultScopes; + } /** * Return information about a scope. From 25f5926c16a2bc6f6a413d8a93304e41ac65fd9a Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 5 Jul 2016 14:16:32 +0200 Subject: [PATCH 39/61] Run coding standards fixer script --- config/oauth2.php | 9 +++---- ...04_02_000001_create_oauth_scopes_table.php | 2 +- ...4_02_000002_create_oauth_clients_table.php | 2 +- ...00003_create_oauth_client_scopes_table.php | 2 +- ...2_000004_create_oauth_auth_codes_table.php | 4 ++-- ...00005_create_oauth_access_tokens_table.php | 4 ++-- ...06_create_oauth_auth_code_scopes_table.php | 2 +- ...create_oauth_access_token_scopes_table.php | 2 +- ...0008_create_oauth_refresh_tokens_table.php | 4 ++-- ...reate_oauth_client_redirect_uris_table.php | 4 ++-- src/Entities/AccessToken.php | 4 ++-- src/Entities/AuthCode.php | 2 +- src/Entities/Client.php | 5 ++-- src/Entities/RedirectUri.php | 4 +--- src/Entities/RefreshToken.php | 5 ++-- src/Entities/Scope.php | 3 +-- src/Guard.php | 20 +++++++--------- src/OAuth2ServerServiceProvider.php | 24 +++++++++---------- src/Repositories/AccessTokenRepository.php | 4 ++-- src/Repositories/AuthCodeRepository.php | 5 ++-- src/Repositories/ClientRepository.php | 3 +-- src/Repositories/RefreshTokenRepository.php | 4 ++-- .../RepositoriesServiceProvider.php | 1 - src/Repositories/ScopeRepository.php | 7 +++--- src/Repositories/UserRepository.php | 8 ++----- src/Traits/OAuthControllerTrait.php | 19 +++++++-------- 26 files changed, 67 insertions(+), 86 deletions(-) diff --git a/config/oauth2.php b/config/oauth2.php index b28aa01a..ed2e476a 100644 --- a/config/oauth2.php +++ b/config/oauth2.php @@ -30,10 +30,9 @@ [ 'class' => \League\OAuth2\Server\Grant\PasswordGrant::class, 'access_token_ttl' => '', - ] + ], ], - /* |-------------------------------------------------------------------------- | Private Key Path @@ -43,7 +42,6 @@ */ 'private_key_path' => 'file://path_to_private_key/private.key', - /* |-------------------------------------------------------------------------- | Public Key Path @@ -76,7 +74,6 @@ */ 'response_type' => \League\OAuth2\Server\ResponseTypes\BearerTokenResponse::class, - /* |-------------------------------------------------------------------------- | Authorization Validator @@ -87,6 +84,6 @@ | Default value is \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::class | */ - 'authorization_validator' => \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::class + 'authorization_validator' => \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::class, -]; \ No newline at end of file +]; diff --git a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php index 8a5c635e..f9b167b2 100644 --- a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php +++ b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php @@ -43,4 +43,4 @@ public function down() { Schema::drop('oauth_scopes'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php index b6bde03d..5f6abe44 100644 --- a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php +++ b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php @@ -44,4 +44,4 @@ public function down() { Schema::drop('oauth_scopes'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php index b505a78a..65de5bef 100644 --- a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php +++ b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php @@ -53,4 +53,4 @@ public function down() { Schema::drop('oauth_client_scopes'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index a6f724cf..1db9f447 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -26,7 +26,7 @@ class CreateOauthAuthCodesTable extends Migration public function up() { Schema::create('oauth_auth_codes', function (Blueprint $table) { - + $table->increments('id'); $table->string('code')->unique(); $table->string('redirect_uri')->nullable(); @@ -53,4 +53,4 @@ public function down() { Schema::drop('oauth_client_scopes'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php index 2e024065..bb3343cf 100644 --- a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -26,7 +26,7 @@ class CreateOauthAccessTokensTable extends Migration public function up() { Schema::create('oauth_access_tokens', function (Blueprint $table) { - + $table->increments('id'); $table->string('token')->unique(); @@ -52,4 +52,4 @@ public function down() { Schema::drop('oauth_access_tokens'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php index dabd16f5..9945f172 100644 --- a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -53,4 +53,4 @@ public function down() { Schema::drop('oauth_auth_code_scopes'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php index 40c7f16e..fae510bd 100644 --- a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php +++ b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php @@ -53,4 +53,4 @@ public function down() { Schema::drop('oauth_access_token_scopes'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php index 192520f2..66821620 100644 --- a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php @@ -26,7 +26,7 @@ class CreateOauthRefreshTokensTable extends Migration public function up() { Schema::create('oauth_refresh_tokens', function (Blueprint $table) { - + $table->increments('id'); $table->string('token')->unique(); @@ -49,4 +49,4 @@ public function down() { Schema::drop('oauth_refresh_tokens'); } -} \ No newline at end of file +} diff --git a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php index fdf2becd..cfbc21a9 100644 --- a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php +++ b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php @@ -26,7 +26,7 @@ class CreateOauthClientRedirectUrisTable extends Migration public function up() { Schema::create('oauth_client_redirect_uris', function (Blueprint $table) { - + $table->increments('id'); $table->string('uri')->unique(); $table->integer('client_id')->unsigned(); @@ -46,4 +46,4 @@ public function down() { Schema::drop('oauth_client_redirect_uris'); } -} \ No newline at end of file +} diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index 495c70a7..5ceb2a88 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -10,11 +10,11 @@ namespace LucaDegasperi\OAuth2Server\Entities; +use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\ScopeEntityInterface; -use Carbon\Carbon; use League\OAuth2\Server\Entities\Traits\AccessTokenTrait; /** @@ -148,4 +148,4 @@ public function refreshToken() { return $this->hasOne(RefreshToken::class); } -} \ No newline at end of file +} diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 455a978f..0da606ef 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -162,4 +162,4 @@ public function scopes() { return $this->belongsToMany(Scope::class, 'oauth_auth_code_scopes'); } -} \ No newline at end of file +} diff --git a/src/Entities/Client.php b/src/Entities/Client.php index db6a9e2b..1017e754 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -83,12 +83,11 @@ public function setRedirectUri($redirectUri) */ public function getRedirectUri() { - return $this->redirectUris->map(function($item, $key){ + return $this->redirectUris->map(function ($item, $key) { return $item->uri; })->toArray(); } - public function accessTokens() { return $this->hasMany(AccessToken::class); @@ -108,4 +107,4 @@ public function redirectUris() { return $this->hasMany(RedirectUri::class); } -} \ No newline at end of file +} diff --git a/src/Entities/RedirectUri.php b/src/Entities/RedirectUri.php index 5d9a2a63..283b4dbc 100644 --- a/src/Entities/RedirectUri.php +++ b/src/Entities/RedirectUri.php @@ -18,12 +18,10 @@ */ class RedirectUri extends Model { - protected $table = 'oauth_client_redirect_uris'; - public function client() { return $this->belongsTo(Client::class); } -} \ No newline at end of file +} diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index 6b973a9b..c9d8a9a8 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -10,10 +10,10 @@ namespace LucaDegasperi\OAuth2Server\Entities; +use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; -use Carbon\Carbon; /** * @property string token @@ -22,7 +22,6 @@ */ class RefreshToken extends Model implements RefreshTokenEntityInterface { - protected $table = 'oauth_refresh_tokens'; protected $dates = ['expires_at']; @@ -91,4 +90,4 @@ public function accessToken() { return $this->belongsTo(AccessToken::class); } -} \ No newline at end of file +} diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php index b2b1f619..4b328331 100644 --- a/src/Entities/Scope.php +++ b/src/Entities/Scope.php @@ -19,7 +19,6 @@ */ class Scope extends Model implements ScopeEntityInterface { - protected $table = 'oauth_scopes'; /** @@ -56,4 +55,4 @@ public function clients() { return $this->belongsToMany(Client::class, 'oauth_client_scopes'); } -} \ No newline at end of file +} diff --git a/src/Guard.php b/src/Guard.php index 92bba690..2f07a12f 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -11,7 +11,6 @@ namespace LucaDegasperi\OAuth2Server; use Illuminate\Auth\GuardHelpers; -use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Guard as IlluminateGuard; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Http\Request; @@ -19,7 +18,6 @@ use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\ResourceServer; -use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory; class Guard implements IlluminateGuard @@ -55,7 +53,7 @@ class Guard implements IlluminateGuard * @var ResourceServer */ private $resourceServer; - + /** * @var ClientRepositoryInterface */ @@ -74,8 +72,7 @@ public function __construct( ResourceServer $resourceServer, Request $request, ClientRepositoryInterface $clientRepository - ) - { + ) { $this->provider = $provider; $this->resourceServer = $resourceServer; $psr7Factory = new DiactorosFactory(); @@ -103,6 +100,7 @@ public function user() * Validate a user's credentials. * * @param array $credentials + * * @return bool */ public function validate(array $credentials = []) @@ -129,7 +127,6 @@ protected function hasValidCredentials($user, $credentials) return !is_null($user) && $this->provider->validateCredentials($user, $credentials); } - public function scopes() { if (!is_null($this->scopes)) { @@ -152,9 +149,8 @@ public function accessToken() return $this->accessToken; } - /** - * Get the client doing the request + * Get the client doing the request. */ public function client() { @@ -170,6 +166,7 @@ public function client() public function setClient(ClientEntityInterface $client) { $this->client = $client; + return $this; } @@ -177,19 +174,20 @@ public function setClient(ClientEntityInterface $client) * Set the current request instance. * * @param Request $request + * * @return $this */ public function setRequest(Request $request) { $psr7Factory = new DiactorosFactory(); $this->request = $psr7Factory->createRequest($request); + return $this; } protected function parseRequest() { try { - $this->request = $this->resourceServer->validateAuthenticatedRequest($this->request); $this->user = $this->provider->retrieveById($this->request->getAttribute('oauth_user_id')); @@ -197,7 +195,6 @@ protected function parseRequest() $this->client = $this->clientRepository->getClientEntity($this->request->getAttribute('oauth_client_id'), null, null, false); $this->scopes = $this->request->getAttribute('oauth_scopes', []); $this->accessToken = $this->request->getAttribute('oauth_access_token_id'); - } catch (OAuthServerException $exception) { $this->user = null; $this->client = null; @@ -220,6 +217,7 @@ public function getResourceServer() public function setResourceServer(ResourceServer $server) { $this->resourceServer = $server; + return $this; } -} \ No newline at end of file +} diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index ebdc8990..f644320a 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -12,19 +12,19 @@ use DateInterval; use Illuminate\Support\ServiceProvider; +use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\CryptKey; use League\OAuth2\Server\Grant\AuthCodeGrant; use League\OAuth2\Server\Grant\ImplicitGrant; use League\OAuth2\Server\Grant\PasswordGrant; use League\OAuth2\Server\Grant\RefreshTokenGrant; +use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface; +use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; +use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; -use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\ResourceServer; -use League\OAuth2\Server\Repositories\ClientRepositoryInterface; -use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; -use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; class OAuth2ServerServiceProvider extends ServiceProvider { @@ -51,7 +51,7 @@ public function boot() $this->bootGuard(); - $this->loadViewsFrom(__DIR__ . '/../views', 'oauth2server'); + $this->loadViewsFrom(__DIR__.'/../views', 'oauth2server'); } protected function registerServer() @@ -71,7 +71,7 @@ protected function registerServer() foreach ($app['config']->get('oauth2.grant_types') as $grantType) { $server->enableGrantType( $app->make($grantType['class'], $grantType), - new DateInterval('PT' . $grantType['access_token_ttl'] . 'S') + new DateInterval('PT'.$grantType['access_token_ttl'].'S') ); } @@ -99,11 +99,11 @@ protected function registerGrantTypes() $grant = new AuthCodeGrant( $app->make(AuthCodeRepositoryInterface::class), $app->make(RefreshTokenRepositoryInterface::class), - new DateInterval('PT' . $parameters['auth_code_ttl'] . 'S') + new DateInterval('PT'.$parameters['auth_code_ttl'].'S') ); - if(array_key_exists('code_exchange_proof', $parameters)) { - if($parameters['code_exchange_proof'] === true) { + if (array_key_exists('code_exchange_proof', $parameters)) { + if ($parameters['code_exchange_proof'] === true) { $grant->enableCodeExchangeProof(); } } @@ -160,7 +160,7 @@ protected function bootGuard() */ protected function bootMigrationPublishing() { - $source = realpath(__DIR__ . '/../database/migrations/'); + $source = realpath(__DIR__.'/../database/migrations/'); $this->publishes([$source => database_path('migrations')], 'migrations'); } @@ -171,8 +171,8 @@ protected function bootMigrationPublishing() */ protected function bootConfigPublishing() { - $source = realpath(__DIR__ . '/../config/oauth2.php'); + $source = realpath(__DIR__.'/../config/oauth2.php'); $this->publishes([$source => config_path('oauth2.php')]); $this->mergeConfigFrom($source, 'oauth2'); } -} \ No newline at end of file +} diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index f0375bf2..1b982855 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -18,7 +18,7 @@ class AccessTokenRepository implements AccessTokenRepositoryInterface { /** - * Create a new access token + * Create a new access token. * * @param \League\OAuth2\Server\Entities\ClientEntityInterface $clientEntity * @param \League\OAuth2\Server\Entities\ScopeEntityInterface[] $scopes @@ -62,4 +62,4 @@ public function isAccessTokenRevoked($tokenId) { return AccessToken::where('token', $tokenId)->count() === 0; } -} \ No newline at end of file +} diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php index 16cf5d0f..50d2b155 100644 --- a/src/Repositories/AuthCodeRepository.php +++ b/src/Repositories/AuthCodeRepository.php @@ -16,9 +16,8 @@ class AuthCodeRepository implements AuthCodeRepositoryInterface { - /** - * Creates a new AuthCode + * Creates a new AuthCode. * * @return \League\OAuth2\Server\Entities\AuthCodeEntityInterface */ @@ -58,4 +57,4 @@ public function isAuthCodeRevoked($codeId) { return AuthCode::where('code', $codeId)->count() === 0; } -} \ No newline at end of file +} diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php index babbf53f..101c72c9 100644 --- a/src/Repositories/ClientRepository.php +++ b/src/Repositories/ClientRepository.php @@ -15,7 +15,6 @@ class ClientRepository implements ClientRepositoryInterface { - /** * Get a client. * @@ -38,4 +37,4 @@ public function getClientEntity($clientIdentifier, $grantType, $clientSecret = n return $query->first(); } -} \ No newline at end of file +} diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php index 9454a212..8268da45 100644 --- a/src/Repositories/RefreshTokenRepository.php +++ b/src/Repositories/RefreshTokenRepository.php @@ -17,7 +17,7 @@ class RefreshTokenRepository implements RefreshTokenRepositoryInterface { /** - * Creates a new refresh token + * Creates a new refresh token. * * @return RefreshTokenEntityInterface */ @@ -57,4 +57,4 @@ public function isRefreshTokenRevoked($tokenId) { return RefreshToken::where('token', $tokenId)->count() === 0; } -} \ No newline at end of file +} diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index feffc5b4..38f02272 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -20,7 +20,6 @@ class RepositoriesServiceProvider extends ServiceProvider { - /** * Register the service provider. * diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index 6b3137d3..1a42efea 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -24,7 +24,6 @@ class ScopeRepository implements ScopeRepositoryInterface public function __construct($defaultScopes = []) { - $this->defaultScopes = $defaultScopes; } @@ -64,11 +63,11 @@ public function finalizeScopes( $clientScopes = $clientEntity->scopes; // TODO: this can be simplified imho. - $scopes = array_filter($scopes, function($scope) use ($clientScopes) { + $scopes = array_filter($scopes, function ($scope) use ($clientScopes) { $identifier = $scope->getItentifier(); - return $clientScopes->contains(function($key, $value) use ($identifier) { + return $clientScopes->contains(function ($key, $value) use ($identifier) { $value->getIdentifer() == $identifier; }); @@ -78,4 +77,4 @@ public function finalizeScopes( return $scopes; } -} \ No newline at end of file +} diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index a0b9befb..067b7560 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -16,7 +16,6 @@ class UserRepository implements UserRepositoryInterface { - /** * @var AuthManager */ @@ -24,7 +23,6 @@ class UserRepository implements UserRepositoryInterface public function __construct(AuthManager $authManager) { - $this->authManager = $authManager; } @@ -54,13 +52,11 @@ public function getUserEntityByUserCredentials( $user = $this->authManager->getProvider()->retrieveByCredentials($credentials); if (is_null($user)) { - - return null; + return; } // TODO: validate grant type and client for user return $this->authManager->getProvider()->validateCredentials($user, $credentials) ? $user : null; - } -} \ No newline at end of file +} diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index e37b9986..f4e672c9 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -3,19 +3,17 @@ * Created by PhpStorm. * User: Luca * Date: 29/06/16 - * Time: 16:18 + * Time: 16:18. */ namespace LucaDegasperi\OAuth2Server\Traits; -use League\OAuth2\Server\RequestTypes\AuthorizationRequest; -use League\OAuth2\Server\Exception\OAuthServerException; +use Illuminate\Support\Facades\Auth; use League\OAuth2\Server\AuthorizationServer; +use League\OAuth2\Server\Exception\OAuthServerException; +use League\OAuth2\Server\RequestTypes\AuthorizationRequest; use Psr\Http\Message\ServerRequestInterface; -use Illuminate\Support\Facades\Auth; use Zend\Diactoros\Response; -use Zend\Diactoros\Stream; - trait OAuthControllerTrait { @@ -51,7 +49,6 @@ public function doAuthorize(ServerRequestInterface $request, AuthorizationServer } else { return $this->getAuthorizationView($authRequest, $request->getUri()->getQuery()); } - } catch (OAuthServerException $exception) { return $exception->generateHttpResponse($response); } catch (\Exception $exception) { @@ -62,6 +59,7 @@ public function doAuthorize(ServerRequestInterface $request, AuthorizationServer public function getAuthorizationView(AuthorizationRequest $authRequest, $queryString) { $view = property_exists($this, 'authorizationView') ? $this->authorizationView : 'oauth2server::authorize'; + return view($view) ->with('authRequest', $authRequest) ->with('queryString', $queryString); @@ -70,13 +68,14 @@ public function getAuthorizationView(AuthorizationRequest $authRequest, $querySt public function getAuthorizationApprovedAttribute(ServerRequestInterface $request) { $attribute = property_exists($this, 'authorizationApprovedAttribute') ? $this->authorizationApprovedAttribute : 'authorize'; - return (bool)$this->getRequestParameter($attribute, $request, false); + + return (bool) $this->getRequestParameter($attribute, $request, false); } protected function getRequestParameter($parameter, ServerRequestInterface $request, $default = null) { - $requestParameters = (array)$request->getParsedBody(); + $requestParameters = (array) $request->getParsedBody(); return isset($requestParameters[$parameter]) ? $requestParameters[$parameter] : $default; } -} \ No newline at end of file +} From f80d19efba9b140eeeae3d8bf5231eaa2812d3bf Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 5 Jul 2016 14:56:46 +0200 Subject: [PATCH 40/61] Add service provider test --- .gitignore | 2 -- composer.json | 10 ++++------ phpspec.yml.dist | 6 ------ tests/.gitkeep | 0 tests/AbstractTestCase.php | 35 +++++++++++++++++++++++++++++++++++ tests/ServiceProviderTest.php | 24 ++++++++++++++++++++++++ 6 files changed, 63 insertions(+), 14 deletions(-) delete mode 100644 phpspec.yml.dist delete mode 100644 tests/.gitkeep create mode 100644 tests/AbstractTestCase.php create mode 100644 tests/ServiceProviderTest.php diff --git a/.gitignore b/.gitignore index de76a418..81b92580 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,3 @@ composer.lock phpunit.xml -phpspec.yml vendor -.idea diff --git a/composer.json b/composer.json index ae8f158b..d11feee5 100644 --- a/composer.json +++ b/composer.json @@ -15,22 +15,20 @@ ], "require": { "php": ">=5.5.9", - "illuminate/database": "5.2.*", + "illuminate/config": "5.2.*", "illuminate/console": "5.2.*", "illuminate/contracts": "5.2.*", + "illuminate/database": "5.2.*", "illuminate/http": "5.2.*", "illuminate/support": "5.2.*", - "illuminate/config": "5.2.*", "league/oauth2-server": "^5.0", "symfony/psr-http-message-bridge": "^0.2.0", "zendframework/zend-diactoros": "^1.3" }, "require-dev": { - "orchestra/testbench": "3.2.*", - "phpunit/phpunit": "^5.0", - "phpspec/phpspec": "^2.2", + "graham-campbell/testbench": "^3.1", "mockery/mockery": "^0.9.4", - "henrikbjorn/phpspec-code-coverage": "^2.0" + "phpunit/phpunit": "^4.8 || ^5.0" }, "autoload": { "psr-4": { diff --git a/phpspec.yml.dist b/phpspec.yml.dist deleted file mode 100644 index 15c3dd41..00000000 --- a/phpspec.yml.dist +++ /dev/null @@ -1,6 +0,0 @@ -suites: - package_suite: - namespace: LucaDegasperi\OAuth2Server - src_path: src - spec_prefix: unit - spec_path: tests diff --git a/tests/.gitkeep b/tests/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/AbstractTestCase.php b/tests/AbstractTestCase.php new file mode 100644 index 00000000..ee4adc09 --- /dev/null +++ b/tests/AbstractTestCase.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace LucaDegasperi\OAuth2Server\Tests; + +use GrahamCampbell\TestBench\AbstractPackageTestCase; +use LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider; + +/** + * This is the abstract test class. + * + * @author Vincent Klaiber + */ +abstract class AbstractTestCase extends AbstractPackageTestCase +{ + /** + * Get the service provider class. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * + * @return string + */ + protected function getServiceProviderClass($app) + { + return OAuth2ServerServiceProvider::class; + } +} diff --git a/tests/ServiceProviderTest.php b/tests/ServiceProviderTest.php new file mode 100644 index 00000000..390a594e --- /dev/null +++ b/tests/ServiceProviderTest.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace LucaDegasperi\OAuth2Server\Tests; + +use GrahamCampbell\TestBenchCore\ServiceProviderTrait; + +/** + * This is the service provider test class. + * + * @author Vincent Klaiber + */ +class ServiceProviderTest extends AbstractTestCase +{ + use ServiceProviderTrait; +} From 2bdadf36c37c12caf57e6a38e23a29b66c9d4f2d Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 5 Jul 2016 14:57:19 +0200 Subject: [PATCH 41/61] Update php support --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d11feee5..200565a5 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ } ], "require": { - "php": ">=5.5.9", + "php": "^5.6.4 || ^7.0", "illuminate/config": "5.2.*", "illuminate/console": "5.2.*", "illuminate/contracts": "5.2.*", From 0b7cc3d9dc179a311e28459b64fca2a7e5eab651 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 5 Jul 2016 14:59:14 +0200 Subject: [PATCH 42/61] Add laravel 5.3 support --- composer.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/composer.json b/composer.json index 200565a5..f4982602 100644 --- a/composer.json +++ b/composer.json @@ -15,14 +15,14 @@ ], "require": { "php": "^5.6.4 || ^7.0", - "illuminate/config": "5.2.*", - "illuminate/console": "5.2.*", - "illuminate/contracts": "5.2.*", - "illuminate/database": "5.2.*", - "illuminate/http": "5.2.*", - "illuminate/support": "5.2.*", + "illuminate/config": "5.2.* || 5.3.*", + "illuminate/console": "5.2.* || 5.3.*", + "illuminate/contracts": "5.2.* || 5.3.*", + "illuminate/database": "5.2.* || 5.3.*", + "illuminate/http": "5.2.* || 5.3.*", + "illuminate/support": "5.2.* || 5.3.*", "league/oauth2-server": "^5.0", - "symfony/psr-http-message-bridge": "^0.2.0", + "symfony/psr-http-message-bridge": "^0.2", "zendframework/zend-diactoros": "^1.3" }, "require-dev": { From 82db7db44fa74297b312cbab7b957bf514e1bf21 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Thu, 7 Jul 2016 08:47:37 +0200 Subject: [PATCH 43/61] Update dependencies --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index f4982602..2ad63074 100644 --- a/composer.json +++ b/composer.json @@ -26,9 +26,9 @@ "zendframework/zend-diactoros": "^1.3" }, "require-dev": { - "graham-campbell/testbench": "^3.1", - "mockery/mockery": "^0.9.4", - "phpunit/phpunit": "^4.8 || ^5.0" + "graham-campbell/testbench": "^3.2", + "mockery/mockery": "^0.9.5", + "phpunit/phpunit": "^5.4" }, "autoload": { "psr-4": { From 6f8c31b1e42242884e8e72679c98b9749736af48 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Thu, 7 Jul 2016 08:48:14 +0200 Subject: [PATCH 44/61] Remove 5.5 from travis tests --- .travis.yml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index e989d1df..e20e2ff8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,6 @@ language: php php: - - 5.5.9 - - 5.5 - 5.6 - 7.0 - hhvm @@ -10,12 +8,11 @@ php: sudo: false install: - - travis_retry composer install --no-interaction --prefer-source + - travis_retry composer install --no-interaction script: - - if [ "$TRAVIS_PHP_VERSION" != "5.5.9" ] && [ "$TRAVIS_PHP_VERSION" != "5.5" ] && [ "$TRAVIS_PHP_VERSION" != "5.6" ]; then vendor/bin/phpunit; vendor/bin/phpspec run; fi - - if [ "$TRAVIS_PHP_VERSION" == "5.5.9" ] || [ "$TRAVIS_PHP_VERSION" == "5.5" ] || [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then vendor/bin/phpunit --coverage-clover build/logs/clover.xml; fi + - vendor/bin/phpunit --coverage-clover build/logs/clover.xml after_script: - - if [ "$TRAVIS_PHP_VERSION" == "5.5.9" ] || [ "$TRAVIS_PHP_VERSION" == "5.5" ] || [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi - - if [ "$TRAVIS_PHP_VERSION" == "5.5.9" ] || [ "$TRAVIS_PHP_VERSION" == "5.5" ] || [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml; fi + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml From d87965fe269f933e0f29e96eaf9ed0b860911a2f Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Thu, 7 Jul 2016 08:58:16 +0200 Subject: [PATCH 45/61] Remove phpspsec --- .gitattributes | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index e48cc897..2a212f23 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,7 +7,6 @@ /.travis.yml export-ignore /.scrutinizer.yml export-ignore /phpunit.xml.dist export-ignore -/phpspec.xml.dist export-ignore /CHANGELOG.md export-ignore /CONTRIBUTING.md export-ignore /README.md export-ignore From 73540ef42bd28ebe12048acb08f4a814566c1ce1 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Thu, 7 Jul 2016 08:59:55 +0200 Subject: [PATCH 46/61] Working on changelog --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6725657..6eebfe5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # CHANGELOG +## 6.0.0 (upcoming) + +- Rewrite for league/oauth2-server 5.0 +- Added Laravel 5.3 support +- Added auth guard support +- Removed PHP 5.5 support + ## 5.1.1 (released 2015-12-22) - Fix Laravel 5.2 support bug From 53f51f3d32d501de13fdf06ca32cbeaa7bf35caa Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Thu, 7 Jul 2016 09:05:14 +0200 Subject: [PATCH 47/61] Update config and migrations methods --- src/OAuth2ServerServiceProvider.php | 75 ++++++++++++++++------------- 1 file changed, 42 insertions(+), 33 deletions(-) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index f644320a..ba42f5b3 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -26,32 +26,64 @@ use League\OAuth2\Server\Repositories\UserRepositoryInterface; use League\OAuth2\Server\ResourceServer; +/** + * This is the oauth2 server service provider class. + * + * @author Luca Degasperi + * @author Vincent Klaiber + */ class OAuth2ServerServiceProvider extends ServiceProvider { /** - * Register the service provider. + * Boot the service provider. * * @return void */ - public function register() + public function boot() { - $this->registerGrantTypes(); - $this->registerServer(); + $this->setupConfig(); + $this->setupMigrations(); + + $this->bootGuard(); + + $this->loadViewsFrom(__DIR__.'/../views', 'oauth2server'); } /** - * Boot the authentication services for the application. + * Setup the config. * * @return void */ - public function boot() + protected function setupConfig() { - $this->bootConfigPublishing(); - $this->bootMigrationPublishing(); + $source = realpath(__DIR__.'/../config/oauth2.php'); - $this->bootGuard(); + $this->publishes([$source => config_path('oauth2.php')]); - $this->loadViewsFrom(__DIR__.'/../views', 'oauth2server'); + $this->mergeConfigFrom($source, 'oauth2'); + } + + /** + * Setup the migrations. + * + * @return void + */ + protected function setupMigrations() + { + $source = realpath(__DIR__.'/../database/migrations/'); + + $this->publishes([$source => database_path('migrations')], 'migrations'); + } + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $this->registerGrantTypes(); + $this->registerServer(); } protected function registerServer() @@ -152,27 +184,4 @@ protected function bootGuard() return $guard; }); } - - /** - * Setup the migrations. - * - * @return void - */ - protected function bootMigrationPublishing() - { - $source = realpath(__DIR__.'/../database/migrations/'); - $this->publishes([$source => database_path('migrations')], 'migrations'); - } - - /** - * Setup the config. - * - * @return void - */ - protected function bootConfigPublishing() - { - $source = realpath(__DIR__.'/../config/oauth2.php'); - $this->publishes([$source => config_path('oauth2.php')]); - $this->mergeConfigFrom($source, 'oauth2'); - } } From ed83388e56bf01b6faa0df0a5cef625abbc0d71d Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Thu, 7 Jul 2016 09:05:52 +0200 Subject: [PATCH 48/61] Add resources folder --- {views => resources/views}/authorize.blade.php | 0 {views => resources/views}/layout.blade.php | 0 src/OAuth2ServerServiceProvider.php | 2 +- 3 files changed, 1 insertion(+), 1 deletion(-) rename {views => resources/views}/authorize.blade.php (100%) rename {views => resources/views}/layout.blade.php (100%) diff --git a/views/authorize.blade.php b/resources/views/authorize.blade.php similarity index 100% rename from views/authorize.blade.php rename to resources/views/authorize.blade.php diff --git a/views/layout.blade.php b/resources/views/layout.blade.php similarity index 100% rename from views/layout.blade.php rename to resources/views/layout.blade.php diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index ba42f5b3..599f46e7 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -46,7 +46,7 @@ public function boot() $this->bootGuard(); - $this->loadViewsFrom(__DIR__.'/../views', 'oauth2server'); + $this->loadViewsFrom(__DIR__.'/../resources/views', 'oauth2server'); } /** From b0313721f62432625d75b1c6cb9a83bca6ec123c Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:18:01 +0200 Subject: [PATCH 49/61] Add php_cs file --- .php_cs | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/Guard.php | 2 +- 2 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 .php_cs diff --git a/.php_cs b/.php_cs new file mode 100644 index 00000000..a7747b02 --- /dev/null +++ b/.php_cs @@ -0,0 +1,89 @@ + + +For the full copyright and license information, please view the LICENSE +file that was distributed with this source code. +EOF; + +$fixers = [ + // PSR-0 + '-psr0', + + // PSR-1 + 'encoding', + 'short_tag', + + // Symfony + 'array_element_white_space_after_comma', + 'blankline_after_open_tag', + 'concat_without_spaces', + 'duplicate_semicolon', + 'empty_return', + 'extra_empty_lines', + 'function_typehint_space', + 'include', + 'join_function', + 'list_commas', + 'multiline_array_trailing_comma', + 'namespace_no_leading_whitespace', + 'new_with_braces', + 'no_blank_lines_after_class_opening', + 'no_empty_lines_after_phpdocs', + 'object_operator', + 'operators_spaces', + 'phpdoc_indent', + 'phpdoc_no_access', + 'phpdoc_no_package', + 'phpdoc_scalar', + 'phpdoc_separation', + 'phpdoc_short_description', + 'phpdoc_to_comment', + 'phpdoc_trim', + 'phpdoc_type_to_var', + 'phpdoc_var_without_name', + 'print_to_echo', + 'remove_leading_slash_use', + 'remove_lines_between_uses', + 'return', + 'self_accessor', + 'short_bool_cast', + 'single_array_no_trailing_comma', + 'single_blank_line_before_namespace', + 'single_quote', + 'spaces_before_semicolon', + 'spaces_cast', + 'standardize_not_equal', + 'ternary_spaces', + 'trim_array_spaces', + 'unalign_double_arrow', + 'unalign_equals', + 'unary_operators_spaces', + 'unneeded_control_parentheses', + 'unused_use', + 'whitespacy_lines', + + // Contrib + 'header_comment', + 'multiline_spaces_before_semicolon', + 'newline_after_open_tag', + 'ordered_use', + 'php_unit_construct', + 'php_unit_strict', + 'phpdoc_order', + 'short_array_syntax', + 'short_echo_tag', +]; + +Symfony\CS\Fixer\Contrib\HeaderCommentFixer::setHeader($header); + +$finder = Symfony\CS\Finder\DefaultFinder::create() + ->in(__DIR__); + +return Symfony\CS\Config\Config::create() + ->level(Symfony\CS\FixerInterface::PSR2_LEVEL) + ->fixers($fixers) + ->finder($finder); diff --git a/src/Guard.php b/src/Guard.php index 2f07a12f..c6d69329 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -1,6 +1,6 @@ * From 5635ff38fe11ba1633e8555870f61d493883b891 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:18:30 +0200 Subject: [PATCH 50/61] Run coding standards script --- config/oauth2.php | 2 +- .../2016_04_02_000001_create_oauth_scopes_table.php | 4 +++- .../2016_04_02_000002_create_oauth_clients_table.php | 4 +++- ...6_04_02_000003_create_oauth_client_scopes_table.php | 4 +++- ...2016_04_02_000004_create_oauth_auth_codes_table.php | 4 +++- ...6_04_02_000005_create_oauth_access_tokens_table.php | 4 +++- ...4_02_000006_create_oauth_auth_code_scopes_table.php | 4 +++- ...2_000007_create_oauth_access_token_scopes_table.php | 4 +++- ..._04_02_000008_create_oauth_refresh_tokens_table.php | 4 +++- ..._000010_create_oauth_client_redirect_uris_table.php | 4 +++- src/Entities/AccessToken.php | 3 ++- src/Entities/AuthCode.php | 3 ++- src/Entities/Client.php | 3 ++- src/Entities/RedirectUri.php | 3 ++- src/Entities/RefreshToken.php | 3 ++- src/Entities/Scope.php | 3 ++- src/Guard.php | 1 + src/OAuth2ServerServiceProvider.php | 3 ++- src/Repositories/AccessTokenRepository.php | 3 ++- src/Repositories/AuthCodeRepository.php | 3 ++- src/Repositories/ClientRepository.php | 3 ++- src/Repositories/RefreshTokenRepository.php | 3 ++- src/Repositories/RepositoriesServiceProvider.php | 3 ++- src/Repositories/ScopeRepository.php | 3 ++- src/Repositories/UserRepository.php | 3 ++- src/Traits/OAuthControllerTrait.php | 10 ++++++++++ tests/AbstractTestCase.php | 2 +- tests/ServiceProviderTest.php | 2 +- 28 files changed, 69 insertions(+), 26 deletions(-) diff --git a/config/oauth2.php b/config/oauth2.php index ed2e476a..cf0156a9 100644 --- a/config/oauth2.php +++ b/config/oauth2.php @@ -1,7 +1,7 @@ * diff --git a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php index f9b167b2..1169b45c 100644 --- a/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php +++ b/database/migrations/2016_04_02_000001_create_oauth_scopes_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php index 5f6abe44..4daa23ef 100644 --- a/database/migrations/2016_04_02_000002_create_oauth_clients_table.php +++ b/database/migrations/2016_04_02_000002_create_oauth_clients_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php index 65de5bef..2fea723a 100644 --- a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php +++ b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index 1db9f447..7c23d121 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php index bb3343cf..9c101026 100644 --- a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php index 9945f172..a5b466cd 100644 --- a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php index fae510bd..0ac80e25 100644 --- a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php +++ b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php index 66821620..4f57387d 100644 --- a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php index cfbc21a9..9b5a30fc 100644 --- a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php +++ b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php @@ -1,12 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index 5ceb2a88..f7685aad 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -1,6 +1,7 @@ * diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 0da606ef..42337ac4 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -1,6 +1,7 @@ * diff --git a/src/Entities/Client.php b/src/Entities/Client.php index 1017e754..b2efc7d6 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -1,6 +1,7 @@ * diff --git a/src/Entities/RedirectUri.php b/src/Entities/RedirectUri.php index 283b4dbc..e19b7a16 100644 --- a/src/Entities/RedirectUri.php +++ b/src/Entities/RedirectUri.php @@ -1,6 +1,7 @@ * diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index c9d8a9a8..18b02085 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -1,6 +1,7 @@ * diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php index 4b328331..5e8812fa 100644 --- a/src/Entities/Scope.php +++ b/src/Entities/Scope.php @@ -1,6 +1,7 @@ * diff --git a/src/Guard.php b/src/Guard.php index c6d69329..a30c558e 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -1,4 +1,5 @@ * diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index 1b982855..dc19bf5d 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -1,6 +1,7 @@ * diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php index 50d2b155..b3a5ca8e 100644 --- a/src/Repositories/AuthCodeRepository.php +++ b/src/Repositories/AuthCodeRepository.php @@ -1,6 +1,7 @@ * diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php index 101c72c9..5fe0d078 100644 --- a/src/Repositories/ClientRepository.php +++ b/src/Repositories/ClientRepository.php @@ -1,6 +1,7 @@ * diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php index 8268da45..805e54e1 100644 --- a/src/Repositories/RefreshTokenRepository.php +++ b/src/Repositories/RefreshTokenRepository.php @@ -1,6 +1,7 @@ * diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index 38f02272..7b11b12d 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -1,6 +1,7 @@ * diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index 1a42efea..aa4b60a4 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -1,6 +1,7 @@ * diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index 067b7560..a8c6a742 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -1,6 +1,7 @@ * diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index f4e672c9..c09a193d 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -1,4 +1,14 @@ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + /** * Created by PhpStorm. * User: Luca diff --git a/tests/AbstractTestCase.php b/tests/AbstractTestCase.php index ee4adc09..24f7452c 100644 --- a/tests/AbstractTestCase.php +++ b/tests/AbstractTestCase.php @@ -1,7 +1,7 @@ * diff --git a/tests/ServiceProviderTest.php b/tests/ServiceProviderTest.php index 390a594e..8ae89b0e 100644 --- a/tests/ServiceProviderTest.php +++ b/tests/ServiceProviderTest.php @@ -1,7 +1,7 @@ * From 03fa6e57db5dc4e80621e3720924f9de45834988 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:20:22 +0200 Subject: [PATCH 51/61] Update readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ea4d2dbc..be2b5862 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# OAuth 2.0 Server for Laravel +# Laravel OAuth 2.0 ![oauth2-server-laravel](https://cloud.githubusercontent.com/assets/499192/9065550/751404ba-3ad2-11e5-9f92-3d4d5d4b9c54.png) @@ -23,6 +23,7 @@ 5.0.x | 4.0.x |>= 5.4 5.1.x | 5.0.x |>= 5.5.9 5.2.x | 5.1.x |>= 5.5.9 + 5.3.x | 6.0.x |>= 5.6.4 ## Documentation From 69539440277de57b522d4779c4b0c315be0fd093 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:23:35 +0200 Subject: [PATCH 52/61] CS fixes --- ...016_04_02_000003_create_oauth_client_scopes_table.php | 1 - .../2016_04_02_000004_create_oauth_auth_codes_table.php | 1 - ...016_04_02_000005_create_oauth_access_tokens_table.php | 1 - ..._04_02_000006_create_oauth_auth_code_scopes_table.php | 1 - ..._02_000007_create_oauth_access_token_scopes_table.php | 1 - ...16_04_02_000008_create_oauth_refresh_tokens_table.php | 1 - ...02_000010_create_oauth_client_redirect_uris_table.php | 1 - src/OAuth2ServerServiceProvider.php | 9 --------- src/Repositories/RepositoriesServiceProvider.php | 8 ++++---- src/Repositories/ScopeRepository.php | 9 +-------- src/Traits/OAuthControllerTrait.php | 7 ------- 11 files changed, 5 insertions(+), 35 deletions(-) diff --git a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php index 2fea723a..7640a803 100644 --- a/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php +++ b/database/migrations/2016_04_02_000003_create_oauth_client_scopes_table.php @@ -28,7 +28,6 @@ class CreateOauthClientScopesTable extends Migration public function up() { Schema::create('oauth_client_scopes', function (Blueprint $table) { - $table->increments('id'); $table->integer('client_id')->unsigned(); $table->integer('scope_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php index 7c23d121..de2fe651 100644 --- a/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php +++ b/database/migrations/2016_04_02_000004_create_oauth_auth_codes_table.php @@ -28,7 +28,6 @@ class CreateOauthAuthCodesTable extends Migration public function up() { Schema::create('oauth_auth_codes', function (Blueprint $table) { - $table->increments('id'); $table->string('code')->unique(); $table->string('redirect_uri')->nullable(); diff --git a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php index 9c101026..2a48329c 100644 --- a/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php +++ b/database/migrations/2016_04_02_000005_create_oauth_access_tokens_table.php @@ -28,7 +28,6 @@ class CreateOauthAccessTokensTable extends Migration public function up() { Schema::create('oauth_access_tokens', function (Blueprint $table) { - $table->increments('id'); $table->string('token')->unique(); diff --git a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php index a5b466cd..58746dc8 100644 --- a/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php +++ b/database/migrations/2016_04_02_000006_create_oauth_auth_code_scopes_table.php @@ -28,7 +28,6 @@ class CreateOauthAuthCodeScopesTable extends Migration public function up() { Schema::create('oauth_auth_code_scopes', function (Blueprint $table) { - $table->increments('id'); $table->integer('auth_code_id')->unsigned(); $table->integer('scope_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php index 0ac80e25..4e10ae7b 100644 --- a/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php +++ b/database/migrations/2016_04_02_000007_create_oauth_access_token_scopes_table.php @@ -28,7 +28,6 @@ class CreateOauthAccessTokenScopesTable extends Migration public function up() { Schema::create('oauth_access_token_scopes', function (Blueprint $table) { - $table->increments('id'); $table->integer('access_token_id')->unsigned(); $table->integer('scope_id')->unsigned(); diff --git a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php index 4f57387d..1c3fd096 100644 --- a/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2016_04_02_000008_create_oauth_refresh_tokens_table.php @@ -28,7 +28,6 @@ class CreateOauthRefreshTokensTable extends Migration public function up() { Schema::create('oauth_refresh_tokens', function (Blueprint $table) { - $table->increments('id'); $table->string('token')->unique(); diff --git a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php index 9b5a30fc..34293ff9 100644 --- a/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php +++ b/database/migrations/2016_04_02_000010_create_oauth_client_redirect_uris_table.php @@ -28,7 +28,6 @@ class CreateOauthClientRedirectUrisTable extends Migration public function up() { Schema::create('oauth_client_redirect_uris', function (Blueprint $table) { - $table->increments('id'); $table->string('uri')->unique(); $table->integer('client_id')->unsigned(); diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index c9175723..68d4b20a 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -90,7 +90,6 @@ public function register() protected function registerServer() { $this->app->singleton(AuthorizationServer::class, function ($app) { - $server = new AuthorizationServer( $app->make(ClientRepositoryInterface::class), $app->make(AccessTokenRepositoryInterface::class), @@ -113,7 +112,6 @@ protected function registerServer() }); $this->app->singleton(ResourceServer::class, function ($app) { - $server = new ResourceServer( $app->make(AccessTokenRepositoryInterface::class), new CryptKey($app['config']->get('oauth2.public_key_path'), $app['config']->get('oauth2.key_passphrase')), @@ -121,14 +119,12 @@ protected function registerServer() ); return $server; - }); } protected function registerGrantTypes() { $this->app->bind(AuthCodeGrant::class, function ($app, $parameters = []) { - $grant = new AuthCodeGrant( $app->make(AuthCodeRepositoryInterface::class), $app->make(RefreshTokenRepositoryInterface::class), @@ -149,24 +145,19 @@ protected function registerGrantTypes() return new ImplicitGrant( $app->make(UserRepositoryInterface::class) ); - }); $this->app->bind(PasswordGrant::class, function ($app, $parameters = []) { - return new PasswordGrant( $app->make(UserRepositoryInterface::class), $app->make(RefreshTokenRepositoryInterface::class) ); - }); $this->app->bind(RefreshTokenGrant::class, function ($app, $parameters = []) { - return new RefreshTokenGrant( $app->make(RefreshTokenRepositoryInterface::class) ); - }); } diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index 7b11b12d..d836139a 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -28,11 +28,11 @@ class RepositoriesServiceProvider extends ServiceProvider */ public function register() { - $this->app->bind(AccessTokenRepositoryInterface::class, AccessTokenRepository::class); - $this->app->bind(AuthCodeRepositoryInterface::class, AuthCodeRepository::class); - $this->app->bind(ClientRepositoryInterface::class, ClientRepository::class); + $this->app->bind(AccessTokenRepositoryInterface::class, AccessTokenRepository::class); + $this->app->bind(AuthCodeRepositoryInterface::class, AuthCodeRepository::class); + $this->app->bind(ClientRepositoryInterface::class, ClientRepository::class); $this->app->bind(RefreshTokenRepositoryInterface::class, RefreshTokenRepository::class); - $this->app->bind(UserRepositoryInterface::class, UserRepository::class); + $this->app->bind(UserRepositoryInterface::class, UserRepository::class); $this->app->bind(ScopeRepositoryInterface::class, function ($app) { return new ScopeRepository($app['config']->get('oauth2.default_scopes', [])); }); diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index aa4b60a4..f197d5fd 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -51,12 +51,7 @@ public function getScopeEntityByIdentifier($identifier) * * @return \League\OAuth2\Server\Entities\ScopeEntityInterface[] */ - public function finalizeScopes( - array $scopes, - $grantType, - ClientEntityInterface $clientEntity, - $userIdentifier = null - ) { + public function finalizeScopes(array $scopes, $grantType, ClientEntityInterface $clientEntity, $userIdentifier = null) { if (!$clientEntity->has('scopes')) { return $scopes; } @@ -65,13 +60,11 @@ public function finalizeScopes( // TODO: this can be simplified imho. $scopes = array_filter($scopes, function ($scope) use ($clientScopes) { - $identifier = $scope->getItentifier(); return $clientScopes->contains(function ($key, $value) use ($identifier) { $value->getIdentifer() == $identifier; }); - }); // TODO: add possibility to append scopes from clients or grants diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index c09a193d..0935aabe 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -9,13 +9,6 @@ * file that was distributed with this source code. */ -/** - * Created by PhpStorm. - * User: Luca - * Date: 29/06/16 - * Time: 16:18. - */ - namespace LucaDegasperi\OAuth2Server\Traits; use Illuminate\Support\Facades\Auth; From 51f89ee0919adaaad02b528d4bce11840e9a48ef Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:25:38 +0200 Subject: [PATCH 53/61] CS fixes --- src/OAuth2ServerServiceProvider.php | 2 -- src/Repositories/ScopeRepository.php | 3 ++- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/OAuth2ServerServiceProvider.php b/src/OAuth2ServerServiceProvider.php index 68d4b20a..ccf8ac48 100644 --- a/src/OAuth2ServerServiceProvider.php +++ b/src/OAuth2ServerServiceProvider.php @@ -108,7 +108,6 @@ protected function registerServer() } return $server; - }); $this->app->singleton(ResourceServer::class, function ($app) { @@ -141,7 +140,6 @@ protected function registerGrantTypes() }); $this->app->bind(ImplicitGrant::class, function ($app, $parameters = []) { - return new ImplicitGrant( $app->make(UserRepositoryInterface::class) ); diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index f197d5fd..f55994c5 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -51,7 +51,8 @@ public function getScopeEntityByIdentifier($identifier) * * @return \League\OAuth2\Server\Entities\ScopeEntityInterface[] */ - public function finalizeScopes(array $scopes, $grantType, ClientEntityInterface $clientEntity, $userIdentifier = null) { + public function finalizeScopes(array $scopes, $grantType, ClientEntityInterface $clientEntity, $userIdentifier = null) + { if (!$clientEntity->has('scopes')) { return $scopes; } From cfea6f44d91bdbad8a5cf68fe41b8e257322eac7 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:30:12 +0200 Subject: [PATCH 54/61] Add styleci badge --- README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index be2b5862..923bdc37 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,13 @@ [OAuth 2.0](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) authorization server and resource server for the Laravel and Lumen frameworks. Standard compliant thanks to the amazing work by [The League of Extraordinary Packages](http://www.thephpleague.com) OAuth 2.0 authorization server and resource server. -[![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat-square)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) -[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) -[![Build Status](https://img.shields.io/travis/lucadegasperi/oauth2-server-laravel/master.svg?style=flat-square)](https://travis-ci.org/lucadegasperi/oauth2-server-laravel) -[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel/code-structure) -[![Quality Score](https://img.shields.io/scrutinizer/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel) -[![Total Downloads](https://img.shields.io/packagist/dt/lucadegasperi/oauth2-server-laravel.svg?style=flat-square)](https://packagist.org/packages/lucadegasperi/oauth2-server-laravel) +[![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) +[![StyleCI](https://styleci.io/repos/13300645/shield?style=flat)](https://styleci.io/repos/13300645) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://travis-ci.org/lucadegasperi/oauth2-server-laravel) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel) +[![Total Downloads](https://img.shields.io/packagist/dt/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://packagist.org/packages/lucadegasperi/oauth2-server-laravel) > **Note:** This package assumes you have a good-enough knowledge of the principles behind the [OAuth 2.0 authorization specification](http://tools.ietf.org/html/rfc6749). From fbb4776911487f22d0d27236389798c902d9985e Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:31:32 +0200 Subject: [PATCH 55/61] Reorder badges --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 923bdc37..ccc081ee 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ [OAuth 2.0](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) authorization server and resource server for the Laravel and Lumen frameworks. Standard compliant thanks to the amazing work by [The League of Extraordinary Packages](http://www.thephpleague.com) OAuth 2.0 authorization server and resource server. -[![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) [![StyleCI](https://styleci.io/repos/13300645/shield?style=flat)](https://styleci.io/repos/13300645) -[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE.md) [![Build Status](https://img.shields.io/travis/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://travis-ci.org/lucadegasperi/oauth2-server-laravel) [![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel/code-structure) [![Quality Score](https://img.shields.io/scrutinizer/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel) +[![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) [![Total Downloads](https://img.shields.io/packagist/dt/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://packagist.org/packages/lucadegasperi/oauth2-server-laravel) +[![License](https://img.shields.io/packagist/l/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://packagist.org/packages/lucadegasperi/oauth2-server-laravel) > **Note:** This package assumes you have a good-enough knowledge of the principles behind the [OAuth 2.0 authorization specification](http://tools.ietf.org/html/rfc6749). From aa75d460e4689f1dc80053c81e95505c58c17a50 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:31:44 +0200 Subject: [PATCH 56/61] Build status should go first --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ccc081ee..461d8b47 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ [OAuth 2.0](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) authorization server and resource server for the Laravel and Lumen frameworks. Standard compliant thanks to the amazing work by [The League of Extraordinary Packages](http://www.thephpleague.com) OAuth 2.0 authorization server and resource server. -[![StyleCI](https://styleci.io/repos/13300645/shield?style=flat)](https://styleci.io/repos/13300645) [![Build Status](https://img.shields.io/travis/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://travis-ci.org/lucadegasperi/oauth2-server-laravel) +[![StyleCI](https://styleci.io/repos/13300645/shield?style=flat)](https://styleci.io/repos/13300645) [![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel/code-structure) [![Quality Score](https://img.shields.io/scrutinizer/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel) [![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) From d6f4fd09c60d031cced7f209ee923f77909d064a Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Fri, 15 Jul 2016 12:32:10 +0200 Subject: [PATCH 57/61] Order by color --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 461d8b47..514bd10e 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ [![StyleCI](https://styleci.io/repos/13300645/shield?style=flat)](https://styleci.io/repos/13300645) [![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel/code-structure) [![Quality Score](https://img.shields.io/scrutinizer/g/lucadegasperi/oauth2-server-laravel/master.svg?style=flat)](https://scrutinizer-ci.com/g/lucadegasperi/oauth2-server-laravel) -[![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) [![Total Downloads](https://img.shields.io/packagist/dt/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://packagist.org/packages/lucadegasperi/oauth2-server-laravel) +[![Latest Version](http://img.shields.io/github/release/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://github.com/lucadegasperi/oauth2-server-laravel/releases) [![License](https://img.shields.io/packagist/l/lucadegasperi/oauth2-server-laravel.svg?style=flat)](https://packagist.org/packages/lucadegasperi/oauth2-server-laravel) > **Note:** This package assumes you have a good-enough knowledge of the principles behind the [OAuth 2.0 authorization specification](http://tools.ietf.org/html/rfc6749). From 2969c26612212edfb19bb8f0da4f9b2db5f3a5dd Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 26 Jul 2016 16:03:21 +0200 Subject: [PATCH 58/61] Add author --- src/Entities/AccessToken.php | 11 ++++------- src/Entities/AuthCode.php | 10 +++------- src/Entities/Client.php | 8 +++----- src/Entities/RedirectUri.php | 5 +++-- src/Entities/RefreshToken.php | 6 +++--- src/Entities/Scope.php | 5 +++-- src/Guard.php | 5 +++++ src/Repositories/AccessTokenRepository.php | 5 +++++ src/Repositories/AuthCodeRepository.php | 5 +++++ src/Repositories/ClientRepository.php | 5 +++++ src/Repositories/RefreshTokenRepository.php | 5 +++++ src/Repositories/RepositoriesServiceProvider.php | 5 +++++ src/Repositories/ScopeRepository.php | 5 +++++ src/Repositories/UserRepository.php | 5 +++++ src/Traits/OAuthControllerTrait.php | 5 +++++ 15 files changed, 64 insertions(+), 26 deletions(-) diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index f7685aad..c516a314 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -18,14 +18,11 @@ use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Entities\Traits\AccessTokenTrait; + /** - * @property mixed client - * @property string client_id - * @property int|string user_id - * @property Carbon expires_at - * @property mixed id - * @property string token - * @property mixed scopes + * This is the access token model class. + * + * @author Luca Degasperi */ class AccessToken extends Model implements AccessTokenEntityInterface { diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 42337ac4..dabb8581 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -19,13 +19,9 @@ use League\OAuth2\Server\Entities\ScopeEntityInterface; /** - * @property mixed redirect_uri - * @property mixed code - * @property mixed user - * @property Carbon expires_at - * @property mixed scopes - * @property int|string user_id - * @property mixed client + * This is the auth code model class. + * + * @author Luca Degasperi */ class AuthCode extends Model implements AuthCodeEntityInterface { diff --git a/src/Entities/Client.php b/src/Entities/Client.php index b2efc7d6..53a0bd0f 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -15,11 +15,9 @@ use League\OAuth2\Server\Entities\ClientEntityInterface; /** - * @property mixed id - * @property mixed name - * @property string redirect_uri - * @property string identifier - * @property mixed redirectUris + * This is the client model class. + * + * @author Luca Degasperi */ class Client extends Model implements ClientEntityInterface { diff --git a/src/Entities/RedirectUri.php b/src/Entities/RedirectUri.php index e19b7a16..695262a1 100644 --- a/src/Entities/RedirectUri.php +++ b/src/Entities/RedirectUri.php @@ -14,8 +14,9 @@ use Illuminate\Database\Eloquent\Model; /** - * @property mixed id - * @property mixed identifier + * This is the redirect uri model class. + * + * @author Luca Degasperi */ class RedirectUri extends Model { diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index 18b02085..d28384be 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -17,9 +17,9 @@ use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; /** - * @property string token - * @property Carbon expires_at - * @property mixed accessToken + * This is the refresh token model class. + * + * @author Luca Degasperi */ class RefreshToken extends Model implements RefreshTokenEntityInterface { diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php index 5e8812fa..26d8b7df 100644 --- a/src/Entities/Scope.php +++ b/src/Entities/Scope.php @@ -15,8 +15,9 @@ use League\OAuth2\Server\Entities\ScopeEntityInterface; /** - * @property mixed id - * @property mixed identifier + * This is the scope model class. + * + * @author Luca Degasperi */ class Scope extends Model implements ScopeEntityInterface { diff --git a/src/Guard.php b/src/Guard.php index a30c558e..76e72601 100644 --- a/src/Guard.php +++ b/src/Guard.php @@ -21,6 +21,11 @@ use League\OAuth2\Server\ResourceServer; use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory; +/** + * This is the guard class. + * + * @author Luca Degasperi + */ class Guard implements IlluminateGuard { use GuardHelpers; diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index dc19bf5d..bd7ae5ce 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -16,6 +16,11 @@ use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\AccessToken; +/** + * This is the access token repository class. + * + * @author Luca Degasperi + */ class AccessTokenRepository implements AccessTokenRepositoryInterface { /** diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php index b3a5ca8e..bca6dba0 100644 --- a/src/Repositories/AuthCodeRepository.php +++ b/src/Repositories/AuthCodeRepository.php @@ -15,6 +15,11 @@ use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\AuthCode; +/** + * This is the auth code repository class. + * + * @author Luca Degasperi + */ class AuthCodeRepository implements AuthCodeRepositoryInterface { /** diff --git a/src/Repositories/ClientRepository.php b/src/Repositories/ClientRepository.php index 5fe0d078..9210f301 100644 --- a/src/Repositories/ClientRepository.php +++ b/src/Repositories/ClientRepository.php @@ -14,6 +14,11 @@ use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\Client; +/** + * This is the client repository class. + * + * @author Luca Degasperi + */ class ClientRepository implements ClientRepositoryInterface { /** diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php index 805e54e1..b9500141 100644 --- a/src/Repositories/RefreshTokenRepository.php +++ b/src/Repositories/RefreshTokenRepository.php @@ -15,6 +15,11 @@ use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\RefreshToken; +/** + * This is the refresh token repository class. + * + * @author Luca Degasperi + */ class RefreshTokenRepository implements RefreshTokenRepositoryInterface { /** diff --git a/src/Repositories/RepositoriesServiceProvider.php b/src/Repositories/RepositoriesServiceProvider.php index d836139a..bf16c952 100644 --- a/src/Repositories/RepositoriesServiceProvider.php +++ b/src/Repositories/RepositoriesServiceProvider.php @@ -19,6 +19,11 @@ use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; +/** + * This is the repository service provider class. + * + * @author Luca Degasperi + */ class RepositoriesServiceProvider extends ServiceProvider { /** diff --git a/src/Repositories/ScopeRepository.php b/src/Repositories/ScopeRepository.php index f55994c5..bb0e20b6 100644 --- a/src/Repositories/ScopeRepository.php +++ b/src/Repositories/ScopeRepository.php @@ -16,6 +16,11 @@ use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; use LucaDegasperi\OAuth2Server\Entities\Scope; +/** + * This is the scope repository class. + * + * @author Luca Degasperi + */ class ScopeRepository implements ScopeRepositoryInterface { /** diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index a8c6a742..c4de9963 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -15,6 +15,11 @@ use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\UserRepositoryInterface; +/** + * This is the user repository class. + * + * @author Luca Degasperi + */ class UserRepository implements UserRepositoryInterface { /** diff --git a/src/Traits/OAuthControllerTrait.php b/src/Traits/OAuthControllerTrait.php index 0935aabe..38390d2f 100644 --- a/src/Traits/OAuthControllerTrait.php +++ b/src/Traits/OAuthControllerTrait.php @@ -18,6 +18,11 @@ use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response; +/** + * This is the oauth controller trait. + * + * @author Luca Degasperi + */ trait OAuthControllerTrait { public function postAccessToken(ServerRequestInterface $request, AuthorizationServer $server) From 2bbf3ffae5a3408ad8309cbcfc12d11e865b7e37 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 26 Jul 2016 16:05:31 +0200 Subject: [PATCH 59/61] Add table docblocs --- src/Entities/AccessToken.php | 5 +++++ src/Entities/AuthCode.php | 5 +++++ src/Entities/Client.php | 5 +++++ src/Entities/RedirectUri.php | 5 +++++ src/Entities/RefreshToken.php | 5 +++++ src/Entities/Scope.php | 5 +++++ 6 files changed, 30 insertions(+) diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index c516a314..b33ee121 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -28,6 +28,11 @@ class AccessToken extends Model implements AccessTokenEntityInterface { use AccessTokenTrait; + /** + * The table associated with the model. + * + * @var string + */ protected $table = 'oauth_access_tokens'; protected $dates = ['expires_at']; diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index dabb8581..56259c7d 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -25,6 +25,11 @@ */ class AuthCode extends Model implements AuthCodeEntityInterface { + /** + * The table associated with the model. + * + * @var string + */ protected $table = 'oauth_auth_codes'; protected $dates = ['expires_at']; diff --git a/src/Entities/Client.php b/src/Entities/Client.php index 53a0bd0f..89a09c6e 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -21,6 +21,11 @@ */ class Client extends Model implements ClientEntityInterface { + /** + * The table associated with the model. + * + * @var string + */ protected $table = 'oauth_clients'; /** diff --git a/src/Entities/RedirectUri.php b/src/Entities/RedirectUri.php index 695262a1..716b81ee 100644 --- a/src/Entities/RedirectUri.php +++ b/src/Entities/RedirectUri.php @@ -20,6 +20,11 @@ */ class RedirectUri extends Model { + /** + * The table associated with the model. + * + * @var string + */ protected $table = 'oauth_client_redirect_uris'; public function client() diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index d28384be..7a20ad14 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -23,6 +23,11 @@ */ class RefreshToken extends Model implements RefreshTokenEntityInterface { + /** + * The table associated with the model. + * + * @var string + */ protected $table = 'oauth_refresh_tokens'; protected $dates = ['expires_at']; diff --git a/src/Entities/Scope.php b/src/Entities/Scope.php index 26d8b7df..b1775458 100644 --- a/src/Entities/Scope.php +++ b/src/Entities/Scope.php @@ -21,6 +21,11 @@ */ class Scope extends Model implements ScopeEntityInterface { + /** + * The table associated with the model. + * + * @var string + */ protected $table = 'oauth_scopes'; /** From c1620f582aefdfd960dbd3d9a00e89a2d93e0194 Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 26 Jul 2016 16:06:10 +0200 Subject: [PATCH 60/61] Add date docblocs --- src/Entities/AccessToken.php | 5 +++++ src/Entities/AuthCode.php | 5 +++++ src/Entities/RefreshToken.php | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index b33ee121..5be89422 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -35,6 +35,11 @@ class AccessToken extends Model implements AccessTokenEntityInterface */ protected $table = 'oauth_access_tokens'; + /** + * The attributes that should be mutated to dates. + * + * @var string[] + */ protected $dates = ['expires_at']; /** diff --git a/src/Entities/AuthCode.php b/src/Entities/AuthCode.php index 56259c7d..fe5b3d16 100644 --- a/src/Entities/AuthCode.php +++ b/src/Entities/AuthCode.php @@ -32,6 +32,11 @@ class AuthCode extends Model implements AuthCodeEntityInterface */ protected $table = 'oauth_auth_codes'; + /** + * The attributes that should be mutated to dates. + * + * @var string[] + */ protected $dates = ['expires_at']; /** diff --git a/src/Entities/RefreshToken.php b/src/Entities/RefreshToken.php index 7a20ad14..f34cfcdb 100644 --- a/src/Entities/RefreshToken.php +++ b/src/Entities/RefreshToken.php @@ -30,6 +30,11 @@ class RefreshToken extends Model implements RefreshTokenEntityInterface */ protected $table = 'oauth_refresh_tokens'; + /** + * The attributes that should be mutated to dates. + * + * @var string[] + */ protected $dates = ['expires_at']; /** From 3ea5647d1a2bca11bffcac3d9e0363563cb57efd Mon Sep 17 00:00:00 2001 From: Vincent Klaiber Date: Tue, 26 Jul 2016 16:37:02 +0200 Subject: [PATCH 61/61] CS fix --- src/Entities/AccessToken.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Entities/AccessToken.php b/src/Entities/AccessToken.php index 5be89422..85f0c55e 100644 --- a/src/Entities/AccessToken.php +++ b/src/Entities/AccessToken.php @@ -18,7 +18,6 @@ use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Entities\Traits\AccessTokenTrait; - /** * This is the access token model class. *