Implements: blueprint openid-oauth2-user-service

[smarcet] - #5029 - UserService

Change-Id: Ie4da1f28810e7562a9dc9ceb06228040848eebdf
This commit is contained in:
smarcet 2014-02-06 19:51:58 -03:00
parent ebeb5d2dbf
commit 9abe4b2196
131 changed files with 2312 additions and 1391 deletions

View File

@ -78,7 +78,7 @@ return array(
|
*/
'providers' => array(
'providers' => array(
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
'Illuminate\Cache\CacheServiceProvider',
@ -105,13 +105,17 @@ return array(
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
'Illuminate\Redis\RedisServiceProvider',
'services\utils\UtilsProvider',
'services\openid\OpenIdProvider',
'services\oauth2\OAuth2ServiceProvider',
'auth\AuthenticationServiceProvider',
'services\ServicesProvider',
'strategies\StrategyProvider',
'oauth2\OAuth2ServiceProvider',
'openid\OpenIdServiceProvider',
'Greggilbert\Recaptcha\RecaptchaServiceProvider',
),
'services\oauth2\CORS\CORSProvider',
),
/*
|--------------------------------------------------------------------------

23
app/config/cors.php Normal file
View File

@ -0,0 +1,23 @@
<?php
/**
* CORS Configuration
*/
return array(
/**
* http://www.w3.org/TR/cors/#access-control-allow-credentials-response-header
*/
'AllowCredentials' => 'true',
/**
* http://www.w3.org/TR/cors/#access-control-max-age-response-header
*/
'UsePreflightCaching' => true,
'MaxAge' => 32000,
/**
* http://www.w3.org/TR/cors/#access-control-allow-headers-response-header
*/
'AllowedHeaders' => 'origin, content-type, accept, authorization',
/**
* http://www.w3.org/TR/cors/#access-control-allow-methods-response-header
*/
'AllowedMethods' => 'GET, POST, OPTIONS, PUT, DELETE',
);

View File

@ -105,12 +105,16 @@ return array(
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
'Illuminate\Redis\RedisServiceProvider',
'services\utils\UtilsProvider',
'services\openid\OpenIdProvider',
'services\oauth2\OAuth2ServiceProvider',
'auth\AuthenticationServiceProvider',
'services\ServicesProvider',
'strategies\StrategyProvider',
'oauth2\OAuth2ServiceProvider',
'openid\OpenIdServiceProvider',
'Greggilbert\Recaptcha\RecaptchaServiceProvider',
'services\oauth2\CORS\CORSProvider',
),
/*

51
app/config/server.php Normal file
View File

@ -0,0 +1,51 @@
<?php
/**
* Server Configuration
*
*/
return array(
//general default values
'Assets_Url' => 'http://www.openstack.org/',
'MaxFailed_Login_Attempts' => 10,
'MaxFailed_LoginAttempts_2ShowCaptcha' => 3,
//openid default values
'OpenId_Private_Association_Lifetime' => 240,
'OpenId_Session_Association_Lifetime' => 21600,
'OpenId_Nonce_Lifetime' => 360,
/**
* Security Policies Configuration
*/
'BlacklistSecurityPolicy_BannedIpLifeTimeSeconds' => 21600,
'BlacklistSecurityPolicy_MinutesWithoutExceptions' => 5,
'BlacklistSecurityPolicy_ReplayAttackExceptionInitialDelay' => 10,
'BlacklistSecurityPolicy_MaxInvalidNonceAttempts' => 10,
'BlacklistSecurityPolicy_InvalidNonceInitialDelay' => 10,
'BlacklistSecurityPolicy_MaxInvalidOpenIdMessageExceptionAttempts' => 10,
'BlacklistSecurityPolicy_InvalidOpenIdMessageExceptionInitialDelay' => 10,
'BlacklistSecurityPolicy_MaxOpenIdInvalidRealmExceptionAttempts' => 10,
'BlacklistSecurityPolicy_OpenIdInvalidRealmExceptionInitialDelay' => 10,
'BlacklistSecurityPolicy_MaxInvalidOpenIdMessageModeAttempts' => 10,
'BlacklistSecurityPolicy_InvalidOpenIdMessageModeInitialDelay' => 10,
'BlacklistSecurityPolicy_MaxInvalidOpenIdAuthenticationRequestModeAttempts' => 10,
'BlacklistSecurityPolicy_InvalidOpenIdAuthenticationRequestModeInitialDelay' => 10,
'BlacklistSecurityPolicy_MaxAuthenticationExceptionAttempts' => 10,
'BlacklistSecurityPolicy_AuthenticationExceptionInitialDelay' => 20,
'BlacklistSecurityPolicy_MaxInvalidAssociationAttempts' => 10,
'BlacklistSecurityPolicy_InvalidAssociationInitialDelay' => 20,
'BlacklistSecurityPolicy_OAuth2_MaxAuthCodeReplayAttackAttempts' => 3,
'BlacklistSecurityPolicy_OAuth2_AuthCodeReplayAttackInitialDelay' => 10,
'BlacklistSecurityPolicy_OAuth2_MaxInvalidAuthorizationCodeAttempts' => 3,
'BlacklistSecurityPolicy_OAuth2_InvalidAuthorizationCodeInitialDelay' => 10,
'BlacklistSecurityPolicy_OAuth2_MaxInvalidBearerTokenDisclosureAttempt' => 3,
'BlacklistSecurityPolicy_OAuth2_BearerTokenDisclosureAttemptInitialDelay' => 10,
//oauth2 default config values
'OAuth2_AuthorizationCode_Lifetime' => 240,
'OAuth2_AccessToken_Lifetime' => 3600,
'OAuth2_RefreshToken_Lifetime' => 0,
//oauth2 security policy configuration
'OAuth2SecurityPolicy_MinutesWithoutExceptions' => 2,
'OAuth2SecurityPolicy_MaxBearerTokenDisclosureAttempts' => 5,
'OAuth2SecurityPolicy_MaxInvalidClientExceptionAttempts' => 10,
'OAuth2SecurityPolicy_MaxInvalidRedeemAuthCodeAttempts' => 10,
'OAuth2SecurityPolicy_MaxInvalidInvalidClientCredentialsAttempts' => 5,
);

View File

@ -60,6 +60,7 @@ class AdminController extends BaseController {
}
$allowed_uris = $client->getClientRegisteredUris();
$allowed_origins = $client->getClientAllowedOrigins();
$selected_scopes = $client->getClientScopes();
$aux_scopes = array();
@ -87,6 +88,7 @@ class AdminController extends BaseController {
array(
'client' => $client,
'allowed_uris' => $allowed_uris,
'allowed_origins' => $allowed_origins,
'selected_scopes' => $aux_scopes,
'scopes' => $scopes,
'access_tokens' => $access_tokens,

View File

@ -11,7 +11,7 @@ use openid\services\IServerConfigurationService;
use openid\services\ITrustedSitesService;
use openid\services\IUserService;
use openid\XRDS\XRDSDocumentBuilder;
use services\IPHelper;
use utils\IPHelper;
use services\IUserActionService;
use strategies\DefaultLoginStrategy;
use strategies\OAuth2ConsentStrategy;

View File

@ -3,11 +3,18 @@
use utils\services\IBannedIPService;
use utils\services\ILogService;
/**
* Class ApiBannedIPController
*/
class ApiBannedIPController extends AbstractRESTController implements ICRUDController
{
private $banned_ip_service;
/**
* @param IBannedIPService $banned_ip_service
* @param ILogService $log_service
*/
public function __construct(IBannedIPService $banned_ip_service, ILogService $log_service)
{

View File

@ -69,8 +69,9 @@ class ApiEndpointController extends AbstractRESTController implements ICRUDContr
$rules = array(
'name' => 'required|alpha_dash|max:255',
'description' => 'required|text',
'description' => 'required|freetext',
'active' => 'required|boolean',
'allow_cors' => 'required|boolean',
'route' => 'required|route',
'http_method' => 'required|httpmethod',
'api_id' => 'required|integer',
@ -88,6 +89,7 @@ class ApiEndpointController extends AbstractRESTController implements ICRUDContr
$new_api_endpoint['name'],
$new_api_endpoint['description'],
$new_api_endpoint['active'],
$new_api_endpoint['allow_cors'],
$new_api_endpoint['route'],
$new_api_endpoint['http_method'],
$new_api_endpoint['api_id']
@ -128,8 +130,9 @@ class ApiEndpointController extends AbstractRESTController implements ICRUDContr
$rules = array(
'id' => 'required|integer',
'name' => 'sometimes|required|alpha_dash|max:255',
'description' => 'sometimes|required|text',
'description' => 'sometimes|required|freetext',
'active' => 'sometimes|required|boolean',
'allow_cors' => 'sometimes|required|boolean',
'route' => 'sometimes|required|route',
'http_method' => 'sometimes|required|httpmethod',
);

View File

@ -68,8 +68,8 @@ class ApiScopeController extends AbstractRESTController implements ICRUDControll
$rules = array(
'name' => 'required|scopename|max:512',
'short_description' => 'required|text|max:512',
'description' => 'required|text',
'short_description' => 'required|freetext|max:512',
'description' => 'required|freetext',
'active' => 'required|boolean',
'default' => 'required|boolean',
'system' => 'required|boolean',
@ -135,8 +135,8 @@ class ApiScopeController extends AbstractRESTController implements ICRUDControll
$rules = array(
'id' => 'required|integer',
'name' => 'sometimes|required|scopename|max:512',
'description' => 'sometimes|required|text',
'short_description' => 'sometimes|required|text|max:512',
'description' => 'sometimes|required|freetext',
'short_description' => 'sometimes|required|freetext|max:512',
'active' => 'sometimes|required|boolean',
'system' => 'sometimes|required|boolean',
'default' => 'sometimes|required|boolean',

View File

@ -18,6 +18,7 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
private $scope_service;
private $token_service;
/**
* @param IApiScopeService $scope_service
* @param ITokenService $token_service
@ -65,8 +66,9 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
// Build the validation constraint set.
$rules = array(
'user_id' => 'required|integer',
'application_name' => 'required|alpha_dash|max:255',
'application_description' => 'required|text',
'app_name' => 'required|alpha_dash|max:255',
'app_description' => 'required|freetext',
'website' => 'required|url',
'application_type' => 'required|applicationtype',
);
@ -78,11 +80,11 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
return $this->error400(array('error'=>'validation','messages' => $messages));
}
if ($this->client_service->existClientAppName($values['application_name'])) {
if ($this->client_service->existClientAppName($values['app_name'])) {
return $this->error400(array('error' => 'application Name already exists!.'));
}
$new_client = $this->client_service->addClient($values['application_type'], intval($values['user_id']), trim($values['application_name']), trim($values['application_description']));
$new_client = $this->client_service->addClient($values['application_type'], intval($values['user_id']), trim($values['app_name']), trim($values['app_description']), trim($values['website']));
return $this->created(array('client_id' => $new_client->id));
@ -150,12 +152,13 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
$values = Input::all();
$rules = array(
'id' => 'required|integer',
'app_name' => 'sometimes|required|alpha_dash|max:255',
'app_description' => 'sometimes|required|text',
'active' => 'sometimes|required|boolean',
'locked' => 'sometimes|required|boolean',
'use_refresh_token' => 'sometimes|required|boolean',
'id' => 'required|integer',
'app_name' => 'sometimes|required|alpha_dash|max:255',
'app_description' => 'sometimes|required|freetext',
'website' => 'sometimes|required|url',
'active' => 'sometimes|required|boolean',
'locked' => 'sometimes|required|boolean',
'use_refresh_token' => 'sometimes|required|boolean',
'rotate_refresh_token' => 'sometimes|required|boolean',
);
@ -180,6 +183,10 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
}
}
/**
* @param $id
* @return mixed
*/
public function getRegisteredUris($id)
{
try {
@ -198,6 +205,10 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
}
}
/**
* @param $id
* @return mixed
*/
public function addAllowedRedirectUri($id)
{
try {
@ -210,7 +221,7 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error400(array('error' => $messages));
return $this->error400(array('error'=>'validation','messages' => $messages));
}
$res = $this->client_service->addClientAllowedUri($id, $values['redirect_uri']);
return $res ? $this->ok(): $this->error404(array('error' => 'operation failed'));
@ -226,6 +237,11 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
}
}
/**
* @param $id
* @param $uri_id
* @return mixed
*/
public function deleteClientAllowedUri($id, $uri_id)
{
try {
@ -308,7 +324,7 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error400(array('error' => $messages));
return $this->error400(array('error'=>'validation','messages' => $messages));
}
$res = $this->client_service->setRefreshTokenUsage($id, $values['use_refresh_token']);
@ -337,7 +353,7 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error400(array('error' => $messages));
return $this->error400(array('error'=>'validation','messages' => $messages));
}
$res = $this->client_service->setRotateRefreshTokenPolicy($id, $values['rotate_refresh_token']);
@ -454,4 +470,75 @@ class ClientApiController extends AbstractRESTController implements ICRUDControl
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function geAllowedOrigins($id)
{
try {
$client = $this->client_service->getClientByIdentifier($id);
$allowed_origins = $client->allowed_origins()->get(array('id', 'allowed_origin'));
$data = array();
foreach ($allowed_origins as $origin) {
array_push($data, $origin->toArray());
}
return $this->ok(array('allowed_origins' => $data));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function addAllowedOrigin($id)
{
try {
$values = Input::All();
// Build the validation constraint set.
$rules = array(
'origin' => 'sslorigin|required',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error400(array('error'=>'validation','messages' => $messages));
}
$res = $this->client_service->addClientAllowedOrigin($id, $values['origin']);
return $res ? $this->ok(): $this->error404(array('error' => 'operation failed'));
} catch (AllowedClientUriAlreadyExistsException $ex1) {
$this->log_service->error($ex1);
return $this->error400(array('error' => $ex1->getMessage()));
} catch (AbsentClientException $ex2) {
$this->log_service->error($ex2);
return $this->error404(array('error' => $ex2->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $origin_id
* @return mixed
*/
public function deleteClientAllowedOrigin($id, $origin_id)
{
try {
$res = $this->client_service->deleteClientAllowedOrigin($id, $origin_id);
return $res ? $this->ok() : $this->error404(array('error' => 'operation failed'));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
}

View File

@ -5,7 +5,7 @@ use utils\services\ILogService;
/**
* Class JsonController
*/
class JsonController extends BaseController {
abstract class JsonController extends BaseController {
protected $log_service;

View File

@ -72,7 +72,17 @@ class UserApiController extends AbstractRESTController implements ICRUDControlle
public function get($id)
{
// TODO: Implement get() method.
try {
$user = $this->user_service->get($id);
if(is_null($user)){
return $this->error404(array('error' => 'user not found'));
}
$data = $user->toArray();
return $this->ok($data);
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
public function create()

View File

@ -7,7 +7,7 @@ use utils\services\ILogService;
* Class OAuth2ProtectedController
* OAuth2 Protected Base API
*/
class OAuth2ProtectedController extends JsonController {
abstract class OAuth2ProtectedController extends JsonController {
protected $resource_server_context;

View File

@ -0,0 +1,33 @@
<?php
use oauth2\IResourceServerContext;
use utils\services\ILogService;
use oauth2\resource_server\IUserService;
/**
* Class OAuth2UserApiController
* OAUTH2 Protected User REST API
*/
class OAuth2UserApiController extends OAuth2ProtectedController {
public function __construct (IUserService $user_service, IResourceServerContext $resource_server_context, ILogService $log_service){
parent::__construct($resource_server_context,$log_service);
$this->user_service = $user_service;
}
/**
* Gets User Basic Info
* @return mixed
*/
public function me(){
try{
$data = $this->user_service->getCurrentUserInfo();
return $this->ok($data);
}
catch(Exception $ex){
$this->log_service->error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,38 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
class CreateOauth2ClientsAuthorizedRealm extends Migration {
public function up()
{
Schema::create('oauth2_client_authorized_realm', function($table)
{
$table->bigIncrements('id')->unsigned();
$table->string('realm',255);
$table->bigInteger("client_id")->unsigned();
$table->index('client_id');
$table->foreign('client_id')->references('id')->on('oauth2_client')
->onDelete('cascade')
->onUpdate('no action');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('oauth2_client_authorized_realm', function($table)
{
$table->dropForeign('client_id');
});
Schema::dropIfExists('oauth2_client_authorized_realm');
}
}

View File

@ -0,0 +1,45 @@
<?php
use Illuminate\Database\Migrations\Migration;
class CreateOauth2ClientAllowedOrigin extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oauth2_client_allowed_origin', function($table)
{
$table->bigIncrements('id')->unsigned();
$table->text('allowed_origin');
$table->bigInteger("client_id")->unsigned();
$table->index('client_id');
$table->foreign('client_id')
->references('id')
->on('oauth2_client')
->onDelete('cascade')
->onUpdate('no action');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('oauth2_client_allowed_origin', function($table)
{
$table->dropForeign('client_id');
});
Schema::dropIfExists('oauth2_client_allowed_origin');
}
}

View File

@ -13,6 +13,7 @@ class UpdateOauth2Client extends Migration {
{
Schema::table('oauth2_client', function($table)
{
$table->text("website");
$table->enum('application_type', array('WEB_APPLICATION', 'JS_CLIENT','SERVICE'));
});
}
@ -24,12 +25,10 @@ class UpdateOauth2Client extends Migration {
*/
public function down()
{
Schema::table('oauth2_client', function($table)
{
$table->dropColumn('website');
$table->dropColumn('application_type');
});
}
}

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
class UpdateOauth2ApiEndpoint extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('oauth2_api_endpoint', function($table)
{
$table->boolean('allow_cors')->default(true);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('oauth2_api_endpoint', function($table)
{
$table->dropColumn('allow_cors');
});
}
}

View File

@ -1,457 +1,38 @@
<?php
class ApiEndpointSeeder extends Seeder {
class ApiEndpointSeeder extends Seeder
{
public function run()
{
DB::table('oauth2_api_endpoint_api_scope')->delete();
DB::table('oauth2_api_endpoint')->delete();
$this->seedResourceServerEndpoints();
$this->seedApiEndpoints();
$this->seedApiEndpointEndpoints();
$this->seedScopeEndpoints();
$this->seedUsersEndpoints();
}
private function seedResourceServerEndpoints(){
$current_realm = Config::get('app.url');
$resource_server = Api::where('name','=','resource-server')->first();
ApiEndpoint::create(
array(
'name' => 'create-resource-server',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server',
'http_method' => 'POST'
)
);
ApiEndpoint::create(
array(
'name' => 'get-resource-server',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server/{id}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'resource-server-regenerate-secret',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server/regenerate-client-secret/{id}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'resource-server-get-page',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server/{page_nbr}/{page_size}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'resource-server-delete',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server/{id}',
'http_method' => 'DELETE'
)
);
ApiEndpoint::create(
array(
'name' => 'resource-server-update',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server',
'http_method' => 'PUT'
)
);
ApiEndpoint::create(
array(
'name' => 'resource-server-update-status',
'active' => true,
'api_id' => $resource_server->id,
'route' => 'api/v1/resource-server/status/{id}/{active}',
'http_method' => 'GET'
)
);
//attach scopes to endpoints
//resource server api scopes
$resource_server_read_scope = ApiScope::where('name','=',sprintf('%s/resource-server/read',$current_realm))->first();
$resource_server_write_scope = ApiScope::where('name','=',sprintf('%s/resource-server/write',$current_realm))->first();
$resource_server_read_page_scope = ApiScope::where('name','=',sprintf('%s/resource-server/read.page',$current_realm))->first();
$resource_server_regenerate_secret_scope = ApiScope::where('name','=',sprintf('%s/resource-server/regenerate.secret',$current_realm))->first();
$resource_server_delete_scope = ApiScope::where('name','=',sprintf('%s/resource-server/delete',$current_realm))->first();
$resource_server_update_scope = ApiScope::where('name','=',sprintf('%s/resource-server/update',$current_realm))->first();
$resource_server_update_status_scope = ApiScope::where('name','=',sprintf('%s/resource-server/update.status',$current_realm))->first();
// create needs write access
$resource_server_api_create = ApiEndpoint::where('name','=','create-resource-server')->first();
$resource_server_api_create->scopes()->attach($resource_server_write_scope->id);
//get needs read access
$resource_server_api_get = ApiEndpoint::where('name','=','get-resource-server')->first();
$resource_server_api_get->scopes()->attach($resource_server_read_scope->id);
// get page needs read access or read page access
$resource_server_api_get_page = ApiEndpoint::where('name','=','resource-server-get-page')->first();
$resource_server_api_get_page->scopes()->attach($resource_server_read_scope->id);
$resource_server_api_get_page->scopes()->attach($resource_server_read_page_scope->id);
//regenerate secret needs write access or specific access
$resource_server_api_regenerate = ApiEndpoint::where('name','=','resource-server-regenerate-secret')->first();
$resource_server_api_regenerate->scopes()->attach($resource_server_write_scope->id);
$resource_server_api_regenerate->scopes()->attach($resource_server_regenerate_secret_scope->id);
//deletes needs delete access
$resource_server_api_delete = ApiEndpoint::where('name','=','resource-server-delete')->first();
$resource_server_api_delete->scopes()->attach($resource_server_delete_scope->id);
//update needs update access
$resource_server_api_update = ApiEndpoint::where('name','=','resource-server-update')->first();
$resource_server_api_update->scopes()->attach($resource_server_update_scope->id);
//update status needs update access or specific access
$resource_server_api_update_status = ApiEndpoint::where('name','=','resource-server-update-status')->first();
$resource_server_api_update_status->scopes()->attach($resource_server_update_scope->id);
$resource_server_api_update_status->scopes()->attach($resource_server_update_status_scope->id);
}
private function seedApiEndpoints(){
$current_realm = Config::get('app.url');
$api_api = Api::where('name','=','api')->first();
ApiEndpoint::create(
array(
'name' => 'get-api',
'active' => true,
'api_id' => $api_api->id,
'route' => 'api/v1/api/{id}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'delete-api',
'active' => true,
'api_id' => $api_api->id,
'route' => 'api/v1/api/{id}',
'http_method' => 'DELETE'
)
);
ApiEndpoint::create(
array(
'name' => 'create-api',
'active' => true,
'api_id' => $api_api->id,
'route' => 'api/v1/api',
'http_method' => 'POST'
)
);
ApiEndpoint::create(
array(
'name' => 'update-api',
'active' => true,
'api_id' => $api_api->id,
'route' => 'api/v1/api',
'http_method' => 'PUT'
)
);
ApiEndpoint::create(
array(
'name' => 'update-api-status',
'active' => true,
'api_id' => $api_api->id,
'route' => 'api/v1/api/status/{id}/{active}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'api-get-page',
'active' => true,
'api_id' => $api_api->id,
'route' => 'api/v1/api/{page_nbr}/{page_size}',
'http_method' => 'GET'
)
);
//endpoint api scopes
$api_read_scope = ApiScope::where('name','=',sprintf('%s/api/read',$current_realm))->first();
$api_write_scope = ApiScope::where('name','=',sprintf('%s/api/write',$current_realm))->first();
$api_read_page_scope = ApiScope::where('name','=',sprintf('%s/api/read.page',$current_realm))->first();
$api_delete_scope = ApiScope::where('name','=',sprintf('%s/api/delete',$current_realm))->first();
$api_update_scope = ApiScope::where('name','=',sprintf('%s/api/update',$current_realm))->first();
$api_update_status_scope = ApiScope::where('name','=',sprintf('%s/api/update.status',$current_realm))->first();
$endpoint_api_get = ApiEndpoint::where('name','=','get-api')->first();
$endpoint_api_get->scopes()->attach($api_read_scope->id);
$endpoint_api_get_page = ApiEndpoint::where('name','=','api-get-page')->first();
$endpoint_api_get_page->scopes()->attach($api_read_scope->id);
$endpoint_api_get_page->scopes()->attach($api_read_page_scope->id);
$endpoint_api_delete = ApiEndpoint::where('name','=','delete-api')->first();
$endpoint_api_delete->scopes()->attach($api_delete_scope->id);
$endpoint_api_create = ApiEndpoint::where('name','=','create-api')->first();
$endpoint_api_create->scopes()->attach($api_write_scope->id);
$endpoint_api_update = ApiEndpoint::where('name','=','update-api')->first();
$endpoint_api_update->scopes()->attach($api_update_scope->id);
$endpoint_api_update_status = ApiEndpoint::where('name','=','update-api-status')->first();
$endpoint_api_update_status->scopes()->attach($api_update_scope->id);
$endpoint_api_update_status->scopes()->attach($api_update_status_scope->id);
}
private function seedApiEndpointEndpoints(){
$current_realm = Config::get('app.url');
$api_api_endpoint = Api::where('name','=','api-endpoint')->first();
ApiEndpoint::create(
array(
'name' => 'get-api-endpoint',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint/{id}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'delete-api-endpoint',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint/{id}',
'http_method' => 'DELETE'
)
);
ApiEndpoint::create(
array(
'name' => 'create-api-endpoint',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint',
'http_method' => 'POST'
)
);
ApiEndpoint::create(
array(
'name' => 'update-api-endpoint',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint',
'http_method' => 'PUT'
)
);
ApiEndpoint::create(
array(
'name' => 'update-api-endpoint-status',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint/status/{id}/{active}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'api-endpoint-get-page',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint/{page_nbr}/{page_size}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'add-api-endpoint-scope',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint/scope/add/{id}/{scope_id}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'remove-api-endpoint-scope',
'active' => true,
'api_id' => $api_api_endpoint->id,
'route' => 'api/v1/api-endpoint/scope/remove/{id}/{scope_id}',
'http_method' => 'GET'
)
);
//endpoint api endpoint scopes
$api_endpoint_read_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/read',$current_realm))->first();
$api_endpoint_write_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/write',$current_realm))->first();
$api_endpoint_read_page_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/read.page',$current_realm))->first();
$api_endpoint_delete_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/delete',$current_realm))->first();
$api_endpoint_update_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/update',$current_realm))->first();
$api_endpoint_update_status_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/update.status',$current_realm))->first();
$api_endpoint_add_scope_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/add.scope',$current_realm))->first();
$api_endpoint_remove_scope_scope = ApiScope::where('name','=',sprintf('%s/api-endpoint/remove.scope',$current_realm))->first();
$endpoint_api_endpoint_get = ApiEndpoint::where('name','=','get-api-endpoint')->first();
$endpoint_api_endpoint_get->scopes()->attach($api_endpoint_read_scope->id);
$endpoint_api_endpoint_get_page = ApiEndpoint::where('name','=','api-endpoint-get-page')->first();
$endpoint_api_endpoint_get_page->scopes()->attach($api_endpoint_read_scope->id);
$endpoint_api_endpoint_get_page->scopes()->attach($api_endpoint_read_page_scope->id);
$endpoint_api_endpoint_delete = ApiEndpoint::where('name','=','delete-api-endpoint')->first();
$endpoint_api_endpoint_delete->scopes()->attach($api_endpoint_delete_scope->id);
$endpoint_api_endpoint_create = ApiEndpoint::where('name','=','create-api-endpoint')->first();
$endpoint_api_endpoint_create->scopes()->attach($api_endpoint_write_scope->id);
$endpoint_api_endpoint_update = ApiEndpoint::where('name','=','update-api-endpoint')->first();
$endpoint_api_endpoint_update->scopes()->attach($api_endpoint_update_scope->id);
$endpoint_api_add_api_endpoint_scope = ApiEndpoint::where('name','=','add-api-endpoint-scope')->first();
$endpoint_api_add_api_endpoint_scope->scopes()->attach($api_endpoint_write_scope->id);
$endpoint_api_add_api_endpoint_scope->scopes()->attach($api_endpoint_add_scope_scope->id);
$endpoint_api_remove_api_endpoint_scope = ApiEndpoint::where('name','=','remove-api-endpoint-scope')->first();
$endpoint_api_remove_api_endpoint_scope->scopes()->attach($api_endpoint_write_scope->id);
$endpoint_api_remove_api_endpoint_scope->scopes()->attach($api_endpoint_remove_scope_scope->id);
$endpoint_api_endpoint_update_status = ApiEndpoint::where('name','=','update-api-endpoint-status')->first();
$endpoint_api_endpoint_update_status->scopes()->attach($api_endpoint_update_scope->id);
$endpoint_api_endpoint_update_status->scopes()->attach($api_endpoint_update_status_scope->id);
}
private function seedScopeEndpoints(){
$api_scope = Api::where('name','=','api-scope')->first();
$current_realm = Config::get('app.url');
private function seedUsersEndpoints()
{
$users = Api::where('name', '=', 'users')->first();
// endpoints scopes
ApiEndpoint::create(
array(
'name' => 'get-scope',
'active' => true,
'api_id' => $api_scope->id,
'route' => 'api/v1/api-scope/{id}',
'http_method' => 'GET'
'name' => 'get-user-info',
'active' => true,
'api_id' => $users->id,
'route' => '/api/v1/users/me',
'http_method' => 'GET'
)
);
$profile_scope = ApiScope::where('name', '=', 'profile')->first();
$email_scope = ApiScope::where('name', '=', 'email')->first();
$address_scope = ApiScope::where('name', '=', 'address')->first();
ApiEndpoint::create(
array(
'name' => 'delete-scope',
'active' => true,
'api_id' => $api_scope->id,
'route' => 'api/v1/api-scope/{id}',
'http_method' => 'DELETE'
)
);
ApiEndpoint::create(
array(
'name' => 'create-scope',
'active' => true,
'api_id' => $api_scope->id,
'route' => 'api/v1/api-scope',
'http_method' => 'POST'
)
);
ApiEndpoint::create(
array(
'name' => 'update-scope',
'active' => true,
'api_id' => $api_scope->id,
'route' => 'api/v1/api-scope',
'http_method' => 'PUT'
)
);
ApiEndpoint::create(
array(
'name' => 'update-scope-status',
'active' => true,
'api_id' => $api_scope->id,
'route' => 'api/v1/api-scope/status/{id}/{active}',
'http_method' => 'GET'
)
);
ApiEndpoint::create(
array(
'name' => 'scope-get-page',
'active' => true,
'api_id' => $api_scope->id,
'route' => 'api/v1/api-scope/{page_nbr}/{page_size}',
'http_method' => 'GET'
)
);
$api_scope_read_scope = ApiScope::where('name','=',sprintf('%s/api-scope/read',$current_realm))->first();
$api_scope_write_scope = ApiScope::where('name','=',sprintf('%s/api-scope/write',$current_realm))->first();
$api_scope_read_page_scope = ApiScope::where('name','=',sprintf('%s/api-scope/read.page',$current_realm))->first();
$api_scope_delete_scope = ApiScope::where('name','=',sprintf('%s/api-scope/delete',$current_realm))->first();
$api_scope_update_scope = ApiScope::where('name','=',sprintf('%s/api-scope/update',$current_realm))->first();
$api_scope_update_status_scope = ApiScope::where('name','=',sprintf('%s/api-scope/update.status',$current_realm))->first();
$endpoint_api_scope_get = ApiEndpoint::where('name','=','get-scope')->first();
$endpoint_api_scope_get->scopes()->attach($api_scope_read_scope->id);
$endpoint_api_scope_get_page = ApiEndpoint::where('name','=','scope-get-page')->first();
$endpoint_api_scope_get_page->scopes()->attach($api_scope_read_scope->id);
$endpoint_api_scope_get_page->scopes()->attach($api_scope_read_page_scope->id);
$endpoint_api_scope_delete = ApiEndpoint::where('name','=','delete-scope')->first();
$endpoint_api_scope_delete->scopes()->attach($api_scope_delete_scope->id);
$endpoint_api_scope_create = ApiEndpoint::where('name','=','create-scope')->first();
$endpoint_api_scope_create->scopes()->attach($api_scope_write_scope->id);
$endpoint_api_scope_update = ApiEndpoint::where('name','=','update-scope')->first();
$endpoint_api_scope_update->scopes()->attach($api_scope_update_scope->id);
$endpoint_api_scope_update_status = ApiEndpoint::where('name','=','update-scope-status')->first();
$endpoint_api_scope_update_status->scopes()->attach($api_scope_update_scope->id);
$endpoint_api_scope_update_status->scopes()->attach($api_scope_update_status_scope->id);
$get_user_info_endpoint = ApiEndpoint::where('name', '=', 'get-user-info')->first();
$get_user_info_endpoint->scopes()->attach($profile_scope->id);
$get_user_info_endpoint->scopes()->attach($email_scope->id);
$get_user_info_endpoint->scopes()->attach($address_scope->id);
}
}

View File

@ -8,305 +8,40 @@ class ApiScopeSeeder extends Seeder {
DB::table('oauth2_api_endpoint_api_scope')->delete();
DB::table('oauth2_client_api_scope')->delete();
DB::table('oauth2_api_scope')->delete();
$this->seedResourceServerScopes();
$this->seedApiScopes();
$this->seedApiEndpointScopes();
$this->seedApiScopeScopes();
$this->seedUsersScopes();
}
private function seedResourceServerScopes(){
private function seedUsersScopes(){
$resource_server = Api::where('name','=','resource-server')->first();
$current_realm = Config::get('app.url');
$users = Api::where('name','=','users')->first();
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/read',$current_realm),
'short_description' => 'Resource Server Read Access',
'description' => 'Resource Server Read Access',
'api_id' => $resource_server->id,
'system' => true,
'name' => 'profile',
'short_description' => 'Allows access to your profile info.',
'description' => 'This scope value requests access to the End-Users default profile Claims, which are: name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at.',
'api_id' => $users->id,
'system' => false,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/read.page',$current_realm),
'short_description' => 'Resource Server Page Read Access',
'description' => 'Resource Server Page Read Access',
'api_id' => $resource_server->id,
'system' => true,
'name' => 'email',
'short_description' => 'Allows access to your email info.',
'description' => 'This scope value requests access to the email and email_verified Claims.',
'api_id' => $users->id,
'system' => false,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/write',$current_realm),
'short_description' => 'Resource Server Write Access',
'description' => 'Resource Server Write Access',
'api_id' => $resource_server->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/delete',$current_realm),
'short_description' => 'Resource Server Delete Access',
'description' => 'Resource Server Delete Access',
'api_id' => $resource_server->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/update',$current_realm),
'short_description' => 'Resource Server Update Access',
'description' => 'Resource Server Update Access',
'api_id' => $resource_server->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/update.status',$current_realm),
'short_description' => 'Resource Server Update Status',
'description' => 'Resource Server Update Status',
'api_id' => $resource_server->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/resource-server/regenerate.secret',$current_realm),
'short_description' => 'Resource Server Regenerate Client Secret',
'description' => 'Resource Server Regenerate Client Secret',
'api_id' => $resource_server->id,
'system' => true,
)
);
}
private function seedApiScopes(){
$api = Api::where('name','=','api')->first();
$current_realm = Config::get('app.url');
ApiScope::create(
array(
'name' => sprintf('%s/api/read',$current_realm),
'short_description' => 'Get Api',
'description' => 'Get Api',
'api_id' => $api->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api/delete',$current_realm),
'short_description' => 'Deletes Api',
'description' => 'Deletes Api',
'api_id' => $api->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api/write',$current_realm),
'short_description' => 'Create Api',
'description' => 'Create Api',
'api_id' => $api->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api/update',$current_realm),
'short_description' => 'Update Api',
'description' => 'Update Api',
'api_id' => $api->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api/update.status',$current_realm),
'short_description' => 'Update Api Status',
'description' => 'Update Api Status',
'api_id' => $api->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api/read.page',$current_realm),
'short_description' => 'Get Api By Page',
'description' => 'Get Api By Page',
'api_id' => $api->id,
'system' => true,
)
);
}
private function seedApiEndpointScopes(){
$api_endpoint = Api::where('name','=','api-endpoint')->first();
$current_realm = Config::get('app.url');
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/read',$current_realm),
'short_description' => 'Get Api Endpoint',
'description' => 'Get Api Endpoint',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/delete',$current_realm),
'short_description' => 'Deletes Api Endpoint',
'description' => 'Deletes Api Endpoint',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/write',$current_realm),
'short_description' => 'Create Api Endpoint',
'description' => 'Create Api Endpoint',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/update',$current_realm),
'short_description' => 'Update Api Endpoint',
'description' => 'Update Api Endpoint',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/update.status',$current_realm),
'short_description' => 'Update Api Endpoint Status',
'description' => 'Update Api Endpoint Status',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/read.page',$current_realm),
'short_description' => 'Get Api Endpoints By Page',
'description' => 'Get Api Endpoints By Page',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/add.scope',$current_realm),
'short_description' => 'Add required scope to endpoint',
'description' => 'Add required scope to endpoint',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-endpoint/remove.scope',$current_realm),
'short_description' => 'Remove required scope to endpoint',
'description' => 'Remove required scope to endpoint',
'api_id' => $api_endpoint->id,
'system' => true,
)
);
}
private function seedApiScopeScopes(){
$current_realm = Config::get('app.url');
$api_scope = Api::where('name','=','api-scope')->first();
ApiScope::create(
array(
'name' => sprintf('%s/api-scope/read',$current_realm),
'short_description' => 'Get Api Scope',
'description' => 'Get Api Scope',
'api_id' => $api_scope->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-scope/delete',$current_realm),
'short_description' => 'Deletes Api Scope',
'description' => 'Deletes Api Scope',
'api_id' => $api_scope->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-scope/write',$current_realm),
'short_description' => 'Create Api Scope',
'description' => 'Create Api Scope',
'api_id' => $api_scope->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-scope/update',$current_realm),
'short_description' => 'Update Api Scope',
'description' => 'Update Api Scope',
'api_id' => $api_scope->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-scope/update.status',$current_realm),
'short_description' => 'Update Api Scope Status',
'description' => 'Update Api Scope Status',
'api_id' => $api_scope->id,
'system' => true,
)
);
ApiScope::create(
array(
'name' => sprintf('%s/api-scope/read.page',$current_realm),
'short_description' => 'Get Api Scopes By Page',
'description' => 'Get Api Scopes By Page',
'api_id' => $api_scope->id,
'system' => true,
'name' => 'address',
'short_description' => 'Allows access to your Address info.',
'description' => 'This scope value requests access to the address Claim.',
'api_id' => $users->id,
'system' => false,
)
);

View File

@ -12,49 +12,13 @@ class ApiSeeder extends Seeder {
Api::create(
array(
'name' => 'resource-server',
'logo' => null,
'active' => true,
'Description' => 'Resource Server CRUD operations',
'resource_server_id' => $resource_server->id,
'logo' => asset('img/apis/server.png')
)
);
Api::create(
array(
'name' => 'api',
'name' => 'users',
'logo' => null,
'active' => true,
'Description' => 'Api CRUD operations',
'Description' => 'User Info',
'resource_server_id' => $resource_server->id,
'logo' => asset('img/apis/server.png')
)
);
Api::create(
array(
'name' => 'api-endpoint',
'logo' => null,
'active' => true,
'Description' => 'Api Endpoints CRUD operations',
'resource_server_id' => $resource_server->id,
'logo' => asset('img/apis/server.png')
)
);
Api::create(
array(
'name' => 'api-scope',
'logo' => null,
'active' => true,
'Description' => 'Api Scopes CRUD operations',
'resource_server_id' => $resource_server->id,
'logo' => asset('img/apis/server.png')
)
);
}
}
}

View File

@ -6,14 +6,15 @@ class ResourceServerSeeder extends Seeder {
{
DB::table('oauth2_resource_server')->delete();
$current_realm = Config::get('app.url');
$res = @parse_url($current_realm);
ResourceServer::create(
array(
'friendly_name' => 'openstack id server',
'host' => $current_realm,
'host' => $res['host'],
'ip' => '127.0.0.1'
)
);
}
}
}

View File

@ -55,11 +55,13 @@ class TestSeeder extends Seeder {
$this->seedApiScopes();
$this->seedApiEndpointScopes();
$this->seedApiScopeScopes();
$this->seedUsersScopes();
//endpoints
$this->seedResourceServerEndpoints();
$this->seedApiEndpoints();
$this->seedApiEndpointEndpoints();
$this->seedScopeEndpoints();
$this->seedUsersEndpoints();
$this->seedTestUsersAndClients();
}
@ -328,7 +330,6 @@ class TestSeeder extends Seeder {
)
);
Client::create(
array(
'app_name' => 'oauth2.service',
@ -344,8 +345,6 @@ class TestSeeder extends Seeder {
)
);
Client::create(
array(
'app_name' => 'oauth2_test_app_public',
@ -464,6 +463,17 @@ class TestSeeder extends Seeder {
'logo' => asset('img/apis/server.png')
)
);
Api::create(
array(
'name' => 'users',
'logo' => null,
'active' => true,
'Description' => 'User Info',
'resource_server_id' => $resource_server->id,
'logo' => asset('img/apis/server.png')
)
);
}
private function seedResourceServerScopes(){
@ -763,6 +773,42 @@ class TestSeeder extends Seeder {
}
private function seedUsersScopes(){
$current_realm = Config::get('app.url');
$users = Api::where('name','=','users')->first();
ApiScope::create(
array(
'name' => 'profile',
'short_description' => 'This scope value requests access to the End-Users default profile Claims',
'description' => 'This scope value requests access to the End-Users default profile Claims, which are: name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at',
'api_id' => $users->id,
'system' => false,
)
);
ApiScope::create(
array(
'name' => 'email',
'short_description' => 'This scope value requests access to the email and email_verified Claims',
'description' => 'This scope value requests access to the email and email_verified Claims',
'api_id' => $users->id,
'system' => false,
)
);
ApiScope::create(
array(
'name' => 'address',
'short_description' => 'This scope value requests access to the address Claim.',
'description' => 'This scope value requests access to the address Claim.',
'api_id' => $users->id,
'system' => false,
)
);
}
private function seedResourceServerEndpoints(){
$current_realm = Config::get('app.url');
@ -1203,5 +1249,28 @@ class TestSeeder extends Seeder {
$endpoint_api_scope_update_status->scopes()->attach($api_scope_update_scope->id);
$endpoint_api_scope_update_status->scopes()->attach($api_scope_update_status_scope->id);
}
}
private function seedUsersEndpoints(){
$users = Api::where('name','=','users')->first();
$current_realm = Config::get('app.url');
// endpoints scopes
ApiEndpoint::create(
array(
'name' => 'get-user-info',
'active' => true,
'api_id' => $users->id,
'route' => 'api/v1/users/me',
'http_method' => 'GET'
)
);
$profile_scope = ApiScope::where('name','=','profile')->first();
$email_scope = ApiScope::where('name','=','email')->first();
$address_scope = ApiScope::where('name','=','address')->first();
$get_user_info_endpoint = ApiEndpoint::where('name','=','get-user-info')->first();
$get_user_info_endpoint->scopes()->attach($profile_scope->id);
$get_user_info_endpoint->scopes()->attach($email_scope->id);
$get_user_info_endpoint->scopes()->attach($address_scope->id);
}
}

View File

@ -2,7 +2,7 @@
use openid\exceptions\InvalidOpenIdMessageException;
use openid\requests\OpenIdAuthenticationRequest;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use oauth2\services\OAuth2ServiceCatalog;
use oauth2\exceptions\InvalidAuthorizationRequestException;
@ -17,12 +17,11 @@ use oauth2\exceptions\InvalidAuthorizationRequestException;
|
*/
//SAP (single access point)
App::before(function ($request) {
App::before(function($request){
try {
//checkpoint security pattern entry point
$checkpoint_service = Registry::getInstance()->get(UtilsServiceCatalog::CheckPointService);
$checkpoint_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::CheckPointService);
if (!$checkpoint_service->check()) {
return View::make('404');
}
@ -30,11 +29,19 @@ App::before(function ($request) {
Log::error($ex);
return View::make('404');
}
$cors = ServiceLocator::getInstance()->getService('CORSMiddleware');
if($response = $cors->verifyRequest($request))
return $response;
});
App::after(function($request, $response){
App::after(function ($request, $response) {
//
$response->headers->set('X-content-type-options','nosniff');
$response->headers->set('X-xss-protection','1; mode=block');
$cors = ServiceLocator::getInstance()->getService('CORSMiddleware');
$cors->modifyResponse($request, $response);
});
/*
@ -79,7 +86,6 @@ Route::filter('guest', function () {
if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
@ -141,7 +147,7 @@ Route::filter("oauth2.needs.auth.request", function () {
Route::filter("ssl", function () {
if (!Request::secure()) {
$openid_memento_service = Registry::getInstance()->get(OpenIdServiceCatalog::MementoService);
$openid_memento_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::MementoService);
$openid_memento_service->saveCurrentRequest();
$oauth2_memento_service = App::make(OAuth2ServiceCatalog::MementoService);

View File

@ -18,11 +18,31 @@ use oauth2\IResourceServerContext;
*/
class OAuth2BearerAccessTokenRequestValidator {
protected function headers()
{
if (function_exists('getallheaders')) {
// @codeCoverageIgnoreStart
$headers = getallheaders();
} else {
// @codeCoverageIgnoreEnd
$headers = array();
foreach ($this->server() as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
$headers[$name] = $value;
}
}
}
return $headers;
}
private $api_endpoint_service;
private $token_service;
private $log_service;
private $checkpoint_service;
private $resource_server_context;
private $headers;
public function __construct(IResourceServerContext $resource_server_context,IApiEndpointService $api_endpoint_service, ITokenService $token_service, ILogService $log_service, ICheckPointService $checkpoint_service){
$this->api_endpoint_service = $api_endpoint_service;
@ -30,6 +50,7 @@ class OAuth2BearerAccessTokenRequestValidator {
$this->log_service = $log_service;
$this->checkpoint_service = $checkpoint_service;
$this->resource_server_context = $resource_server_context;
$this->headers = $this->headers();
}
/**
@ -39,6 +60,10 @@ class OAuth2BearerAccessTokenRequestValidator {
public function filter($route, $request)
{
$url = $route->getPath();
if(strpos($url, '/') != 0){
$url = '/'.$url;
}
$method = $request->getMethod();
$realm = $request->getHost();
@ -51,7 +76,7 @@ class OAuth2BearerAccessTokenRequestValidator {
}
//check first http basic auth header
$auth_header = Request::header('Authorization');
$auth_header = isset($this->headers['Authorization'])?$this->headers['Authorization']:null;
if(!is_null($auth_header) && !empty($auth_header))
$access_token_value = BearerAccessTokenAuthorizationHeaderParser::getInstance()->parse($auth_header);
else{
@ -94,8 +119,8 @@ class OAuth2BearerAccessTokenRequestValidator {
'scope' => $access_token->getScope()
);
if(!is_null($access_token>getUserId()))
$context['user_id'] = $access_token>getUserId();
if(!is_null($access_token->getUserId()))
$context['user_id'] = $access_token->getUserId();
$this->resource_server_context->setAuthorizationContext($context);

View File

@ -103,4 +103,6 @@ return array(
'scopename' => "The :attribute may be a valid scope name.",
'applicationtype' => "The :attribute may be a valid application type.",
'sslurl' => "The :attribute may be a valid URL under ssl schema.",
'sslorigin' => "The :attribute may be a valid HTTP origin under ssl schema.",
'freetext' => "The :attribute may only contain text."
);

View File

@ -3,7 +3,6 @@
namespace auth;
use Illuminate\Support\ServiceProvider;
use utils\services\Registry;
use utils\services\UtilsServiceCatalog;
class AuthenticationServiceProvider extends ServiceProvider
@ -11,15 +10,16 @@ class AuthenticationServiceProvider extends ServiceProvider
public function boot()
{
$this->app->singleton(UtilsServiceCatalog::AuthenticationService, 'auth\\AuthService');
Registry::getInstance()->set(UtilsServiceCatalog::AuthenticationService, $this->app->make(UtilsServiceCatalog::AuthenticationService));
$this->app->singleton('auth\\IAuthenticationExtensionService', 'auth\\AuthenticationExtensionService');
Registry::getInstance()->set('auth\\IAuthenticationExtensionService', $this->app->make('auth\\IAuthenticationExtensionService'));
}
public function register()
{
$this->app->singleton(UtilsServiceCatalog::AuthenticationService, 'auth\\AuthService');
$this->app->singleton('auth\\IAuthenticationExtensionService', 'auth\\AuthenticationExtensionService');
}
public function provides()
{
return array('Authentication.services');
}
}

View File

@ -1,7 +1,6 @@
<?php
namespace auth;
use auth\exceptions\AuthenticationException;
use auth\exceptions\AuthenticationInvalidPasswordAttemptException;
use auth\exceptions\AuthenticationLockedUserLoginAttempt;
@ -10,10 +9,9 @@ use Illuminate\Auth\UserInterface;
use Illuminate\Auth\UserProviderInterface;
use Log;
use Member;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use utils\services\UtilsServiceCatalog;
use DB;
use openid\services\IUserService;
use utils\services\ICheckPointService;
/**
* Class CustomAuthProvider
@ -24,9 +22,15 @@ class CustomAuthProvider implements UserProviderInterface
{
private $auth_extension_service;
private $user_service;
private $checkpoint_service;
public function __construct(IAuthenticationExtensionService $auth_extension_service){
public function __construct(IAuthenticationExtensionService $auth_extension_service,
IUserService $user_service,
ICheckPointService $checkpoint_service){
$this->auth_extension_service = $auth_extension_service;
$this->user_service = $user_service;
$this->checkpoint_service = $checkpoint_service;
}
/**
@ -98,13 +102,11 @@ class CustomAuthProvider implements UserProviderInterface
$user = User::where('external_id', '=', $identifier)->first();
}
$user_service = Registry::getInstance()->get(OpenIdServiceCatalog::UserService);
$user_name = $member->FirstName . "." . $member->Surname;
//do association between user and member
$user_service->associateUser($user->id, strtolower($user_name));
$server_configuration = Registry::getInstance()->get(UtilsServiceCatalog::ServerConfigurationService);
$this->user_service->associateUser($user->id, strtolower($user_name));
//update user fields
$user->last_login_date = gmdate("Y-m-d H:i:s", time());
@ -124,8 +126,7 @@ class CustomAuthProvider implements UserProviderInterface
}
});
} catch (Exception $ex) {
$checkpoint_service = Registry::getInstance()->get(UtilsServiceCatalog::CheckPointService);
$checkpoint_service->trackException($ex);
$this->checkpoint_service->trackException($ex);
Log::error($ex);
$user = null;
}

View File

@ -7,7 +7,7 @@ use Member;
use MemberPhoto;
use openid\model\IOpenIdUser;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use utils\services\ServiceLocator;
use oauth2\models\IOAuth2User;
use Eloquent;
use utils\model\BaseModelEloquent;
@ -126,7 +126,7 @@ class User extends BaseModelEloquent implements UserInterface, IOpenIdUser, IOAu
public function getNickName()
{
return $this->getFullName;
return $this->getFullName();
}
public function getGender()
@ -134,7 +134,7 @@ class User extends BaseModelEloquent implements UserInterface, IOpenIdUser, IOAu
if (is_null($this->member)) {
$this->member = Member::where('Email', '=', $this->external_id)->first();
}
return "";
return $this->member->Gender;
}
public function getCountry()
@ -214,7 +214,7 @@ class User extends BaseModelEloquent implements UserInterface, IOpenIdUser, IOAu
if (!is_null($photoId) && is_numeric($photoId) && $photoId > 0) {
$photo = MemberPhoto::where('ID', '=', $photoId)->first();
if(!is_null($photo)){
$server_configuration_service = Registry::getInstance()->get(OpenIdServiceCatalog::ServerConfigurationService);
$server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService);
$url = $server_configuration_service->getConfigValue("Assets.Url").$photo->Filename;
}
}
@ -262,4 +262,36 @@ class User extends BaseModelEloquent implements UserInterface, IOpenIdUser, IOAu
$group = $this->member->groups()->where('code','=',IOpenIdUser::OpenstackIdServerAdminGroup)->first();
return !is_null($group);
}
public function getStreetAddress()
{
if (is_null($this->member)) {
$this->member = Member::where('Email', '=', $this->external_id)->first();
}
return sprintf("%s, %s ",$this->member->Address,$this->member->Suburb);
}
public function getRegion()
{
if (is_null($this->member)) {
$this->member = Member::where('Email', '=', $this->external_id)->first();
}
return $this->member->State;
}
public function getLocality()
{
if (is_null($this->member)) {
$this->member = Member::where('Email', '=', $this->external_id)->first();
}
return $this->member->City;
}
public function getPostalCode()
{
if (is_null($this->member)) {
$this->member = Member::where('Email', '=', $this->external_id)->first();
}
return $this->member->Postcode;
}
}

View File

@ -2,13 +2,42 @@
namespace oauth2;
/**
* Interface IResourceServerContext
* Current Request OAUTH2 security context
* @package oauth2
*/
interface IResourceServerContext {
/**
* returns given scopes for current requewt
* @return array
*/
public function getCurrentScope();
/**
* gets current access token valaue
* @return string
*/
public function getCurrentAccessToken();
/**
* gets current access token lifetime
* @return mixed
*/
public function getCurrentAccessTokenLifetime();
/**
* gets current client id
* @return string
*/
public function getCurrentClientId();
public function setAuthorizationContext($auth_context);
/**
* gets current user id (if was set)
* @return int
*/
public function getCurrentUserId();
public function setAuthorizationContext($auth_context);
}

View File

@ -31,6 +31,7 @@ use oauth2\exceptions\UnsupportedResponseTypeException;
use oauth2\exceptions\UriNotAllowedException;
use oauth2\exceptions\MissingClientAuthorizationInfo;
use oauth2\exceptions\InvalidRedeemAuthCodeException;
use oauth2\exceptions\InvalidClientCredentials;
//grant types
use oauth2\grant_types\AuthorizationCodeGrantType;
@ -427,6 +428,11 @@ class OAuth2Protocol implements IOAuth2Protocol
$this->checkpoint_service->trackException($ex17);
return new OAuth2DirectErrorResponse(OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient);
}
catch(InvalidClientCredentials $ex18){
$this->log_service->error($ex18);
$this->checkpoint_service->trackException($ex18);
return new OAuth2DirectErrorResponse(OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient);
}
catch (Exception $ex) {
$this->log_service->error($ex);
$this->checkpoint_service->trackException($ex);
@ -478,6 +484,11 @@ class OAuth2Protocol implements IOAuth2Protocol
$this->checkpoint_service->trackException($ex2);
return new OAuth2DirectErrorResponse(OAuth2Protocol::OAuth2Protocol_Error_InvalidGrant);
}
catch(InvalidClientCredentials $ex3){
$this->log_service->error($ex3);
$this->checkpoint_service->trackException($ex3);
return new OAuth2DirectErrorResponse(OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient);
}
catch (Exception $ex) {
$this->log_service->error($ex);
$this->checkpoint_service->trackException($ex);

View File

@ -3,17 +3,20 @@
namespace oauth2;
use Illuminate\Support\ServiceProvider;
use utils\services\Registry;
class OAuth2ServiceProvider extends ServiceProvider
class OAuth2ServiceProvider extends ServiceProvider
{
public function boot()
{
Registry::getInstance()->set('oauth2\IOAuth2Protocol', $this->app->make('oauth2\IOAuth2Protocol'));
}
public function register()
{
$this->app->bind('oauth2\IOAuth2Protocol', 'oauth2\OAuth2Protocol');
$this->app->singleton('oauth2\IOAuth2Protocol', 'oauth2\OAuth2Protocol');
}
public function provides()
{
return array('oauth2');
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace oauth2\exceptions;
class InvalidClientCredentials extends OAuth2ClientBaseException
{
public function __construct($client_id, $message = "")
{
$message = "Invalid Client Credentials : " . $message;
parent::__construct($client_id, $message);
}
}

View File

@ -3,9 +3,9 @@
namespace oauth2\grant_types;
use oauth2\exceptions\InvalidClientException;
use oauth2\exceptions\InvalidClientType;
use oauth2\exceptions\MissingClientIdParam;
use oauth2\exceptions\LockedClientException;
use oauth2\exceptions\InvalidClientCredentials;
use oauth2\models\IClient;
use oauth2\requests\OAuth2Request;
@ -38,10 +38,9 @@ abstract class AbstractGrantType implements IGrantType
* @param OAuth2Request $request
* @return mixed|void
* @throws \oauth2\exceptions\MissingClientIdParam
* @throws \oauth2\exceptions\InvalidClientType
* @throws \oauth2\exceptions\InvalidClientCredentials
* @throws \oauth2\exceptions\InvalidClientException
* @throws \oauth2\exceptions\LockedClientException
* @throws \oauth2\exceptions\MissingClientAuthorizationInfo
*/
public function completeFlow(OAuth2Request $request)
{
@ -64,7 +63,7 @@ abstract class AbstractGrantType implements IGrantType
//verify client credentials (only for confidential clients )
if ($this->current_client->getClientType() == IClient::ClientType_Confidential && $this->current_client->getClientSecret() !== $this->current_client_secret)
throw new InvalidClientType($this->current_client_id,sprintf('client id %s',$this->current_client_id));
throw new InvalidClientCredentials($this->current_client_id, sprintf('client id %s',$this->current_client_id));
}
}

View File

@ -13,7 +13,7 @@ use oauth2\requests\OAuth2Request;
use oauth2\responses\OAuth2AccessTokenValidationResponse;
use oauth2\services\IClientService;
use oauth2\services\ITokenService;
use services\IPHelper;
use utils\IPHelper;
use utils\services\ILogService;
use oauth2\models\IClient;
@ -126,7 +126,7 @@ class ValidateBearerTokenGrantType extends AbstractGrantType
throw new BearerTokenDisclosureAttemptException($this->current_client_id,sprintf('access token current audience does not match with current request ip %s', $current_ip));
}
return new OAuth2AccessTokenValidationResponse($token_value, $access_token->getScope(), $access_token->getAudience(),$access_token->getClientId(),$access_token->getRemainingLifetime(),$access_token->getUserId());
return new OAuth2AccessTokenValidationResponse( $token_value, $access_token->getScope(), $access_token->getAudience(), $access_token->getClientId(), $access_token->getRemainingLifetime(), $access_token->getUserId());
}
catch(InvalidAccessTokenException $ex1){
$this->log_service->error($ex1);

View File

@ -2,7 +2,7 @@
namespace oauth2\models;
use services\IPHelper;
use utils\IPHelper;
use Zend\Math\Rand;
use oauth2\OAuth2Protocol;
/**

View File

@ -16,6 +16,11 @@ interface IApiEndpoint {
public function isActive();
public function setStatus($active);
/**
* @return booll
*/
public function supportCORS();
/**
* @return IApi
*/

View File

@ -15,25 +15,126 @@ interface IClient {
const ApplicationType_JS_Client = 'JS_CLIENT';
const ApplicationType_Service = 'SERVICE';
/**
* @return int
*/
public function getId();
/**
* @return string
*/
public function getClientId();
/**
* @return null|string
*/
public function getClientSecret();
/**
* @return string
*/
public function getClientType();
/**
* @return string
*/
public function getApplicationType();
public function getClientAuthorizedRealms();
/**
* @return mixed
*/
public function getClientScopes();
public function getClientRegisteredUris();
/**
* @param $scope
* @return bool
*/
public function isScopeAllowed($scope);
public function isRealmAllowed($realm);
/**
* @return mixed
*/
public function getClientRegisteredUris();
/**
* @param $uri
* @return bool
*/
public function isUriAllowed($uri);
/**
* returns all registered allowed js origins for this client
* @return mixed
*/
public function getClientAllowedOrigins();
/**
* @param $origin
* @return bool
*/
public function isOriginAllowed($origin);
/**
* gets application name
* @return string
*/
public function getApplicationName();
/** gets application log url
* @return string
*/
public function getApplicationLogo();
/**
* gets application description
* @return string
*/
public function getApplicationDescription();
/**
* gets application developer email
* @return string
*/
public function getDeveloperEmail();
/**
* gets user id that owns this application
* @return int
*/
public function getUserId();
/**
*
* @return bool
*/
public function isLocked();
/**
* @return bool
*/
public function isActive();
/**
* clients could be associated to resource server in order
* to do server to server communication
* @return bool
*/
public function isResourceServerClient();
/**
* gets associated resource server
* @return null|IResourceServer
*/
public function getResourceServer();
/**
* @return string
*/
public function getFriendlyApplicationType();
/**
* gets application website url
* @return string
*/
public function getWebsite();
}

View File

@ -3,7 +3,7 @@
namespace oauth2\models;
use Zend\Math\Rand;
use services\IPHelper;
use utils\IPHelper;
use oauth2\OAuth2Protocol;
/**
* Class RefreshToken

View File

@ -0,0 +1,26 @@
<?php
namespace oauth2\resource_server;
/**
* Interface IUserService
* @package oauth2\resource_server
*/
interface IUserService {
/**
* This scope value requests access to the End-User's default profile Claims, which are:
* name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture,
* website, gender, birthdate, zoneinfo, locale, and updated_at.
*/
const UserProfileScope_Profile = 'profile';
/**
* This scope value requests access to the email and email_verified Claims.
*/
const UserProfileScope_Email = 'email';
/**
* This scope value requests access to the address Claim.
*/
const UserProfileScope_Address = 'address';
public function getCurrentUserInfo();
}

View File

@ -0,0 +1,27 @@
<?php
namespace oauth2\resource_server;
use oauth2\IResourceServerContext;
use utils\services\ILogService;
/**
* Class OAuth2ProtectedService
* Base Class for OAUTH2 protected endpoints
* @package oauth2\resource_server
*/
abstract class OAuth2ProtectedService {
protected $resource_server_context;
protected $log_service;
/**
* @param IResourceServerContext $resource_server_context
* @param ILogService $log_service
*/
public function __construct(IResourceServerContext $resource_server_context, ILogService $log_service)
{
$this->log_service = $log_service;
$this->resource_server_context = $resource_server_context;
}
}

View File

@ -17,6 +17,7 @@ class OAuth2AccessTokenValidationResponse extends OAuth2DirectResponse {
$this[OAuth2Protocol::OAuth2Protocol_Scope] = $scope;
$this[OAuth2Protocol::OAuth2Protocol_Audience] = $audience;
$this[OAuth2Protocol::OAuth2Protocol_AccessToken_ExpiresIn] = $expires_in;
if(!is_null($user_id)){
$this[OAuth2Protocol::OAuth2Protocol_UserId] = $user_id;
}

View File

@ -0,0 +1,17 @@
<?php
namespace oauth2\services;
/**
* Interface IAllowedOriginService
* CRUD Service for clients allowed origins
* @package oauth2\services
*/
interface IAllowedOriginService {
public function get($id);
public function getByUri($uri);
public function create($uri,$client_id);
public function delete($id);
public function deleteByUri($uri);
}

View File

@ -7,12 +7,18 @@ use oauth2\models\IApiEndpoint;
interface IApiEndpointService {
/**
* @param $url
* @param $http_method
* @param string$url
* @param string $http_method
* @return IApiEndpoint
*/
public function getApiEndpointByUrlAndMethod($url,$http_method);
/**
* @param string $url
* @return IApiEndpoint
*/
public function getApiEndpointByUrl($url);
/**
* @param $id
* @return IApiEndpoint
@ -34,12 +40,13 @@ interface IApiEndpointService {
* @param string $name
* @param string $description
* @param boolean $active
* @param boolean $allow_cors
* @param string $route
* @param string $http_method
* @param int $api_id
* @return IApiEndpoint
*/
public function add($name, $description, $active, $route, $http_method, $api_id);
public function add($name, $description, $active, $allow_cors, $route, $http_method, $api_id);
/**

View File

@ -31,14 +31,15 @@ interface IClientService {
/**
* Creates a new client
* @param $application_type
* @param $user_id
* @param $app_name
* @param $app_description
* @param string $app_logo
* @param string $application_type
* @param int $user_id
* @param string $app_name
* @param string $app_description
* @param null|string $app_url
* @param string $app_logo
* @return IClient
*/
public function addClient($application_type, $user_id, $app_name, $app_description, $app_logo='');
public function addClient($application_type, $user_id, $app_name, $app_description,$app_url=null, $app_logo='');
public function addClientScope($id,$scope_id);
public function deleteClientScope($id,$scope_id);
@ -50,6 +51,13 @@ interface IClientService {
*/
public function addClientAllowedUri($id,$uri);
/**
* @param $id
* @param $origin
* @return mixed
*/
public function addClientAllowedOrigin($id,$origin);
/**
* Deletes a former client allowed redirection Uri
* @param $id client identifier
@ -57,6 +65,13 @@ interface IClientService {
*/
public function deleteClientAllowedUri($id,$uri_id);
/**
* @param $id
* @param $origin_id
* @return mixed
*/
public function deleteClientAllowedOrigin($id,$origin_id);
public function deleteClientByIdentifier($id);
/**

View File

@ -12,4 +12,5 @@ class OAuth2ServiceCatalog {
const ApiService = 'oauth2\\services\\IApiService';
const ApiEndpointService = 'oauth2\\services\\IApiEndpointService';
const UserConsentService = 'oauth2\\services\\IUserConsentService';
const AllowedOriginService = 'oauth2\\services\\IAllowedOriginService';
}

View File

@ -6,7 +6,7 @@ use oauth2\responses\OAuth2DirectResponse;
use oauth2\responses\OAuth2IndirectFragmentResponse;
use oauth2\responses\OAuth2IndirectResponse;
use oauth2\responses\OAuth2Response;
use utils\services\Registry;
use utils\services\ServiceLocator;
class OAuth2ResponseStrategyFactoryMethod {
@ -16,19 +16,19 @@ class OAuth2ResponseStrategyFactoryMethod {
switch ($type) {
case OAuth2IndirectResponse::OAuth2IndirectResponse:
{
return Registry::getInstance()->get(OAuth2IndirectResponse::OAuth2IndirectResponse);
return ServiceLocator::getInstance()->getService(OAuth2IndirectResponse::OAuth2IndirectResponse);
}
break;
case OAuth2IndirectFragmentResponse::OAuth2IndirectFragmentResponse:
{
return Registry::getInstance()->get(OAuth2IndirectFragmentResponse::OAuth2IndirectFragmentResponse);
return ServiceLocator::getInstance()->getService(OAuth2IndirectFragmentResponse::OAuth2IndirectFragmentResponse);
}
break;
case OAuth2DirectResponse::OAuth2DirectResponse:
{
return Registry::getInstance()->get(OAuth2DirectResponse::OAuth2DirectResponse);
return ServiceLocator::getInstance()->getService(OAuth2DirectResponse::OAuth2DirectResponse);
}
break;
default:

View File

@ -5,10 +5,9 @@ namespace openid;
use openid\handlers\OpenIdAuthenticationRequestHandler;
use openid\handlers\OpenIdCheckAuthenticationRequestHandler;
use openid\handlers\OpenIdSessionAssociationRequestHandler;
use openid\services\OpenIdServiceCatalog;
use openid\XRDS\XRDSDocumentBuilder;
use openid\XRDS\XRDSService;
use utils\services\Registry;
//services
use utils\services\ILogService;
use openid\services\IMementoOpenIdRequestService;
@ -22,6 +21,7 @@ use utils\services\IAuthService;
use utils\services\ICheckPointService;
/**
* Class OpenIdProtocol
* OpenId Protocol Implementation
@ -126,7 +126,8 @@ class OpenIdProtocol implements IOpenIdProtocol
);
private $request_handlers;
private $server_extension_service;
private $server_config_service;
public function __construct(
IAuthService $auth_service,
@ -141,9 +142,11 @@ class OpenIdProtocol implements IOpenIdProtocol
ICheckPointService $checkpoint_service)
{
//create chain of responsibility
$check_auth = new OpenIdCheckAuthenticationRequestHandler($association_service, $nonce_service, $log_service,$checkpoint_service, null);
$session_assoc = new OpenIdSessionAssociationRequestHandler($log_service,$checkpoint_service, $check_auth);
$this->request_handlers = new OpenIdAuthenticationRequestHandler($auth_service, $memento_request_service, $auth_strategy, $server_extension_service, $association_service, $trusted_sites_service, $server_config_service, $nonce_service, $log_service,$checkpoint_service, $session_assoc);
$check_auth = new OpenIdCheckAuthenticationRequestHandler($association_service, $nonce_service, $log_service,$checkpoint_service, null);
$session_assoc = new OpenIdSessionAssociationRequestHandler($log_service,$checkpoint_service, $check_auth);
$this->request_handlers = new OpenIdAuthenticationRequestHandler($auth_service, $memento_request_service, $auth_strategy, $server_extension_service, $association_service, $trusted_sites_service, $server_config_service, $nonce_service, $log_service,$checkpoint_service, $session_assoc);
$this->server_extension_service = $server_extension_service;
$this->server_config_service = $server_config_service;
}
public static function isAssocTypeSupported($assoc_type)
@ -173,17 +176,13 @@ class OpenIdProtocol implements IOpenIdProtocol
public function getXRDSDiscovery($mode, $canonical_id = null)
{
$server_extension_service = Registry::getInstance()->get(OpenIdServiceCatalog::ServerExtensionsService);
$server_config_service = Registry::getInstance()->get(OpenIdServiceCatalog::ServerConfigurationService);
$active_extensions = $server_extension_service->getAllActiveExtensions();
$active_extensions = $this->server_extension_service->getAllActiveExtensions();
$extensions = array();
foreach ($active_extensions as $ext) {
array_push($extensions, $ext->getNamespace());
}
$services = array();
array_push($services, new XRDSService(0, $mode == IOpenIdProtocol::OpenIdXRDSModeUser ? self::ClaimedIdentifierType : self::OPIdentifierType, $server_config_service->getOPEndpointURL(), $extensions, $canonical_id));
array_push($services, new XRDSService(0, $mode == IOpenIdProtocol::OpenIdXRDSModeUser ? self::ClaimedIdentifierType : self::OPIdentifierType, $this->server_config_service->getOPEndpointURL(), $extensions, $canonical_id));
$builder = new XRDSDocumentBuilder($services, $canonical_id);
$xrds = $builder->render();
return $xrds;

View File

@ -15,9 +15,20 @@ use utils\services\UtilsServiceCatalog;
class OpenIdServiceProvider extends ServiceProvider
{
public function boot()
{
$this->app->bind('openid\IOpenIdProtocol', 'openid\OpenIdProtocol');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('openid\IOpenIdProtocol', 'openid\OpenIdProtocol');
$auth_extension_service = $this->app->make('auth\\IAuthenticationExtensionService');
@ -28,13 +39,8 @@ class OpenIdServiceProvider extends ServiceProvider
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
public function provides()
{
// TODO: Implement register() method.
return array('openid');
}
}

View File

@ -1,11 +1,4 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: smarcet
* Date: 10/16/13
* Time: 2:29 PM
* To change this template use File | Settings | File Templates.
*/
namespace openid\extensions;
@ -13,8 +6,7 @@ use openid\requests\contexts\RequestContext;
use openid\requests\OpenIdRequest;
use openid\responses\contexts\ResponseContext;
use openid\responses\OpenIdResponse;
use utils\services\Registry;
use utils\services\UtilsServiceCatalog;
use utils\services\ILogService;
/**
* Class OpenIdExtension
@ -37,13 +29,13 @@ abstract class OpenIdExtension
* @param $view
* @param $description
*/
public function __construct($name, $namespace, $view, $description)
public function __construct($name, $namespace, $view, $description, ILogService $log_service)
{
$this->namespace = $namespace;
$this->name = $name;
$this->view = $view;
$this->description = $description;
$this->log_service = Registry::getInstance()->get(UtilsServiceCatalog::LogService);
$this->log_service = $log_service;
}
public function getNamespace()

View File

@ -10,9 +10,9 @@ use openid\requests\contexts\RequestContext;
use openid\requests\OpenIdRequest;
use openid\responses\contexts\ResponseContext;
use openid\responses\OpenIdResponse;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use utils\services\ILogService;
/**
* Class OpenIdAXExtension
* Implements
@ -36,9 +36,9 @@ class OpenIdAXExtension extends OpenIdExtension
const FetchRequest = "fetch_request";
public static $available_properties;
public function __construct($name, $namespace, $view, $description)
public function __construct($name, $namespace, $view, $description, ILogService $log_service)
{
parent::__construct($name, $namespace, $view, $description);
parent::__construct($name, $namespace, $view, $description, $log_service);
self::$available_properties[OpenIdAXExtension::Country] = "http://axschema.org/contact/country/home";
self::$available_properties[OpenIdAXExtension::Email] = "http://axschema.org/contact/email";
self::$available_properties[OpenIdAXExtension::FirstMame] = "http://axschema.org/namePerson/first";
@ -72,9 +72,11 @@ class OpenIdAXExtension extends OpenIdExtension
$response->addParam(self::paramNamespace(), self::NamespaceUrl);
$response->addParam(self::param(self::Mode), self::FetchResponse);
$context->addSignParam(self::param(self::Mode));
$attributes = $ax_request->getRequiredAttributes();
$auth_service = Registry::getInstance()->get(UtilsServiceCatalog::AuthenticationService);
$user = $auth_service->getCurrentUser();
$attributes = $ax_request->getRequiredAttributes();
$auth_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::AuthenticationService);
$user = $auth_service->getCurrentUser();
foreach ($attributes as $attr) {
$response->addParam(self::param(self::Type) . "." . $attr, self::$available_properties[$attr]);
$context->addSignParam(self::param(self::Type) . "." . $attr);

View File

@ -6,8 +6,6 @@ use openid\exceptions\InvalidOpenIdMessageException;
use openid\helpers\OpenIdErrorMessages;
use openid\OpenIdMessage;
use openid\requests\OpenIdRequest;
/**
* Class OpenIdAXRequest
* Implements http://openid.net/specs/openid-attribute-exchange-1_0.html

View File

@ -12,8 +12,9 @@ use openid\responses\contexts\ResponseContext;
use openid\responses\OpenIdResponse;
use Exception;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use utils\services\ILogService;
use oauth2\requests\OAuth2AuthorizationRequest;
use oauth2\OAuth2Protocol;
@ -53,14 +54,14 @@ class OpenIdOAuth2Extension extends OpenIdExtension
* @param $view
* @param $description
*/
public function __construct($name, $namespace, $view, $description)
public function __construct($name, $namespace, $view, $description, ILogService $log_service)
{
parent::__construct($name, $namespace, $view, $description);
parent::__construct($name, $namespace, $view, $description,$log_service);
$this->oauth2_protocol = Registry::getInstance()->get('oauth2\IOAuth2Protocol');
$this->checkpoint_service = Registry::getInstance()->get(UtilsServiceCatalog::CheckPointService);
$this->client_service = Registry::getInstance()->get(OAuth2ServiceCatalog::ClientService);
$this->scope_service = Registry::getInstance()->get(OAuth2ServiceCatalog::ScopeService);
$this->oauth2_protocol = ServiceLocator::getInstance()->getService('oauth2\IOAuth2Protocol');
$this->checkpoint_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::CheckPointService);
$this->client_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ClientService);
$this->scope_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ScopeService);
}
/**
@ -136,6 +137,7 @@ class OpenIdOAuth2Extension extends OpenIdExtension
'app_name' => $client->getApplicationName(),
'app_logo' => $client->getApplicationLogo(),
'redirect_to' => $return_to,
'website' => $client->getWebsite(),
'dev_info_email' => $client->getDeveloperEmail()
));

View File

@ -1,12 +1,4 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: smarcet
* Date: 10/16/13
* Time: 2:42 PM
* To change this template use File | Settings | File Templates.
*/
namespace openid\extensions\implementations;
use openid\extensions\OpenIdExtension;
@ -15,7 +7,7 @@ use openid\requests\contexts\RequestContext;
use openid\requests\OpenIdRequest;
use openid\responses\contexts\ResponseContext;
use openid\responses\OpenIdResponse;
use utils\services\ILogService;
/**
* Class OpenIdPAPEExtension
* Implements http://openid.net/specs/openid-provider-authentication-policy-extension-1_0.html
@ -26,6 +18,11 @@ class OpenIdPAPEExtension extends OpenIdExtension
const Prefix = "pape";
public function __construct($name, $namespace, $view, $description, ILogService $log_service)
{
parent::__construct($name, $namespace, $view, $description,$log_service);
}
public static function param($param, $separator = '.')
{
return OpenIdProtocol::OpenIdPrefix . $separator . self::Prefix . $separator . $param;

View File

@ -9,9 +9,10 @@ use openid\requests\contexts\RequestContext;
use openid\requests\OpenIdRequest;
use openid\responses\contexts\ResponseContext;
use openid\responses\OpenIdResponse;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use Exception;
use utils\services\ILogService;
/**
* Class OpenIdSREGExtension
@ -41,9 +42,9 @@ class OpenIdSREGExtension extends OpenIdExtension
public static $available_properties;
public function __construct($name, $namespace, $view, $description)
public function __construct($name, $namespace, $view, $description, ILogService $log_service)
{
parent::__construct($name, $namespace, $view, $description);
parent::__construct($name, $namespace, $view, $description,$log_service);
self::$available_properties[OpenIdSREGExtension::Nickname] = OpenIdSREGExtension::Nickname;
self::$available_properties[OpenIdSREGExtension::Email] = OpenIdSREGExtension::Email;
self::$available_properties[OpenIdSREGExtension::FullName] = OpenIdSREGExtension::FullName;
@ -90,7 +91,7 @@ class OpenIdSREGExtension extends OpenIdExtension
$opt_attributes = $simple_reg_request->getOptionalAttributes();
$attributes = array_merge($attributes, $opt_attributes);
$auth_service = Registry::getInstance()->get(UtilsServiceCatalog::AuthenticationService);
$auth_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::AuthenticationService);
$user = $auth_service->getCurrentUser();
foreach ($attributes as $attr => $value) {

View File

@ -1,17 +1,11 @@
<?php
/**
* Created by PhpStorm.
* User: smarcet
* Date: 11/4/13
* Time: 11:06 AM
*/
namespace openid\extensions\implementations;
use Exception;
use openid\OpenIdMessage;
use openid\requests\OpenIdRequest;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
/**
@ -25,14 +19,12 @@ class OpenIdSREGRequest extends OpenIdRequest
private $attributes;
private $optional_attributes;
private $policy_url;
private $log;
public function __construct(OpenIdMessage $message)
{
parent::__construct($message);
$this->attributes = array();
$this->optional_attributes = array();
$this->log = Registry::getInstance()->get(UtilsServiceCatalog::LogService);
}
public function isValid()
@ -83,7 +75,7 @@ class OpenIdSREGRequest extends OpenIdRequest
return true;
}
} catch (Exception $ex) {
$this->log->error($ex);
$this->log_service->error($ex);
}
return false;
}

View File

@ -9,7 +9,7 @@ use openid\model\IAssociation;
use openid\requests\OpenIdDHAssociationSessionRequest;
use openid\responses\OpenIdDiffieHellmanAssociationSessionResponse;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use Zend\Crypt\PublicKey\DiffieHellman;
@ -27,9 +27,9 @@ class SessionAssociationDHStrategy implements ISessionAssociationStrategy
public function __construct(OpenIdDHAssociationSessionRequest $request)
{
$this->current_request = $request;
$this->association_service = Registry::getInstance()->get(OpenIdServiceCatalog::AssociationService);
$this->server_configuration_service = Registry::getInstance()->get(OpenIdServiceCatalog:: ServerConfigurationService);
$this->log = Registry::getInstance()->get(UtilsServiceCatalog:: LogService);
$this->association_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::AssociationService);
$this->server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog:: ServerConfigurationService);
$this->log = ServiceLocator::getInstance()->getService(UtilsServiceCatalog:: LogService);
}
/**

View File

@ -11,7 +11,7 @@ use openid\requests\OpenIdAssociationSessionRequest;
use openid\responses\OpenIdAssociationSessionResponse;
use openid\responses\OpenIdUnencryptedAssociationSessionResponse;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use Zend\Crypt\Exception\InvalidArgumentException;
use Zend\Crypt\Exception\RuntimeException;
@ -27,9 +27,9 @@ class SessionAssociationUnencryptedStrategy implements ISessionAssociationStrate
public function __construct(OpenIdAssociationSessionRequest $request)
{
$this->current_request = $request;
$this->association_service = Registry::getInstance()->get(OpenIdServiceCatalog::AssociationService);
$this->server_configuration_service = Registry::getInstance()->get(OpenIdServiceCatalog:: ServerConfigurationService);
$this->log_service = Registry::getInstance()->get(UtilsServiceCatalog:: LogService);
$this->association_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::AssociationService);
$this->server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog:: ServerConfigurationService);
$this->log_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog:: LogService);
}
/**

View File

@ -25,6 +25,10 @@ interface IOpenIdUser {
public function getNickName();
public function getGender();
public function getCountry();
public function getStreetAddress();
public function getRegion();
public function getLocality();
public function getPostalCode();
public function getLanguage();
public function getTimeZone();
public function getDateOfBirth();

View File

@ -4,7 +4,8 @@ namespace openid\model;
use openid\exceptions\InvalidNonce;
use openid\helpers\OpenIdErrorMessages;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
class OpenIdNonce
{
@ -72,8 +73,8 @@ class OpenIdNonce
*/
public function isValid()
{
$server_configuration_service = Registry::getInstance()->get("openid\\services\\IServerConfigurationService");
$allowed_skew = $server_configuration_service->getConfigValue("Nonce.Lifetime");
$server_configuration_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::ServerConfigurationService);
$allowed_skew = $server_configuration_service->getConfigValue("Nonce.Lifetime");
$now = time();
// Time after which we should not use the nonce
$past = $now - $allowed_skew;

View File

@ -7,7 +7,7 @@ use openid\OpenIdMessage;
use openid\OpenIdProtocol;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use utils\services\ServiceLocator;
use Exception;
@ -113,7 +113,7 @@ class OpenIdAuthenticationRequest extends OpenIdRequest
* other information in its payload, using extensions.
*/
$server_configuration_service = Registry::getInstance()->get(OpenIdServiceCatalog::ServerConfigurationService);
$server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService);
if (is_null($claimed_id) && is_null($identity))
return false;
//http://specs.openid.net/auth/2.0/identifier_select

View File

@ -5,7 +5,8 @@ namespace openid\requests;
use openid\helpers\OpenIdUriHelper;
use openid\OpenIdMessage;
use openid\OpenIdProtocol;
use utils\services\Registry;
use openid\services\OpenIdServiceCatalog;
use utils\services\ServiceLocator;
class OpenIdCheckAuthenticationRequest extends OpenIdAuthenticationRequest
{
@ -34,7 +35,8 @@ class OpenIdCheckAuthenticationRequest extends OpenIdAuthenticationRequest
$claimed_returnTo = $this->getReturnTo();
$signed = $this->getSigned();
$server_configuration_service = Registry::getInstance()->get("openid\\services\\IServerConfigurationService");
$server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService);
if (
!is_null($mode) && !empty($mode) && $mode == OpenIdProtocol::CheckAuthenticationMode
&& !is_null($claimed_returnTo) && !empty($claimed_returnTo) && OpenIdUriHelper::checkReturnTo($claimed_returnTo)

View File

@ -3,7 +3,7 @@
namespace openid\requests;
use openid\OpenIdMessage;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
abstract class OpenIdRequest
@ -15,7 +15,7 @@ abstract class OpenIdRequest
public function __construct(OpenIdMessage $message)
{
$this->message = $message;
$this->log_service = Registry::getInstance()->get(UtilsServiceCatalog::LogService);
$this->log_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::LogService);
}
public function getMessage()

View File

@ -9,6 +9,7 @@ namespace openid\services;
interface IUserService
{
public function get($id);
/**
* @param $id
* @param $proposed_username

View File

@ -6,7 +6,7 @@ use openid\responses\OpenIdDirectResponse;
use openid\responses\OpenIdIndirectResponse;
use openid\responses\OpenIdResponse;
use utils\IHttpResponseStrategy;
use utils\services\Registry;
use utils\services\ServiceLocator;
class OpenIdResponseStrategyFactoryMethod
{
@ -21,12 +21,12 @@ class OpenIdResponseStrategyFactoryMethod
switch ($type) {
case OpenIdIndirectResponse::OpenIdIndirectResponse:
{
return Registry::getInstance()->get(OpenIdIndirectResponse::OpenIdIndirectResponse);
return ServiceLocator::getInstance()->getService(OpenIdIndirectResponse::OpenIdIndirectResponse);
}
break;
case OpenIdDirectResponse::OpenIdDirectResponse:
{
return Registry::getInstance()->get(OpenIdDirectResponse::OpenIdDirectResponse);
return ServiceLocator::getInstance()->getService(OpenIdDirectResponse::OpenIdDirectResponse);
}
break;
default:

View File

@ -0,0 +1,22 @@
<?php
namespace utils;
use Request;
/**
* Class IPHelper
* @package utils
*/
class IPHelper
{
/**
* returns user current ip address
* @return string
*/
public static function getUserIp()
{
$remote_address = Request::server('REMOTE_ADDR');
return $remote_address;
}
}

View File

@ -86,4 +86,6 @@ interface ICacheService {
* @return mixed
*/
public function setKeyExpiration($key, $ttl);
public function boot();
}

View File

@ -1,42 +0,0 @@
<?php
namespace utils\services;
class Registry
{
private static $instance = null;
private function __construct(){
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new Registry();
}
return self::$instance;
}
public function set($key, $value)
{
if (!isset($this->registry[$key])) {
$this->registry[$key] = $value;
}
}
public function get($key)
{
if (!isset($this->registry[$key])) {
throw new \Exception("There is no entry for key " . $key);
}
return $this->registry[$key];
}
private function __clone()
{
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace utils\services;
use App;
class ServiceLocator {
private static $instance = null;
private function __construct(){
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new ServiceLocator();
}
return self::$instance;
}
public function getService($service_id)
{
$service = App::make($service_id);
return $service;
}
private function __clone()
{
}
}

View File

@ -7,7 +7,7 @@ class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint{
protected $table = 'oauth2_api_endpoint';
protected $fillable = array('active' , 'description','active','name','route', 'http_method', 'api_id');
protected $fillable = array('active' , 'description','active','allow_cors', 'name','route', 'http_method', 'api_id');
public function api()
{
@ -76,4 +76,12 @@ class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint{
{
$this->name= $name;
}
/**
* @return \oauth2\models\booll
*/
public function supportCORS()
{
return $this->allow_cors;
}
}

View File

@ -37,6 +37,12 @@ class Client extends BaseModelEloquent implements IClient {
return $this->hasMany('ClientAuthorizedUri','client_id');
}
public function allowed_origins()
{
return $this->hasMany('ClientAllowedOrigin','client_id');
}
public function getClientId()
{
return $this->client_id;
@ -52,11 +58,6 @@ class Client extends BaseModelEloquent implements IClient {
return $this->client_type;
}
public function getClientAuthorizedRealms()
{
// TODO: Implement getClientAuthorizedRealms() method.
}
public function getClientScopes()
{
$scopes = $this->scopes()
@ -98,14 +99,10 @@ class Client extends BaseModelEloquent implements IClient {
return $res;
}
public function isRealmAllowed($realm)
{
return false;
}
public function isUriAllowed($uri)
{
if(! filter_var($uri, FILTER_VALIDATE_URL)) return false;
if(!filter_var($uri, FILTER_VALIDATE_URL)) return false;
$parts = @parse_url($uri);
if ($parts === false) {
return false;
@ -113,12 +110,15 @@ class Client extends BaseModelEloquent implements IClient {
if($parts['scheme']!=='https')
return false;
$client_authorized_uri = ClientAuthorizedUri::where('client_id', '=', $this->id)->where('uri','=',$uri)->first();
if(is_null($client_authorized_uri)){
if(!is_null($client_authorized_uri)) return true;
if(isset($parts['path'])){
$aux_uri = $parts['scheme'].'://'.strtolower($parts['host']).strtolower($parts['path']);
$client_authorized_uri = ClientAuthorizedUri::where('client_id', '=', $this->id)->where('uri','=',$aux_uri)->first();
return !is_null($client_authorized_uri);
}
return true;
return false;
}
public function getApplicationName()
@ -182,6 +182,10 @@ class Client extends BaseModelEloquent implements IClient {
return $this->application_type;
}
/**
* @return string
* @throws Exception
*/
public function getFriendlyApplicationType(){
switch($this->application_type){
case IClient::ApplicationType_JS_Client:
@ -196,4 +200,39 @@ class Client extends BaseModelEloquent implements IClient {
}
throw new Exception('Invalid Application Type');
}
public function getClientAllowedOrigins()
{
return $this->allowed_origins()->get();
}
/**
* the origin is the triple {protocol, host, port}
* @param $origin
* @return bool
*/
public function isOriginAllowed($origin)
{
if(!filter_var($origin, FILTER_VALIDATE_URL)) return false;
$parts = @parse_url($origin);
if ($parts === false) {
return false;
}
if($parts['scheme']!=='https')
return false;
$origin_without_port = sprinf("%sː//%s",$parts['scheme'],$parts['host']);
$client_allowed_origin = $this->allowed_origins()->where('allowed_origin','=',$origin_without_port)->first();
if(!is_null($client_allowed_origin)) return true;
if(isset($parts['port'])){
$origin_with_port = sprinf("%sː//%s:%s",$parts['scheme'],$parts['host'],$parts['port']);
$client_authorized_uri = $this->allowed_origins()->where('allowed_origin','=',$origin_with_port)->first();;
return !is_null($client_authorized_uri);
}
return false;
}
public function getWebsite()
{
return $this->website;
}
}

View File

@ -0,0 +1,12 @@
<?php
use utils\model\BaseModelEloquent;
class ClientAllowedOrigin extends BaseModelEloquent{
protected $table = 'oauth2_client_allowed_origin';
public function client(){
return $this->belongsTo('Client');
}
}

View File

@ -1,5 +1,13 @@
<?php
class ClientAuthorizedUri extends Eloquent {
use utils\model\BaseModelEloquent;
class ClientAuthorizedUri extends BaseModelEloquent {
protected $table = 'oauth2_client_authorized_uri';
public function client(){
return $this->belongsTo('Client');
}
}

View File

@ -88,9 +88,7 @@ Route::group(array('prefix' => 'admin','before' => 'ssl|auth'), function(){
});
});
//Admin Backend API
Route::group(array('prefix' => 'admin/api/v1', 'before' => 'ssl|auth'), function()
{
@ -112,14 +110,17 @@ Route::group(array('prefix' => 'admin/api/v1', 'before' => 'ssl|auth'), function
Route::get('/',array('before' => 'is.current.user', 'uses' => 'ClientApiController@getByPage'));
Route::delete('/{id}',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@delete'));
Route::group(array('prefix' => 'uris','before' => 'user.owns.client.policy'), function(){
Route::get('/{id}',"ClientApiController@getRegisteredUris");
Route::post('/{id}',"ClientApiController@addAllowedRedirectUri");
Route::delete('/{id}/{uri_id}',"ClientApiController@deleteClientAllowedUri");
});
//allowed redirect uris endpoints
Route::get('/{id}/uris',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@getRegisteredUris'));
Route::post('/{id}/uris',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@addAllowedRedirectUri'));
Route::delete('/{id}/uris/{uri_id}',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@deleteClientAllowedUri'));
//allowed origin endpoints endpoints
Route::get('/{id}/origins',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@geAllowedOrigins'));
Route::post('/{id}/origins',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@addAllowedOrigin'));
Route::delete('/{id}/origins/{origin_id}',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@deleteClientAllowedOrigin'));
Route::delete('/{id}/lock',array('before' => 'openstackid.server.admin.json', 'uses' => 'ClientApiController@unlock'));
Route::put('/{id}/secret',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@regenerateClientSecret'));
Route::put('/{id}/use-refresh-token',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@setRefreshTokenClient'));
Route::put('/{id}/rotate-refresh-token',array('before' => 'user.owns.client.policy', 'uses' => 'ClientApiController@setRotateRefreshTokenPolicy'));
@ -173,13 +174,10 @@ Route::group(array('prefix' => 'admin/api/v1', 'before' => 'ssl|auth'), function
});
});
//OAuth2 Protected API
Route::group(array('prefix' => 'api/v1', 'before' => 'ssl|oauth2.protected.endpoint'), function()
Route::group(array('prefix' => 'api/v1', 'before' => 'ssl|oauth2.cors.before|oauth2.protected.endpoint'), function()
{
/*
Route::group(array('prefix' => ''), function(){
Route::group(array('prefix' => 'users'), function(){
Route::get('/me','OAuth2UserApiController@me');
});
*/
});

View File

@ -1,14 +0,0 @@
<?php
namespace services;
use \Request;
class IPHelper
{
public static function getUserIp()
{
$remote_address = Request::server('REMOTE_ADDR');
return $remote_address;
}
}

View File

@ -1,132 +1,69 @@
<?php
namespace services;
use Illuminate\Support\ServiceProvider;
use openid\services\OpenIdServiceCatalog;
use utils\services\Registry;
use oauth2\services\OAuth2ServiceCatalog;
use utils\services\UtilsServiceCatalog;
use services\oauth2\ResourceServer;
use \Illuminate\Foundation\AliasLoader;
use services\utils\CheckPointService;
/**
* Class ServicesProvider
* @package services
*/
class ServicesProvider extends ServiceProvider
{
protected $defer = false;
public function boot()
{
public function boot(){
$this->app->singleton(UtilsServiceCatalog::CacheService, 'services\\RedisCacheService');
$this->app['serverconfigurationservice'] = $this->app->share(function ($app) {
return new ServerConfigurationService($this->app->make(UtilsServiceCatalog::CacheService));
});
}
// Shortcut so developers don't need to add an Alias in app/config/app.php
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('ServerConfigurationService', 'services\\Facades\\ServerConfigurationService');
});
//register on boot bc we rely on Illuminate\Redis\ServiceProvider\RedisServiceProvider
$this->app->singleton(OpenIdServiceCatalog::MementoService, 'services\\MementoRequestService');
$this->app->singleton(OpenIdServiceCatalog::AuthenticationStrategy, 'services\\AuthenticationStrategy');
$this->app->singleton(OpenIdServiceCatalog::ServerExtensionsService, 'services\\ServerExtensionsService');
$this->app->singleton(OpenIdServiceCatalog::AssociationService, 'services\\AssociationService');
$this->app->singleton(OpenIdServiceCatalog::TrustedSitesService, 'services\\TrustedSitesService');
$this->app->singleton(OpenIdServiceCatalog::ServerConfigurationService, 'services\\ServerConfigurationService');
$this->app->singleton(OpenIdServiceCatalog::UserService, 'services\\UserService');
$this->app->singleton(OpenIdServiceCatalog::NonceService, 'services\\NonceService');
$this->app->singleton(UtilsServiceCatalog::LogService, 'services\\LogService');
$this->app->singleton(UtilsServiceCatalog::LockManagerService, 'services\\LockManagerService');
$this->app->singleton(UtilsServiceCatalog::ServerConfigurationService, 'services\\ServerConfigurationService');
$this->app->singleton(UtilsServiceCatalog::BannedIpService, 'services\\utils\\BannedIPService');
public function register(){
$this->app->singleton('services\\IUserActionService', 'services\\UserActionService');
$this->app->singleton('oauth2\\IResourceServerContext', 'services\\oauth2\\ResourceServerContext');
$this->app->singleton("services\\DelayCounterMeasure", 'services\\DelayCounterMeasure');
$this->app->singleton("services\\LockUserCounterMeasure", 'services\\LockUserCounterMeasure');
$this->app->singleton("services\\oauth2\\RevokeAuthorizationCodeRelatedTokens", 'services\\oauth2\\RevokeAuthorizationCodeRelatedTokens');
$this->app->singleton("services\\BlacklistSecurityPolicy", 'services\\BlacklistSecurityPolicy');
$this->app->singleton("services\\LockUserSecurityPolicy", 'services\\LockUserSecurityPolicy');
$this->app->singleton("services\\OAuth2LockClientCounterMeasure", 'services\\OAuth2LockClientCounterMeasure');
$this->app->singleton("services\\OAuth2SecurityPolicy", 'services\\OAuth2SecurityPolicy');
$this->app->singleton("services\\oauth2\\AuthorizationCodeRedeemPolicy", 'services\\oauth2\\AuthorizationCodeRedeemPolicy');
$this->app->singleton(UtilsServiceCatalog::CheckPointService,
function(){
//set security policies
$delay_counter_measure = $this->app->make("services\\DelayCounterMeasure");
function(){
//set security policies
$delay_counter_measure = $this->app->make("services\\DelayCounterMeasure");
$blacklist_security_policy = $this->app->make("services\\BlacklistSecurityPolicy");
$blacklist_security_policy->setCounterMeasure($delay_counter_measure);
$blacklist_security_policy = $this->app->make("services\\BlacklistSecurityPolicy");
$blacklist_security_policy->setCounterMeasure($delay_counter_measure);
$revoke_tokens_counter_measure = $this->app->make("services\\oauth2\\RevokeAuthorizationCodeRelatedTokens");
$revoke_tokens_counter_measure = $this->app->make("services\\oauth2\\RevokeAuthorizationCodeRelatedTokens");
$authorization_code_redeem_Policy = $this->app->make("services\\oauth2\\AuthorizationCodeRedeemPolicy");
$authorization_code_redeem_Policy->setCounterMeasure($revoke_tokens_counter_measure);
$authorization_code_redeem_Policy = $this->app->make("services\\oauth2\\AuthorizationCodeRedeemPolicy");
$authorization_code_redeem_Policy->setCounterMeasure($revoke_tokens_counter_measure);
$lock_user_counter_measure = $this->app->make("services\\LockUserCounterMeasure");
$lock_user_counter_measure = $this->app->make("services\\LockUserCounterMeasure");
$lock_user_security_policy = $this->app->make("services\\LockUserSecurityPolicy");
$lock_user_security_policy->setCounterMeasure($lock_user_counter_measure);
$lock_user_security_policy = $this->app->make("services\\LockUserSecurityPolicy");
$lock_user_security_policy->setCounterMeasure($lock_user_counter_measure);
$oauth2_lock_client_counter_measure = $this->app->make("services\\OAuth2LockClientCounterMeasure");
$oauth2_security_policy = $this->app->make("services\\OAuth2SecurityPolicy");
$oauth2_security_policy->setCounterMeasure($oauth2_lock_client_counter_measure);
$oauth2_lock_client_counter_measure = $this->app->make("services\\OAuth2LockClientCounterMeasure");
$oauth2_security_policy = $this->app->make("services\\OAuth2SecurityPolicy");
$oauth2_security_policy->setCounterMeasure($oauth2_lock_client_counter_measure);
$checkpoint_service = new CheckPointService($blacklist_security_policy);
$checkpoint_service->addPolicy($lock_user_security_policy);
$checkpoint_service->addPolicy($authorization_code_redeem_Policy);
$checkpoint_service->addPolicy($oauth2_security_policy);
return $checkpoint_service;
});
$checkpoint_service = new CheckPointService($blacklist_security_policy);
$checkpoint_service->addPolicy($lock_user_security_policy);
$checkpoint_service->addPolicy($authorization_code_redeem_Policy);
$checkpoint_service->addPolicy($oauth2_security_policy);
return $checkpoint_service;
});
Registry::getInstance()->set(UtilsServiceCatalog::CheckPointService, $this->app->make(UtilsServiceCatalog::CheckPointService));
Registry::getInstance()->set(OpenIdServiceCatalog::MementoService, $this->app->make(OpenIdServiceCatalog::MementoService));
Registry::getInstance()->set(OpenIdServiceCatalog::AuthenticationStrategy, $this->app->make(OpenIdServiceCatalog::AuthenticationStrategy));
Registry::getInstance()->set(OpenIdServiceCatalog::ServerExtensionsService, $this->app->make(OpenIdServiceCatalog::ServerExtensionsService));
Registry::getInstance()->set(OpenIdServiceCatalog::AssociationService, $this->app->make(OpenIdServiceCatalog::AssociationService));
Registry::getInstance()->set(OpenIdServiceCatalog::TrustedSitesService, $this->app->make(OpenIdServiceCatalog::TrustedSitesService));
Registry::getInstance()->set(OpenIdServiceCatalog::ServerConfigurationService, $this->app->make(OpenIdServiceCatalog::ServerConfigurationService));
Registry::getInstance()->set(OpenIdServiceCatalog::UserService, $this->app->make(OpenIdServiceCatalog::UserService));
Registry::getInstance()->set(OpenIdServiceCatalog::NonceService, $this->app->make(OpenIdServiceCatalog::NonceService));
Registry::getInstance()->set(UtilsServiceCatalog::LogService, $this->app->make(UtilsServiceCatalog::LogService));
Registry::getInstance()->set(UtilsServiceCatalog::CheckPointService, $this->app->make(UtilsServiceCatalog::CheckPointService));
Registry::getInstance()->set(UtilsServiceCatalog::ServerConfigurationService, $this->app->make(UtilsServiceCatalog::ServerConfigurationService));
Registry::getInstance()->set(UtilsServiceCatalog::CacheService, $this->app->make(UtilsServiceCatalog::CacheService));
$this->app->singleton(OAuth2ServiceCatalog::MementoService, 'services\\oauth2\\MementoOAuth2AuthenticationRequestService');
$this->app->singleton(OAuth2ServiceCatalog::ClientService, 'services\\oauth2\\ClientService');
$this->app->singleton(OAuth2ServiceCatalog::TokenService, 'services\\oauth2\\TokenService');
$this->app->singleton(OAuth2ServiceCatalog::ScopeService, 'services\\oauth2\\ApiScopeService');
$this->app->singleton(OAuth2ServiceCatalog::ResourceServerService, 'services\\oauth2\\ResourceServerService');
$this->app->singleton(OAuth2ServiceCatalog::ApiService, 'services\\oauth2\\ApiService');
$this->app->singleton(OAuth2ServiceCatalog::ApiEndpointService, 'services\\oauth2\\ApiEndpointService');
$this->app->singleton(OAuth2ServiceCatalog::UserConsentService, 'services\\oauth2\\UserConsentService');
Registry::getInstance()->set(OAuth2ServiceCatalog::MementoService, $this->app->make(OAuth2ServiceCatalog::MementoService));
Registry::getInstance()->set(OAuth2ServiceCatalog::TokenService, $this->app->make(OAuth2ServiceCatalog::TokenService));
Registry::getInstance()->set(OAuth2ServiceCatalog::ScopeService, $this->app->make(OAuth2ServiceCatalog::ScopeService));
Registry::getInstance()->set(OAuth2ServiceCatalog::ClientService, $this->app->make(OAuth2ServiceCatalog::ClientService));
Registry::getInstance()->set(OAuth2ServiceCatalog::ResourceServerService, $this->app->make(OAuth2ServiceCatalog::ResourceServerService));
Registry::getInstance()->set(OAuth2ServiceCatalog::ApiService, $this->app->make(OAuth2ServiceCatalog::ApiService));
Registry::getInstance()->set(OAuth2ServiceCatalog::ApiEndpointService, $this->app->make(OAuth2ServiceCatalog::ApiEndpointService));
}
public function register()
public function provides()
{
return array('application.services');
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace services\Facades;
namespace services\facades;
use Illuminate\Support\Facades\Facade;

View File

@ -0,0 +1,76 @@
<?php
namespace services\oauth2;
use oauth2\services\IAllowedOriginService;
use Client;
use ClientAllowedOrigin;
/**
* Class AllowedOriginService
* @package services\oauth2
*/
class AllowedOriginService implements IAllowedOriginService{
/**
* @param $id
* @return mixed
*/
public function get($id)
{
return ClientAllowedOrigin::find($id);
}
/**
* @param $uri
* @return mixed
*/
public function getByUri($uri)
{
return ClientAllowedOrigin::where('allowed_origin','=',$uri)->first();
}
/**
* @param $uri
* @param $client_id
* @return bool|int
*/
public function create($uri, $client_id)
{
$origin = new ClientAllowedOrigin();
$origin->allowed_origin = $uri;
$client = Client::find($client_id);
if(!is_null($client)){
$client->allowed_origins()->save($origin);
$origin->Save();
return $origin->id;
}
return false;
}
/**
* @param $id
* @return bool
*/
public function delete($id)
{
$origin = $this->get($id);
if(!is_null($origin)){
return $origin->delete();
}
return false;
}
/**
* @param $uri
* @return bool
*/
public function deleteByUri($uri)
{
$origin = $this->getByUri($uri);
if(!is_null($origin)){
return $origin->delete();
}
return false;
}
}

View File

@ -26,6 +26,16 @@ class ApiEndpointService implements IApiEndpointService {
return ApiEndpoint::where('route','=',$url)->where('http_method','=',$http_method)->first();
}
/**
* @param $url
* @return IApiEndpoint
*/
public function getApiEndpointByUrl($url)
{
return ApiEndpoint::where('route','=',$url)->first();
}
/**
* @param $id
* @return IApiEndpoint
@ -51,16 +61,17 @@ class ApiEndpointService implements IApiEndpointService {
* @param string $name
* @param string $description
* @param boolean $active
* @param boolean $allow_cors
* @param string $route
* @param string $http_method
* @param integer $api_id
* @return IApiEndpoint
*/
public function add($name, $description, $active, $route, $http_method, $api_id)
public function add($name, $description, $active,$allow_cors, $route, $http_method, $api_id)
{
$instance = null;
DB::transaction(function () use ($name, $description, $active, $route, $http_method, $api_id, &$instance) {
DB::transaction(function () use ($name, $description, $active,$allow_cors, $route, $http_method, $api_id, &$instance) {
//check that does not exists an endpoint with same http method and same route
if(ApiEndpoint::where('http_method','=',$http_method)->where('route','=',$route)->count()>0)
@ -74,6 +85,7 @@ class ApiEndpointService implements IApiEndpointService {
'route' => $route,
'http_method' => $http_method,
'api_id' => $api_id,
'allow_cors' => $allow_cors
)
);
$instance->Save();
@ -95,7 +107,7 @@ class ApiEndpointService implements IApiEndpointService {
if(is_null($endpoint))
throw new InvalidApiEndpoint(sprintf('api endpoint id %s does not exists!',$id));
$allowed_update_params = array('name','description','active','route','http_method');
$allowed_update_params = array('name','description','active','route','http_method','allow_cors');
foreach($allowed_update_params as $param){
if(array_key_exists($param,$params)){
$endpoint->{$param} = $params[$param];

View File

@ -0,0 +1,203 @@
<?php
namespace services\oauth2\CORS;
use oauth2\models\IApiEndpoint;
use oauth2\services\IAllowedOriginService;
use oauth2\services\IApiEndpointService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use utils\services\ICacheService;
use Route;
use App;
use Log;
use Exception;
use Config;
/**
* Class CORSMiddleware
* @package services\oauth2
* Implementation of http://www.w3.org/TR/cors/
*/
class CORSMiddleware {
private $app;
private $endpoint_service;
private $cache_service;
private $origin_service;
private $modify_response = false;
private $headers = array();
private $allowed_headers;
private $allowed_methods;
/**
* Simple headers as defined in the spec should always be accepted
*/
protected static $simple_headers = array(
'accept',
'accept-language',
'content-language',
'origin',
);
const DefaultAllowedHeaders = 'origin, content-type, accept, authorization';
const DefaultAllowedMethods = 'GET, POST, OPTIONS, PUT, DELETE';
public function __construct(IApiEndpointService $endpoint_service,
ICacheService $cache_service,
IAllowedOriginService $origin_service)
{
$this->endpoint_service = $endpoint_service;
$this->cache_service = $cache_service;
$this->origin_service = $origin_service;
$this->allowed_headers = Config::get('cors.AllowedHeaders',self::DefaultAllowedHeaders);
$this->allowed_methods = Config::get('cors.AllowedMethods',self::DefaultAllowedMethods);
}
private function makePreflightResponse(Request $request, IApiEndpoint $endpoint){
$response = new Response();
$allow_credentials = Config::get('cors.AllowCredentials', '');
if(!empty($allow_credentials)){
$response->headers->set('Access-Control-Allow-Credentials',$allow_credentials );
}
if(Config::get('cors.UsePreflightCaching', false)){
$response->headers->set('Access-Control-Max-Age', Config::get('cors.MaxAge', 32000));
}
$response->headers->set('Access-Control-Allow-Headers', $this->allowed_headers);
if (!$this->checkOrigin($request)) {
$response->headers->set('Access-Control-Allow-Origin', 'null');
return $response;
}
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
// check request method
if ($request->headers->get('Access-Control-Request-Method') != $endpoint->getHttpMethod()) {
$response->setStatusCode(405);
return $response;
}
$response->headers->set('Access-Control-Allow-Methods', $this->allowed_methods);
// check request headers
$allow_headers = explode(', ',$this->allowed_headers);
$headers = $request->headers->get('Access-Control-Request-Headers');
if ($headers) {
$headers = trim(strtolower($headers));
foreach (preg_split('{, *}', $headers) as $header) {
if (in_array($header, self::$simple_headers, true)) {
continue;
}
if (!in_array($header, $allow_headers, true)) {
$response->setStatusCode(400);
$response->setContent('Unauthorized header '.$header);
break;
}
}
}
$response->setStatusCode(204);
return $response;
}
private function checkOrigin(Request $request)
{
// check origin
$origin = $request->headers->get('Origin');
if($this->cache_service->getSingleValue($origin)) return true;
if($origin = $this->origin_service->getByUri($origin)){
$this->cache_service->addSingleValue($origin,$origin);
return true;
}
Log::warning(sprintf('CORS: origin %s not allowed!',$origin));
return false;
}
public function verifyRequest($request){
try{
// skip if not a CORS request
if (!$request->headers->has('Origin')) {
return;
}
$method = $request->getMethod();
$preflight = false;
//preflight checks
if ($method === 'OPTIONS') {
$request_method = $request->headers->get('Access-Control-Request-Method');
if(is_null($request_method)){
Log::warning('CORS: not a valid preflight request!');
return;
}
// sets the original method on request in order to be able to find the
// correct route
$request->setMethod($request_method);
$preflight = true;
}
//gets routes from container and try to find the route
$router = App::make('router');
$routes = $router->getRoutes();
$route = $routes->match($request);
$url = $route->getPath();
if(strpos($url, '/') != 0){
$url = '/'.$url;
}
$endpoint = $this->endpoint_service->getApiEndpointByUrl($url);
//check if api endpoint exists or not, if active and if supports cors
if(is_null($endpoint) || !$endpoint->isActive() || !$endpoint->supportCORS()){
if(is_null($endpoint)){
Log::warning(sprintf("does not exists an endpoint for url %s.",$url));
}
else if(!$endpoint->isActive()){
Log::warning(sprintf("endpoint %s is not active.",$url));
}
else if(!$endpoint->supportCORS()){
Log::warning(sprintf("endpoint %s does not support CORS.",$url));
}
return;
}
// perform preflight checks
if ($preflight) {
return $this->makePreflightResponse($request,$endpoint);
}
if (!$this->checkOrigin($request)) {
return new Response('', 403, array('Access-Control-Allow-Origin' => 'null'));
}
$this->modify_response = true;
// Save response headers
$this->headers['Access-Control-Allow-Origin'] = $request->headers->get('Origin');
$this->headers['Access-Control-Allow-Credentials'] = 'true';
}
catch(Exception $ex){
Log::error($ex);
}
}
public function modifyResponse($request,$response)
{
if(!$this->modify_response){
return $response;
}
// add CORS response headers
Log::info('CORS: Adding CORS HEADERS.');
$response->headers->add($this->headers);
return $response;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace services\oauth2\CORS;
use Illuminate\Support\ServiceProvider;
class CORSProvider extends ServiceProvider {
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('CORSMiddleware', 'services\oauth2\CORS\CORSMiddleware');
}
public function boot(){
}
public function provides()
{
return array('oauth2.cors');
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

View File

@ -4,6 +4,8 @@ namespace services\oauth2;
use Client;
use ClientAuthorizedUri;
use ClientAllowedOrigin;
use DB;
use Input;
use oauth2\exceptions\AllowedClientUriAlreadyExistsException;
@ -20,7 +22,7 @@ use oauth2\services\id;
use oauth2\services\OAuth2ServiceCatalog;
use Request;
use utils\services\IAuthService;
use utils\services\Registry;
use utils\services\ServiceLocator;
use Zend\Math\Rand;
/**
@ -77,10 +79,10 @@ class ClientService implements IClientService
return array($client_id, $client_secret);
}
public function addClient($application_type, $user_id, $app_name, $app_description, $app_logo = '')
public function addClient($application_type, $user_id, $app_name, $app_description,$app_url=null, $app_logo = '')
{
$instance = null;
DB::transaction(function () use ($application_type, $user_id, $app_name, $app_description, $app_logo, &$instance) {
DB::transaction(function () use ($application_type, $user_id, $app_name,$app_url, $app_description, $app_logo, &$instance) {
//check $application_type vs client_type
$client_type = $application_type == IClient::ApplicationType_JS_Client?IClient::ClientType_Public:IClient::ClientType_Confidential;
@ -98,6 +100,7 @@ class ClientService implements IClientService
$instance->active = true;
$instance->use_refresh_token = false;
$instance->rotate_refresh_token = false;
$instance->website = $app_url;
$instance->Save();
//default allowed url
$this->addClientAllowedUri($instance->getId(), 'https://localhost');
@ -115,20 +118,24 @@ class ClientService implements IClientService
public function addClientAllowedUri($id, $uri)
{
$client = Client::find($id);
$res = false;
DB::transaction(function () use ($id,$uri,&$res){
$client = Client::find($id);
if (is_null($client))
throw new AbsentClientException(sprintf("client id %s does not exists!",$id));
if (is_null($client))
throw new AbsentClientException(sprintf("client id %s does not exists!",$id));
$client_uri = ClientAuthorizedUri::where('uri', '=', $uri)->where('client_id', '=', $id)->first();
if (!is_null($client_uri)) {
throw new AllowedClientUriAlreadyExistsException(sprintf('uri : %s', $uri));
}
$client_uri = ClientAuthorizedUri::where('uri', '=', $uri)->where('client_id', '=', $id)->first();
if (!is_null($client_uri)) {
throw new AllowedClientUriAlreadyExistsException(sprintf('uri : %s', $uri));
}
$client_authorized_uri = new ClientAuthorizedUri;
$client_authorized_uri->client_id = $id;
$client_authorized_uri->uri = $uri;
return $client_authorized_uri->Save();
$client_authorized_uri = new ClientAuthorizedUri;
$client_authorized_uri->client_id = $id;
$client_authorized_uri->uri = $uri;
$res = $client_authorized_uri->Save();
});
return $res;
}
public function addClientScope($id, $scope_id)
@ -165,7 +172,7 @@ class ClientService implements IClientService
if (!is_null($client)) {
$client->authorized_uris()->delete();
$client->scopes()->detach();
$token_service = Registry::getInstance()->get(OAuth2ServiceCatalog::TokenService);
$token_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::TokenService);
$token_service->revokeClientRelatedTokens($client->client_id);
$res = $client->delete();
}
@ -193,7 +200,7 @@ class ClientService implements IClientService
$client_secret = Rand::getString(24, OAuth2Protocol::VsChar, true);
$client->client_secret = $client_secret;
$client->Save();
$token_service = Registry::getInstance()->get(OAuth2ServiceCatalog::TokenService);
$token_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::TokenService);
$token_service->revokeClientRelatedTokens($client->client_id);
$new_secret = $client->client_secret;
@ -208,11 +215,15 @@ class ClientService implements IClientService
*/
public function lockClient($client_id)
{
$client = $this->getClientByIdentifier($client_id);
if (is_null($client))
throw new AbsentClientException($client_id,sprintf("client id %s does not exists!",$client_id));
$client->locked = true;
return $client->Save();
$res = false;
DB::transaction(function () use ($client_id, &$res) {
$client = $this->getClientByIdentifier($client_id);
if (is_null($client))
throw new AbsentClientException($client_id,sprintf("client id %s does not exists!",$client_id));
$client->locked = true;
$res = $client->Save();
});
return $res;
}
/**
@ -222,11 +233,15 @@ class ClientService implements IClientService
*/
public function unlockClient($client_id)
{
$client = $this->getClientByIdentifier($client_id);
if (is_null($client))
throw new AbsentClientException($client_id,sprintf("client id %s does not exists!",$client_id));
$client->locked = false;
return $client->Save();
$res = false;
DB::transaction(function () use ($client_id, &$res) {
$client = $this->getClientByIdentifier($client_id);
if (is_null($client))
throw new AbsentClientException($client_id,sprintf("client id %s does not exists!",$client_id));
$client->locked = false;
$res = $client->Save();
});
return $res;
}
@ -322,17 +337,65 @@ class ClientService implements IClientService
*/
public function update($id, array $params)
{
$client = Client::find($id);
if(is_null($client))
throw new AbsentClientException(sprintf('client id %s does not exists!',$id));
$res = false;
DB::transaction(function () use ($id,$params, &$res) {
$client = Client::find($id);
if(is_null($client))
throw new AbsentClientException(sprintf('client id %s does not exists!',$id));
$allowed_update_params = array('app_name','app_description','app_logo','active','locked','use_refresh_token','rotate_refresh_token');
$allowed_update_params = array(
'app_name','website','app_description','app_logo','active','locked','use_refresh_token','rotate_refresh_token');
foreach($allowed_update_params as $param){
if(array_key_exists($param,$params)){
$client->{$param} = $params[$param];
foreach($allowed_update_params as $param){
if(array_key_exists($param,$params)){
$client->{$param} = $params[$param];
}
}
}
return $this->save($client);
$res = $this->save($client);
});
return $res;
}
/**
* @param $id
* @param $origin
* @return mixed
* @throws \oauth2\exceptions\AllowedClientUriAlreadyExistsException
* @throws \oauth2\exceptions\AbsentClientException
*/
public function addClientAllowedOrigin($id, $origin)
{
$res = false;
DB::transaction(function () use ($id, $origin, &$res) {
$client = Client::find($id);
if (is_null($client))
throw new AbsentClientException(sprintf("client id %s does not exists!",$id));
if($client->getApplicationType()!=IClient::ApplicationType_JS_Client)
throw new InvalidClientType($id,sprintf("client id %s application type must be JS_CLIENT",$id));
$client_origin = ClientAllowedOrigin::where('allowed_origin', '=', $origin)->where('client_id', '=', $id)->first();
if (!is_null($client_origin)) {
throw new AllowedClientUriAlreadyExistsException(sprintf('origin : %s', $origin));
}
$client_origin = new ClientAllowedOrigin;
$client_origin->client_id = $id;
$client_origin->allowed_origin = $origin;
$res = $client_origin->Save();
});
return $res;
}
/**
* @param $id
* @param $origin_id
* @return mixed
*/
public function deleteClientAllowedOrigin($id, $origin_id)
{
return ClientAllowedOrigin::where('id', '=', $origin_id)->where('client_id', '=', $id)->delete();
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace services\oauth2;
use Illuminate\Support\ServiceProvider;
use oauth2\services\OAuth2ServiceCatalog;
use services\oauth2\ResourceServer;
/**
* Class OAuth2ServiceProvider
* @package services\oauth2
*/
class OAuth2ServiceProvider extends ServiceProvider
{
protected $defer = false;
public function boot(){
}
public function register(){
$this->app->singleton('oauth2\\IResourceServerContext', 'services\\oauth2\\ResourceServerContext');
$this->app->singleton(OAuth2ServiceCatalog::MementoService, 'services\\oauth2\\MementoOAuth2AuthenticationRequestService');
$this->app->singleton(OAuth2ServiceCatalog::ClientService, 'services\\oauth2\\ClientService');
$this->app->singleton(OAuth2ServiceCatalog::TokenService, 'services\\oauth2\\TokenService');
$this->app->singleton(OAuth2ServiceCatalog::ScopeService, 'services\\oauth2\\ApiScopeService');
$this->app->singleton(OAuth2ServiceCatalog::ResourceServerService, 'services\\oauth2\\ResourceServerService');
$this->app->singleton(OAuth2ServiceCatalog::ApiService, 'services\\oauth2\\ApiService');
$this->app->singleton(OAuth2ServiceCatalog::ApiEndpointService, 'services\\oauth2\\ApiEndpointService');
$this->app->singleton(OAuth2ServiceCatalog::UserConsentService, 'services\\oauth2\\UserConsentService');
$this->app->singleton(OAuth2ServiceCatalog::AllowedOriginService, 'services\\oauth2\\AllowedOriginService');
//OAUTH2 resource server endpoints
$this->app->singleton('oauth2\resource_server\IUserService', 'services\oauth2\resource_server\UserService');
}
public function provides()
{
return array('oauth2.services');
}
}

View File

@ -13,11 +13,11 @@ class ResourceServerContext implements IResourceServerContext {
private $auth_context;
/**
* @return null|string
* @return array
*/
public function getCurrentScope()
{
return isset($this->auth_context['scope'])?$this->auth_context['scope']:null;
return isset($this->auth_context['scope'])? explode(' ',$this->auth_context['scope']):array();
}
/**
@ -45,6 +45,14 @@ class ResourceServerContext implements IResourceServerContext {
return isset($this->auth_context['client_id'])?$this->auth_context['client_id']:null;
}
/**
* @return null|int
*/
public function getCurrentUserId()
{
return isset($this->auth_context['user_id'])?intval($this->auth_context['user_id']):null;
}
/**
* @param $auth_context
*/
@ -52,12 +60,4 @@ class ResourceServerContext implements IResourceServerContext {
{
$this->auth_context = $auth_context;
}
/**
* @return null
*/
public function getCurrentUserId()
{
return isset($this->auth_context['user_id'])?$this->auth_context['user_id']:null;
}
}

View File

@ -5,7 +5,7 @@ namespace services\oauth2;
use Exception;
use Log;
use oauth2\services\OAuth2ServiceCatalog;
use utils\services\Registry;
use utils\services\ServiceLocator;
use utils\services\ISecurityPolicyCounterMeasure;
@ -32,8 +32,8 @@ class RevokeAuthorizationCodeRelatedTokens implements ISecurityPolicyCounterMeas
$auth_code = $params["auth_code"];
//$client_id = $params["client_id"];
$token_service = Registry::getInstance()->get(OAuth2ServiceCatalog::TokenService);
//$client_service = Registry::getInstance()->get(OAuth2ServiceCatalog::ClientService);
$token_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::TokenService);
//$client_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ClientService);
$token_service->revokeAuthCodeRelatedTokens($auth_code);

View File

@ -23,7 +23,7 @@ use oauth2\services\IUserConsentService;
use RefreshToken as RefreshTokenDB;
use RefreshToken as DBRefreshToken;
use services\IPHelper;
use utils\IPHelper;
use utils\exceptions\UnacquiredLockException;
use utils\services\ILockManagerService;

View File

@ -0,0 +1,73 @@
<?php
namespace services\oauth2\resource_server;
use oauth2\resource_server\IUserService;
use oauth2\resource_server\OAuth2ProtectedService;
use oauth2\IResourceServerContext;
use utils\services\ILogService;
use openid\services\IUserService as IAPIUserService;
use Exception;
/**
* Class UserService
* OAUTH2 Protected Endpoint
* @package services\oauth2\resource_server
*/
class UserService extends OAuth2ProtectedService implements IUserService {
private $user_service;
public function __construct(IAPIUserService $user_service, IResourceServerContext $resource_server_context, ILogService $log_service){
parent::__construct($resource_server_context,$log_service);
$this->user_service = $user_service;
}
/**
* Get Current user info
* @return array
* @throws Exception
*/
public function getCurrentUserInfo()
{
$data = array();
try{
$me = $this->resource_server_context->getCurrentUserId();
if(is_null($me)){
throw new Exception('me is no set!.');
}
$current_user = $this->user_service->get($me);
$scopes = $this->resource_server_context->getCurrentScope();
if(in_array(self::UserProfileScope_Address, $scopes)){
// Address Claim
$data['country'] = $current_user->getCountry();
$data['street_address'] = $current_user->getCountry();
$data['postal_code'] = $current_user->getPostalCode();
$data['region'] = $current_user->getRegion();
$data['locality'] = $current_user->getLocality();
}
if(in_array(self::UserProfileScope_Profile, $scopes)){
// Address Claim
$data['name'] = $current_user->getFirstName();
$data['family_name'] = $current_user->getLastName();
$data['nickname'] = $current_user->getNickName();
$data['picture'] = $current_user->getPic();
$data['birthdate'] = $current_user->getDateOfBirth();
$data['gender'] = $current_user->getGender();
}
if(in_array(self::UserProfileScope_Email, $scopes)){
// Address Claim
$data['email'] = $current_user->getEmail();
}
}
catch(Exception $ex){
$this->log_service->error($ex);
throw $ex;
}
return $data;
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace services;
namespace services\openid;
use Log;
use openid\exceptions\OpenIdInvalidRealmException;

View File

@ -1,12 +1,16 @@
<?php
namespace services;
namespace services\openid;
use openid\handlers\IOpenIdAuthenticationStrategy;
use openid\requests\contexts\RequestContext;
use openid\requests\OpenIdAuthenticationRequest;
use Redirect;
/**
* Class AuthenticationStrategy
* @package services\openid
*/
class AuthenticationStrategy implements IOpenIdAuthenticationStrategy
{

View File

@ -1,6 +1,6 @@
<?php
namespace services;
namespace services\openid;
use Input;
use openid\OpenIdMessage;

View File

@ -1,6 +1,6 @@
<?php
namespace services;
namespace services\openid;
use Exception;
use Log;
@ -11,6 +11,7 @@ use openid\services\INonceService;
use utils\exceptions\UnacquiredLockException;
use utils\services\ILockManagerService;
use utils\services\ICacheService;
use utils\services\IServerConfigurationService;
class NonceService implements INonceService
{
@ -18,11 +19,15 @@ class NonceService implements INonceService
private $cache_service;
private $lock_manager_service;
private $configuration_service;
public function __construct(ILockManagerService $lock_manager_service,ICacheService $cache_service)
public function __construct(ILockManagerService $lock_manager_service,
ICacheService $cache_service,
IServerConfigurationService $configuration_service)
{
$this->lock_manager_service = $lock_manager_service;
$this->cache_service = $cache_service;
$this->lock_manager_service = $lock_manager_service;
$this->cache_service = $cache_service;
$this->configuration_service = $configuration_service;
}
/**
@ -33,7 +38,7 @@ class NonceService implements INonceService
public function lockNonce(OpenIdNonce $nonce)
{
$raw_nonce = $nonce->getRawFormat();
$lock_lifetime = \ServerConfigurationService::getConfigValue("Nonce.Lifetime");
$lock_lifetime = $this->configuration_service->getConfigValue("Nonce.Lifetime");
try {
$this->lock_manager_service->acquireLock('lock.nonce.' . $raw_nonce, $lock_lifetime);
} catch (UnacquiredLockException $ex) {
@ -91,7 +96,7 @@ class NonceService implements INonceService
{
try {
$raw_nonce = $nonce->getRawFormat();
$lifetime = \ServerConfigurationService::getConfigValue("Nonce.Lifetime");
$lifetime = $this->configuration_service->getConfigValue("Nonce.Lifetime");
$this->cache_service->setSingleValue($raw_nonce . $signature, $realm, $lifetime );
} catch (Exception $ex) {
Log::error($ex);

View File

@ -0,0 +1,33 @@
<?php
namespace services\openid;
use Illuminate\Support\ServiceProvider;
use utils\services\UtilsServiceCatalog;
use utils\services\ServiceLocator;
use openid\services\OpenIdServiceCatalog;
class OpenIdProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//register on boot bc we rely on Illuminate\Redis\ServiceProvider\RedisServiceProvider
$this->app->singleton(OpenIdServiceCatalog::MementoService, 'services\\openid\\MementoRequestService');
$this->app->singleton(OpenIdServiceCatalog::AuthenticationStrategy, 'services\\openid\\AuthenticationStrategy');
$this->app->singleton(OpenIdServiceCatalog::ServerExtensionsService, 'services\\openid\\ServerExtensionsService');
$this->app->singleton(OpenIdServiceCatalog::AssociationService, 'services\\openid\\AssociationService');
$this->app->singleton(OpenIdServiceCatalog::TrustedSitesService, 'services\\openid\\TrustedSitesService');
$this->app->singleton(OpenIdServiceCatalog::ServerConfigurationService, 'services\\utils\\ServerConfigurationService');
$this->app->singleton(OpenIdServiceCatalog::UserService, 'services\\openid\\UserService');
$this->app->singleton(OpenIdServiceCatalog::NonceService, 'services\\openid\\NonceService');
}
public function provides()
{
return array('openid.services');
}
}

View File

@ -1,20 +1,27 @@
<?php
namespace services;
namespace services\openid;
use openid\services\IServerExtensionsService;
use utils\services\ServiceLocator;
use utils\services\UtilsServiceCatalog;
use ServerExtension;
class ServerExtensionsService implements IServerExtensionsService
{
public function getAllActiveExtensions()
{
$extensions = \ServerExtension::where('active', '=', true)->get();
$extensions = ServerExtension::where('active', '=', true)->get();
$res = array();
foreach ($extensions as $extension) {
$class = $extension->extension_class;
if (empty($class) /*|| !class_exists($class)*/) continue;
$implementation = new $class($extension->name, $extension->namespace, $extension->view_name, $extension->description);
$implementation = new $class($extension->name,
$extension->namespace,
$extension->view_name,
$extension->description,
ServiceLocator::getInstance()->getService(UtilsServiceCatalog::LogService));
array_push($res, $implementation);
}
return $res;

View File

@ -1,6 +1,6 @@
<?php
namespace services;
namespace services\openid;
use openid\model\IOpenIdUser;
use openid\model\ITrustedSite;

View File

@ -1,6 +1,6 @@
<?php
namespace services;
namespace services\openid;
use auth\User;
use DB;
@ -143,6 +143,9 @@ class UserService implements IUserService
}
}
public function get($id){
return User::find($id);
}
/**
* @param int $page_nbr
* @param int $page_size

View File

@ -11,6 +11,7 @@ use utils\services\ILockManagerService;
use utils\services\ISecurityPolicy;
use utils\services\ISecurityPolicyCounterMeasure;
use utils\services\IServerConfigurationService;
use utils\IPHelper;
abstract class AbstractBlacklistSecurityPolicy implements ISecurityPolicy
{

View File

@ -12,7 +12,7 @@ use utils\exceptions\UnacquiredLockException;
use utils\services\ICacheService;
use utils\services\ILockManagerService;
use utils\services\IServerConfigurationService;
use utils\IPHelper;
/**
* Class BlacklistSecurityPolicy
* implements check point security pattern

View File

@ -6,6 +6,7 @@ use Exception;
use Log;
use utils\services\ICacheService;
use utils\services\ISecurityPolicyCounterMeasure;
use utils\IPHelper;
class DelayCounterMeasure implements ISecurityPolicyCounterMeasure
{

Some files were not shown because too many files have changed in this diff Show More