IDP Upgrade from Laravel 4.X to 5.X

In order to migrate IDP from LV 4.x to
latest LV version, following task were performed:

* Updated namespace to be complain with PSR-4
* General Refactoring: moved all DB access code
  from services to repositories.
* Migration to LV 5.X: these migration guides
  were applied
  - https://laravel.com/docs/5.3/upgrade#upgrade-5.0
  - https://laravel.com/docs/5.3/upgrade#upgrade-5.1.0
  - https://laravel.com/docs/5.3/upgrade#upgrade-5.2.0
* Improved caching: added repositories decorators
  in order to add REDIS cache to queries, entities

Change-Id: I8edf9f5fce6585129701c88bb88332f242307534
This commit is contained in:
Sebastian Marcet 2016-04-13 20:11:36 -03:00
parent 9c8ed1ae7d
commit 6b0d6c36af
955 changed files with 24795 additions and 16477 deletions

64
.env.example Normal file
View File

@ -0,0 +1,64 @@
APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString
APP_URL=http://localhost
APP_OAUTH_2_0_CLIENT_ID=clientid
APP_OAUTH_2_0_CLIENT_SECRET=clientsecret
APP_OAUTH_2_0_AUTH_SERVER_BASE_URL=http://localhost
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
SS_DB_DRIVER=mysql
SS_DB_HOST=localhost
SS_DB_DATABASE=homestead
SS_DB_USERNAME=homestead
SS_DB_PASSWORD=secret
REDIS_HOST=127.0.0.1
REDIS_PORT=port
REDIS_DB=0
REDIS_PASSWORD=
CACHE_DRIVER=file
SESSION_DRIVER=redis
SESSION_COOKIE_DOMAIN=
SESSION_COOKIE_SECURE=false
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
CORS_ALLOWED_HEADERS=origin, content-type, accept, authorization, x-requested-with
CORS_ALLOWED_METHODS=GET, POST, OPTIONS, PUT, DELETE
CORS_USE_PRE_FLIGHT_CACHING=true
CORS_MAX_AGE=3200
CORS_EXPOSED_HEADERS=
CURL_TIMEOUT=3600
CURL_ALLOWS_REDIRECT=false
CURL_VERIFY_SSL_CERT=false
ASSETS_BASE_URL=http://www.openstack.org
SSL_ENABLED=true
DB_LOG_ENABLED=true
ACCESS_TOKEN_CACHE_LIFETIME=300
API_RESPONSE_CACHE_LIFETIME=600
LOG_EMAIL_TO=smarcet@gmail.com
LOG_EMAIL_FROM=smarcet@gmail.com
LOG_LEVEL=info
EVENTBRITE_OAUTH2_PERSONAL_TOKEN=
RECAPTCHA_PUBLIC_KEY=
RECAPTCHA_PRIVATE_KEY=
BANNING_ENABLE=

4
.gitattributes vendored
View File

@ -1 +1,3 @@
* text=auto
* text=auto
*.css linguist-vendored
*.less linguist-vendored

22
.gitignore vendored
View File

@ -1,20 +1,7 @@
/vendor
composer.phar
composer.lock
.DS_Storeapp/storage
/app/storage/*
.idea/*
app/config/dev/*
app/config/testing/*
app/config/local/*
app/config/production/*
app/config/staging/*
app/config/packages/greggilbert/recaptcha/dev/*
app/config/packages/greggilbert/recaptcha/local/*
app/config/packages/greggilbert/recaptcha/production/*
app/config/packages/greggilbert/recaptcha/staging/*
/bootstrap/compiled.php
/bootstrap/environment.php
.tox
AUTHORS
ChangeLog
@ -23,4 +10,11 @@ doc/build
*.egg-info
public/bower_assets
public/bower_assets/*
*.log
*.log
/node_modules
/public/storage
Homestead.yaml
Homestead.json
.env
.env.testing

View File

@ -0,0 +1,33 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
class Inspire extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'inspire';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display an inspiring quote';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);
}
}

30
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// Commands\Inspire::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
}

8
app/Events/Event.php Normal file
View File

@ -0,0 +1,8 @@
<?php
namespace App\Events;
abstract class Event
{
//
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
}

View File

@ -1,6 +1,4 @@
<?php
namespace factories;
<?php namespace Factories;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -13,15 +11,16 @@ namespace factories;
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
/**
* Class FactoriesProvider
*/
class FactoriesProvider extends ServiceProvider
final class FactoriesProvider extends ServiceProvider
{
protected $defer = false;
protected $defer = true;
public function boot()
{
@ -29,6 +28,11 @@ class FactoriesProvider extends ServiceProvider
public function register()
{
App::singleton('oauth2\factories\IOAuth2ClientFactory', 'factories\OAuth2ClientFactory');
App::singleton(\OAuth2\Factories\IOAuth2ClientFactory::class, \Factories\OAuth2ClientFactory::class);
}
public function provides()
{
return [\OAuth2\Factories\IOAuth2ClientFactory::class];
}
}

View File

@ -1,10 +1,4 @@
<?php
namespace factories;
use oauth2\factories\IOAuth2ClientFactory;
use oauth2\models\IClient;
use oauth2\OAuth2Protocol;
<?php namespace Factories;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -17,6 +11,16 @@ use oauth2\OAuth2Protocol;
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Factories\IOAuth2ClientFactory;
use OAuth2\Models\IClient;
use Models\OAuth2\Client;
use OAuth2\OAuth2Protocol;
/**
* Class OAuth2ClientFactory
* @package Factories
*/
final class OAuth2ClientFactory implements IOAuth2ClientFactory
{
@ -28,7 +32,7 @@ final class OAuth2ClientFactory implements IOAuth2ClientFactory
*/
public function build($app_name, $owner, $application_type)
{
$client = new \Client
$client = new Client
(
array
(

View File

@ -1,23 +1,48 @@
<?php
use oauth2\services\IApiScopeService;
use oauth2\services\IApiService;
use oauth2\services\IClientService;
use oauth2\services\ITokenService;
use oauth2\services\IResourceServerService;
use oauth2\services\IApiEndpointService;
use utils\services\IAuthService;
use openid\services\IUserService;
use utils\services\IServerConfigurationService;
use utils\services\IBannedIPService;
use oauth2\repositories\IServerPrivateKeyRepository;
use oauth2\repositories\IApiScopeGroupRepository;
use auth\User;
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Auth\Repositories\IUserRepository;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use OAuth2\Repositories\IAccessTokenRepository;
use OAuth2\Repositories\IApiEndpointRepository;
use OAuth2\Repositories\IApiRepository;
use OAuth2\Repositories\IApiScopeRepository;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Repositories\IRefreshTokenRepository;
use OAuth2\Repositories\IResourceServerRepository;
use OAuth2\Services\ITokenService;
use OAuth2\Repositories\IApiScopeGroupRepository;
use OAuth2\Repositories\IServerPrivateKeyRepository;
use OAuth2\Services\IApiEndpointService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Services\IApiService;
use OAuth2\Services\IClientService;
use OAuth2\Services\IResourceServerService;
use OpenId\Services\IUserService;
use Utils\Services\IAuthService;
use Utils\Services\IBannedIPService;
use Utils\Services\IServerConfigurationService;
use Illuminate\Support\Facades\Log;
/**
* Class AdminController
* @package App\Http\Controllers
*/
class AdminController extends BaseController {
class AdminController extends Controller {
/**
* @var IClientService
@ -27,10 +52,17 @@ class AdminController extends BaseController {
* @var IApiScopeService
*/
private $scope_service;
/**
* @var ITokenService
* @var IAccessTokenRepository
*/
private $token_service;
private $access_token_repository;
/**
* @var IRefreshTokenRepository
*/
private $refresh_token_repository;
/**
* @var IResourceServerService
*/
@ -60,6 +92,9 @@ class AdminController extends BaseController {
*/
private $banned_ips_service;
/**
* @var IServerPrivateKeyRepository
*/
private $private_keys_repository;
/**
@ -67,42 +102,90 @@ class AdminController extends BaseController {
*/
private $group_repository;
public function __construct( IClientService $client_service,
IApiScopeService $scope_service,
ITokenService $token_service,
IResourceServerService $resource_server_service,
IApiService $api_service,
IApiEndpointService $endpoint_service,
IAuthService $auth_service,
IUserService $user_service,
IServerConfigurationService $configuration_service,
IBannedIPService $banned_ips_service,
IServerPrivateKeyRepository $private_keys_repository,
IApiScopeGroupRepository $group_repository)
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IUserRepository
*/
private $user_repository;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiScopeRepository
*/
private $scope_repository;
/**
* @var IApiRepository
*/
private $api_repository;
/**
* @var IResourceServerRepository
*/
private $resource_server_repository;
const TokenPageSize = 25;
public function __construct(
IClientService $client_service,
IApiScopeService $scope_service,
IAccessTokenRepository $access_token_repository,
IRefreshTokenRepository $refresh_token_repository,
IResourceServerService $resource_server_service,
IApiService $api_service,
IApiEndpointService $endpoint_service,
IAuthService $auth_service,
IUserService $user_service,
IServerConfigurationService $configuration_service,
IBannedIPService $banned_ips_service,
IServerPrivateKeyRepository $private_keys_repository,
IApiScopeGroupRepository $group_repository,
IClientRepository $client_repository,
IUserRepository $user_repository,
IApiEndpointRepository $endpoint_repository,
IApiScopeRepository $scope_repository,
IApiRepository $api_repository,
IResourceServerRepository $resource_server_repository
)
{
$this->client_service = $client_service;
$this->scope_service = $scope_service;
$this->token_service = $token_service;
$this->resource_server_service = $resource_server_service;
$this->api_service = $api_service;
$this->endpoint_service = $endpoint_service;
$this->auth_service = $auth_service;
$this->user_service = $user_service;
$this->configuration_service = $configuration_service;
$this->banned_ips_service = $banned_ips_service;
$this->private_keys_repository = $private_keys_repository;
$this->group_repository = $group_repository;
$this->client_service = $client_service;
$this->scope_service = $scope_service;
$this->access_token_repository = $access_token_repository;
$this->refresh_token_repository = $refresh_token_repository;
$this->resource_server_service = $resource_server_service;
$this->api_service = $api_service;
$this->endpoint_service = $endpoint_service;
$this->auth_service = $auth_service;
$this->user_service = $user_service;
$this->configuration_service = $configuration_service;
$this->banned_ips_service = $banned_ips_service;
$this->private_keys_repository = $private_keys_repository;
$this->group_repository = $group_repository;
$this->client_repository = $client_repository;
$this->user_repository = $user_repository;
$this->endpoint_repository = $endpoint_repository;
$this->scope_repository = $scope_repository;
$this->api_repository = $api_repository;
$this->resource_server_repository = $resource_server_repository;
}
public function editRegisteredClient($id)
{
$user = $this->auth_service->getCurrentUser();
$client = $this->client_service->getClientByIdentifier($id);
$user = $this->auth_service->getCurrentUser();
$client = $this->client_repository->getClientByIdentifier($id);
if (is_null($client)) {
Log::warning(sprintf("invalid oauth2 client id %s", $id));
return View::make("404");
return View::make("errors.404");
}
$selected_scopes = $client->getClientScopes();
@ -115,31 +198,33 @@ class AdminController extends BaseController {
$scopes = $this->scope_service->getAvailableScopes();
$group_scopes = $user->getGroupScopes();
$access_tokens = $this->token_service->getAccessTokenByClient($client->client_id);
$access_tokens = $this->access_token_repository->getAllValidByClientIdentifier($client->getId(), 1 , self::TokenPageSize);
foreach ($access_tokens as $token) {
foreach ($access_tokens->items() as $token) {
$friendly_scopes = $this->scope_service->getFriendlyScopesByName(explode(' ', $token->scope));
$token->setFriendlyScopes(implode(',', $friendly_scopes));
}
$refresh_tokens = $this->token_service->getRefreshTokenByClient($client->client_id);
$refresh_tokens = $this->refresh_token_repository->getAllValidByClientIdentifier($client->getId(), 1 , self::TokenPageSize);
foreach ($refresh_tokens as $token) {
foreach ($refresh_tokens->items() as $token) {
$friendly_scopes = $this->scope_service->getFriendlyScopesByName(explode(' ', $token->scope));
$token->setFriendlyScopes(implode(',', $friendly_scopes));
}
return View::make("oauth2.profile.edit-client",
array(
[
'client' => $client,
'selected_scopes' => $aux_scopes,
'scopes' => array_merge($scopes, $group_scopes),
'access_tokens' => $access_tokens,
'access_tokens' => $access_tokens->items(),
'access_tokens_pages' => $access_tokens->total() > 0 ? intval(ceil($access_tokens->total() / self::TokenPageSize)) : 0,
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
"use_system_scopes" => $user->canUseSystemScopes(),
'refresh_tokens' => $refresh_tokens,
));
'refresh_tokens' => $refresh_tokens->items(),
'refresh_tokens_pages' => $refresh_tokens->total() > 0 ? intval(ceil($refresh_tokens->total() / self::TokenPageSize)) : 0,
]);
}
// Api Scope Groups
@ -147,7 +232,7 @@ class AdminController extends BaseController {
public function listApiScopeGroups()
{
$user = $this->auth_service->getCurrentUser();
$groups = $this->group_repository->getAll(1,1000);
$groups = $this->group_repository->getAll(1, PHP_INT_MAX);
$non_selected_scopes = $this->scope_service->getAssignedByGroups();
return View::make("oauth2.profile.admin.api-scope-groups",array
(
@ -162,7 +247,7 @@ class AdminController extends BaseController {
$group = $this->group_repository->get($id);
if(is_null($group))
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
$user = $this->auth_service->getCurrentUser();
$non_selected_scopes = $this->scope_service->getAssignedByGroups();
return View::make("oauth2.profile.admin.edit-api-scope-group",
@ -179,7 +264,7 @@ class AdminController extends BaseController {
// Resource servers
public function listResourceServers() {
$user = $this->auth_service->getCurrentUser();
$resource_servers = $this->resource_server_service->getAll(1,1000);
$resource_servers = $this->resource_server_repository->getAll(1, PHP_INT_MAX);
return View::make("oauth2.profile.admin.resource-servers",array(
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
@ -187,9 +272,9 @@ class AdminController extends BaseController {
}
public function editResourceServer($id){
$resource_server = $this->resource_server_service->get($id);
$resource_server = $this->resource_server_repository->get($id);
if(is_null($resource_server))
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.edit-resource-server",array(
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
@ -199,9 +284,9 @@ class AdminController extends BaseController {
}
public function editApi($id){
$api = $this->api_service->get($id);
$api = $this->api_repository->get($id);
if(is_null($api))
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.edit-api",array(
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
@ -210,9 +295,9 @@ class AdminController extends BaseController {
}
public function editScope($id){
$scope = $this->scope_service->get($id);
$scope = $this->scope_repository->get($id);
if(is_null($scope))
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.edit-scope",array(
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
@ -221,18 +306,17 @@ class AdminController extends BaseController {
}
public function editEndpoint($id){
$endpoint = $this->endpoint_service->get($id);
if(is_null($endpoint))
return Response::view('404', array(), 404);
$endpoint = $this->endpoint_repository->get($id);
if(is_null($endpoint)) return Response::view('errors.404', array(), 404);
$user = $this->auth_service->getCurrentUser();
$selected_scopes = array();
$list = $endpoint->scopes()->get(array('id'));
foreach($list as $selected_scope){
array_push($selected_scopes,$selected_scope->id);
}
return View::make("oauth2.profile.admin.edit-endpoint",array(
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
return View::make('oauth2.profile.admin.edit-endpoint',array(
'is_oauth2_admin' => $user->isOAuth2ServerAdmin(),
'is_openstackid_admin' => $user->isOpenstackIdAdmin(),
'endpoint' => $endpoint ,
'selected_scopes' => $selected_scopes));
}
@ -240,15 +324,15 @@ class AdminController extends BaseController {
public function editIssuedGrants(){
$user = $this->auth_service->getCurrentUser();
$access_tokens = $this->token_service->getAccessTokenByUserId($user->getId());
$refresh_tokens = $this->token_service->getRefreshTokenByUserId($user->getId());
$access_tokens = $this->access_token_repository->getAllValidByUserId($user->getId(), 1, self::TokenPageSize);
$refresh_tokens = $this->refresh_token_repository->getAllValidByUserId($user->getId(), 1, self::TokenPageSize);
foreach($access_tokens as $access_token){
foreach($access_tokens->items() as $access_token){
$friendly_scopes = $this->scope_service->getFriendlyScopesByName(explode(' ',$access_token->scope));
$access_token->setFriendlyScopes(implode(', ',$friendly_scopes));
}
foreach($refresh_tokens as $refresh_token){
foreach($refresh_tokens->items() as $refresh_token){
$friendly_scopes = $this->scope_service->getFriendlyScopesByName(explode(' ',$refresh_token->scope));
$refresh_token->setFriendlyScopes(implode(', ',$friendly_scopes));
}
@ -257,8 +341,10 @@ class AdminController extends BaseController {
array
(
'user_id' => $user->getId(),
'access_tokens' => $access_tokens ,
'refresh_tokens' => $refresh_tokens ,
'access_tokens' => $access_tokens->items() ,
'access_tokens_pages' => $access_tokens->total() > 0 ? intval(ceil($access_tokens->total() / self::TokenPageSize)) : 0,
'refresh_tokens' => $refresh_tokens->items(),
'refresh_tokens_pages' => $refresh_tokens->total() > 0 ? intval(ceil($refresh_tokens->total() / self::TokenPageSize)) : 0,
'is_oauth2_admin' => $user->isOAuth2ServerAdmin(),
'is_openstackid_admin' => $user->isOpenstackIdAdmin(),
)
@ -281,13 +367,13 @@ class AdminController extends BaseController {
public function listLockedClients(){
$user = $this->auth_service->getCurrentUser();
$clients = $this->client_service->getAll(1,1000,array(
array(
$clients = $this->client_repository->getAll(1, PHP_INT_MAX,[
[
'name'=>'locked',
'op' => '=',
'value'=> true
)
));
]
]);
return View::make("oauth2.profile.admin.clients", array(
"username" => $user->getFullName(),
@ -300,28 +386,28 @@ class AdminController extends BaseController {
public function listLockedUsers(){
$user = $this->auth_service->getCurrentUser();
$users = $this->user_service->getAll(1,1000,array(
array(
'name'=>'lock',
'op' => '=',
'value'=> true
)
));
$users = $this->user_repository->getAll(1, PHP_INT_MAX,[
[
'name' => 'lock',
'op' => '=',
'value' => true
]
]);
return View::make("admin.users", array(
"username" => $user->getFullName(),
"user_id" => $user->getId(),
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
'users' => $users,
));
return View::make('admin.users', [
'username' => $user->getFullName(),
'user_id' => $user->getId(),
'is_oauth2_admin' => $user->isOAuth2ServerAdmin(),
'is_openstackid_admin' => $user->isOpenstackIdAdmin(),
'users' => $users,
]);
}
public function listServerConfig(){
$user = $this->auth_service->getCurrentUser();
$user = $this->auth_service->getCurrentUser();
$config_values = array();
$dictionary = array
$dictionary = array
(
'MaxFailed.Login.Attempts',
'MaxFailed.LoginAttempts.2ShowCaptcha',
@ -422,14 +508,17 @@ class AdminController extends BaseController {
public function listBannedIPs(){
$user = $this->auth_service->getCurrentUser();
$ips = $this->banned_ips_service->getByPage(1,1000);
return View::make("admin.banned-ips", array(
"username" => $user->getFullName(),
"user_id" => $user->getId(),
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
"ips" =>$ips
));
$ips = $this->banned_ips_service->getByPage(1, PHP_INT_MAX);
return View::make("admin.banned-ips",
array
(
"username" => $user->getFullName(),
"user_id" => $user->getId(),
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
"ips" => $ips
)
);
}
public function listServerPrivateKeys(){
@ -437,7 +526,7 @@ class AdminController extends BaseController {
$user = $this->auth_service->getCurrentUser();
return View::make("oauth2.profile.admin.server-private-keys", array(
'private_keys' => $this->private_keys_repository->getAll(1,4294967296),
'private_keys' => $this->private_keys_repository->getAll(1, PHP_INT_MAX),
"is_oauth2_admin" => $user->isOAuth2ServerAdmin(),
"is_openstackid_admin" => $user->isOpenstackIdAdmin(),
));

View File

@ -1,9 +1,21 @@
<?php
use utils\services\ILogService;
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Services\ILogService;
/**
* Class AbstractRESTController
* @package App\Http\Controllers\Apis
*/
abstract class AbstractRESTController extends JsonController
{
@ -15,8 +27,10 @@ abstract class AbstractRESTController extends JsonController
protected $filter_delimiter;
protected $field_delimiter;
/**
* AbstractRESTController constructor.
* @param ILogService $log_service
*/
public function __construct(ILogService $log_service)
{
parent::__construct($log_service);
@ -46,7 +60,7 @@ abstract class AbstractRESTController extends JsonController
$res = array();
foreach($filters as $fieldname=>$value){
if(in_array($fieldname,$this->allowed_filter_fields)){
array_push($res,array('name'=>$fieldname,'op'=>'=','value'=>$value));
array_push($res,['name' => $fieldname, 'op' => '=','value' => $value]);
}
}
return $res;

View File

@ -1,10 +1,25 @@
<?php
use utils\services\IBannedIPService;
use utils\services\ILogService;
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Services\IBannedIPService;
use Utils\Services\ILogService;
use App\Http\Controllers\ICRUDController;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class ApiBannedIPController
* @package App\Http\Controllers\Api
*/
class ApiBannedIPController extends AbstractRESTController implements ICRUDController
{
@ -20,8 +35,8 @@ class ApiBannedIPController extends AbstractRESTController implements ICRUDContr
parent::__construct($log_service);
$this->banned_ip_service = $banned_ip_service;
$this->allowed_filter_fields = array();
$this->banned_ip_service = $banned_ip_service;
$this->allowed_filter_fields = array();
$this->allowed_projection_fields = array('*');
}
@ -56,9 +71,9 @@ class ApiBannedIPController extends AbstractRESTController implements ICRUDContr
{
try {
//check for optional filters param on querystring
$fields = $this->getProjection(Input::get('fields', null));
$filters = $this->getFilters(Input::except('fields', 'limit', 'offset'));
$page_nbr = intval(Input::get('offset', 1));
$fields = $this->getProjection(Input::get('fields', null));
$filters = $this->getFilters(Input::except('fields', 'limit', 'offset'));
$page_nbr = intval(Input::get('offset', 1));
$page_size = intval(Input::get('limit', 10));
$list = $this->banned_ip_service->getByPage($page_nbr, $page_size, $filters, $fields);
@ -67,7 +82,7 @@ class ApiBannedIPController extends AbstractRESTController implements ICRUDContr
array_push($items, $ip->toArray());
}
return $this->ok(array(
'page' => $items,
'page' => $items,
'total_items' => $list->getTotal()
));
} catch (Exception $ex) {
@ -83,7 +98,7 @@ class ApiBannedIPController extends AbstractRESTController implements ICRUDContr
$ip = Input::get("ip", null);
} else {
$banned_ip = $this->banned_ip_service->get($id);
$ip = $banned_ip->ip;
$ip = $banned_ip->ip;
}
if (is_null($ip))
return $this->error400('invalid request');

View File

@ -1,31 +1,67 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\services\ILogService;
use oauth2\services\IApiService;
use oauth2\exceptions\InvalidApi;
use OAuth2\Repositories\IApiRepository;
use Utils\Services\ILogService;
use OAuth2\Services\IApiService;
use OAuth2\Exceptions\InvalidApi;
use App\Http\Controllers\ICRUDController;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Exception;
/**
* Class ApiController
* REST controller for Api entity CRUD Ops
* @package App\Http\Controllers\Api
*/
class ApiController extends AbstractRESTController implements ICRUDController
{
/**
* @var IApiService
*/
private $api_service;
public function __construct(IApiService $api_service, ILogService $log_service)
/**
* @var IApiRepository
*/
private $api_repository;
/**
* ApiController constructor.
* @param IApiRepository $api_repository
* @param IApiService $api_service
* @param ILogService $log_service
*/
public function __construct
(
IApiRepository $api_repository,
IApiService $api_service,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->api_service = $api_service;
$this->api_repository = $api_repository;
$this->api_service = $api_service;
//set filters allowed values
$this->allowed_filter_fields = array('resource_server_id');
$this->allowed_projection_fields = array('*');
$this->allowed_filter_fields = ['resource_server_id'];
$this->allowed_projection_fields = ['*'];
}
public function get($id)
{
try {
$api = $this->api_service->get($id);
$api = $this->api_repository->get($id);
if(is_null($api)){
return $this->error404(array('error' => 'api not found'));
}
@ -45,20 +81,28 @@ class ApiController extends AbstractRESTController implements ICRUDController
{
try {
//check for optional filters param on querystring
$fields = $this->getProjection(Input::get('fields',null));
$filters = $this->getFilters(Input::except('fields','limit','offset'));
$page_nbr = intval(Input::get('offset',1));
$fields = $this->getProjection(Input::get('fields',null));
$filters = $this->getFilters(Input::except('fields','limit','offset'));
$page_nbr = intval(Input::get('offset',1));
$page_size = intval(Input::get('limit',10));
$list = $this->api_service->getAll($page_nbr,$page_size, $filters,$fields);
$items = array();
foreach ($list->getItems() as $api) {
$list = $this->api_repository->getAll($page_nbr,$page_size, $filters,$fields);
$items = array();
foreach ($list->items() as $api)
{
array_push($items, $api->toArray());
}
return $this->ok( array(
'page' => $items,
'total_items' => $list->getTotal()
));
} catch (Exception $ex) {
return $this->ok
(
array
(
'page' => $items,
'total_items' => $list->total()
)
);
}
catch (Exception $ex)
{
$this->log_service->error($ex);
return $this->error500($ex);
}
@ -134,9 +178,9 @@ class ApiController extends AbstractRESTController implements ICRUDController
return $this->error400(array('error'=>'validation','messages' => $messages));
}
$res = $this->api_service->update(intval($values['id']),$values);
$this->api_service->update(intval($values['id']),$values);
return $res?$this->ok():$this->error400(array('error'=>'operation failed'));
return $this->ok();
}
catch(InvalidApi $ex1){

View File

@ -1,9 +1,26 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\services\ILogService;
use oauth2\services\IApiEndpointService;
use oauth2\exceptions\InvalidApiEndpoint;
use oauth2\exceptions\InvalidApiScope;
use App\Http\Controllers\ICRUDController;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use OAuth2\Exceptions\InvalidApiEndpoint;
use OAuth2\Exceptions\InvalidApiScope;
use OAuth2\Repositories\IApiEndpointRepository;
use OAuth2\Services\IApiEndpointService;
use Utils\Services\ILogService;
/**
* Class ApiEndpointController
@ -11,12 +28,27 @@ use oauth2\exceptions\InvalidApiScope;
*/
class ApiEndpointController extends AbstractRESTController implements ICRUDController {
/**
* @var IApiEndpointService
*/
private $api_endpoint_service;
public function __construct(IApiEndpointService $api_endpoint_service, ILogService $log_service)
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
public function __construct
(
IApiEndpointService $api_endpoint_service,
IApiEndpointRepository $endpoint_repository,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->api_endpoint_service = $api_endpoint_service;
$this->endpoint_repository = $endpoint_repository;
//set filters allowed values
$this->allowed_filter_fields = array('api_id');
$this->allowed_projection_fields = array('*');
@ -43,20 +75,27 @@ class ApiEndpointController extends AbstractRESTController implements ICRUDContr
{
try {
//check for optional filters param on querystring
$fields = $this->getProjection(Input::get('fields',null));
$filters = $this->getFilters(Input::except('fields','limit','offset'));
$page_nbr = intval(Input::get('offset',1));
$fields = $this->getProjection(Input::get('fields',null));
$filters = $this->getFilters(Input::except('fields','limit','offset'));
$page_nbr = intval(Input::get('offset',1));
$page_size = intval(Input::get('limit',10));
$list = $this->api_endpoint_service->getAll($page_nbr, $page_size, $filters,$fields);
$items = array();
foreach ($list->getItems() as $api_endpoint) {
$list = $this->endpoint_repository->getAll($page_nbr, $page_size, $filters, $fields);
$items = array();
foreach ($list->items() as $api_endpoint) {
array_push($items, $api_endpoint->toArray());
}
return $this->ok( array(
'page' => $items,
'total_items' => $list->getTotal()
));
} catch (Exception $ex) {
return $this->ok
(
array
(
'page' => $items,
'total_items' => $list->total()
)
);
}
catch (Exception $ex)
{
$this->log_service->error($ex);
return $this->error500($ex);
}

View File

@ -1,11 +1,28 @@
<?php
use oauth2\exceptions\InvalidResourceServer;
use oauth2\services\IResourceServerService;
use utils\services\ILogService;
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Exceptions\InvalidResourceServer;
use OAuth2\Repositories\IResourceServerRepository;
use OAuth2\Services\IResourceServerService;
use Utils\Exceptions\EntityNotFoundException;
use Utils\Services\ILogService;
use App\Http\Controllers\ICRUDController;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
/**
* Class ApiResourceServerController
* @package App\Http\Controllers\Api
*/
class ApiResourceServerController extends AbstractRESTController implements ICRUDController
{
@ -14,27 +31,43 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
*/
private $resource_server_service;
public function __construct(IResourceServerService $resource_server_service, ILogService $log_service)
/**
* @var IResourceServerRepository
*/
private $repository;
/**
* ApiResourceServerController constructor.
* @param IResourceServerRepository $repository
* @param IResourceServerService $resource_server_service
* @param ILogService $log_service
*/
public function __construct
(
IResourceServerRepository $repository,
IResourceServerService $resource_server_service,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->resource_server_service = $resource_server_service;
$this->allowed_filter_fields = array('');
$this->allowed_projection_fields = array('*');
$this->repository = $repository;
$this->resource_server_service = $resource_server_service;
$this->allowed_filter_fields = [''];
$this->allowed_projection_fields = ['*'];
}
public function get($id)
{
try {
$resource_server = $this->resource_server_service->get($id);
$resource_server = $this->repository->get($id);
if (is_null($resource_server)) {
return $this->error404(array('error' => 'resource server not found'));
}
$data = $resource_server->toArray();
$apis = $resource_server->apis()->get(array('id', 'name'));
$data = $resource_server->toArray();
$apis = $resource_server->apis()->get(array('id', 'name'));
$data['apis'] = $apis->toArray();
$client = $resource_server->getClient();
$client = $resource_server->getClient();
if (!is_null($client)) {
$data['client_id'] = $client->getClientId();
@ -42,9 +75,9 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
}
return $this->ok($data);
} catch (Exception $ex) {
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
@ -52,24 +85,25 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
public function getByPage()
{
try {
$fields = $this->getProjection(Input::get('fields', null));
$filters = $this->getFilters(Input::except('fields', 'limit', 'offset'));
$page_nbr = intval(Input::get('offset', 1));
$fields = $this->getProjection(Input::get('fields', null));
$filters = $this->getFilters(Input::except('fields', 'limit', 'offset'));
$page_nbr = intval(Input::get('offset', 1));
$page_size = intval(Input::get('limit', 10));
$list = $this->resource_server_service->getAll($page_nbr, $page_size, $filters, $fields);
$items = array();
foreach ($list->getItems() as $rs) {
array_push($items, $rs->toArray());
$paginator = $this->repository->getAll($page_nbr, $page_size, $filters, $fields);
$items = [];
foreach ($paginator->items() as $rs) {
$items[] = $rs->toArray();
}
return $this->ok(array(
'page' => $items,
'total_items' => $list->getTotal()
));
} catch (Exception $ex) {
return $this->ok([
'page' => $items,
'total_items' => $paginator->total()
]);
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
@ -115,12 +149,15 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
public function delete($id)
{
try {
$res = $this->resource_server_service->delete($id);
return $res ? $this->deleted() : $this->error404(array('error' => 'operation failed'));
} catch (Exception $ex) {
$this->resource_server_service->delete($id);
return $this->deleted();
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404(['message' => $ex1->getMessage()]);
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
@ -131,9 +168,13 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
$res = $this->resource_server_service->regenerateClientSecret($id);
return !is_null($res) ? $this->ok(array('new_secret' => $res)) : $this->error404(array('error' => 'operation failed'));
} catch (Exception $ex) {
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404(['message' => $ex1->getMessage()]);
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
@ -159,14 +200,18 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
}
$res = $this->resource_server_service->update(intval($values['id']), $values);
return $res ? $this->ok() : $this->error400(array('error' => 'operation failed'));
} catch (InvalidResourceServer $ex1) {
return $this->ok();
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404(['message' => $ex1->getMessage()]);
}
catch (InvalidResourceServer $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
return $this->error404(array('message' => $ex1->getMessage()));
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
@ -174,12 +219,15 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
public function activate($id)
{
try {
$res = $this->resource_server_service->setStatus($id, true);
return $res ? $this->ok() : $this->error400(array('error' => 'operation failed'));
} catch (Exception $ex) {
$this->resource_server_service->setStatus($id, true);
return $this->ok();
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404(['message' => $ex1->getMessage()]);
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
@ -187,12 +235,16 @@ class ApiResourceServerController extends AbstractRESTController implements ICRU
public function deactivate($id)
{
try {
$res = $this->resource_server_service->setStatus($id, false);
$this->resource_server_service->setStatus($id, false);
return $res ? $this->ok() : $this->error400(array('error' => 'operation failed'));
} catch (Exception $ex) {
return $this->ok();
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404(['message' => $ex1->getMessage()]);
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}

View File

@ -1,9 +1,26 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\services\ILogService;
use oauth2\services\IApiScopeService;
use oauth2\exceptions\InvalidApi;
use oauth2\exceptions\InvalidApiScope;
use OAuth2\Repositories\IApiScopeRepository;
use Utils\Services\ILogService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Exceptions\InvalidApi;
use OAuth2\Exceptions\InvalidApiScope;
use App\Http\Controllers\ICRUDController;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
/**
* Class ApiScopeController
@ -15,9 +32,20 @@ class ApiScopeController extends AbstractRESTController implements ICRUDControll
*/
private $api_scope_service;
public function __construct(IApiScopeService $api_scope_service, ILogService $log_service)
/**
* @var IApiScopeRepository
*/
private $scope_repository;
public function __construct
(
IApiScopeRepository $scope_repository,
IApiScopeService $api_scope_service,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->scope_repository = $scope_repository;
$this->api_scope_service = $api_scope_service;
//set filters allowed values
$this->allowed_filter_fields = array('api_id');
@ -27,7 +55,7 @@ class ApiScopeController extends AbstractRESTController implements ICRUDControll
public function get($id)
{
try {
$scope = $this->api_scope_service->get($id);
$scope = $this->scope_repository->get($id);
if(is_null($scope)){
return $this->error404(array('error' => 'scope not found'));
}
@ -43,20 +71,27 @@ class ApiScopeController extends AbstractRESTController implements ICRUDControll
{
try {
//check for optional filters param on querystring
$fields = $this->getProjection(Input::get('fields',null));
$filters = $this->getFilters(Input::except('fields','limit','offset'));
$page_nbr = intval(Input::get('offset',1));
$fields = $this->getProjection(Input::get('fields',null));
$filters = $this->getFilters(Input::except('fields','limit','offset'));
$page_nbr = intval(Input::get('offset',1));
$page_size = intval(Input::get('limit',10));
$list = $this->api_scope_service->getAll($page_nbr, $page_size, $filters,$fields);
$list = $this->scope_repository->getAll($page_nbr, $page_size, $filters,$fields);
$items = array();
foreach ($list->getItems() as $scope) {
foreach ($list->items() as $scope)
{
array_push($items, $scope->toArray());
}
return $this->ok( array(
'page' => $items,
'total_items' => $list->getTotal()
));
return $this->ok
(
array
(
'page' => $items,
'total_items' => $list->total()
)
);
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
@ -13,16 +13,20 @@
* limitations under the License.
**/
use utils\services\ILogService;
use oauth2\repositories\IApiScopeGroupRepository;
use oauth2\exceptions\InvalidApiScopeGroup;
use oauth2\services\IApiScopeGroupService;
use auth\IUserRepository;
use oauth2\services\IApiScopeService;
use utils\exceptions\EntityNotFoundException;
use App\Http\Controllers\ICRUDController;
use Auth\Repositories\IUserRepository;
use OAuth2\Exceptions\InvalidApiScopeGroup;
use OAuth2\Repositories\IApiScopeGroupRepository;
use OAuth2\Services\IApiScopeGroupService;
use OAuth2\Services\IApiScopeService;
use Utils\Services\ILogService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class ApiScopeGroupController
* @package App\Http\Controllers
*/
final class ApiScopeGroupController extends AbstractRESTController implements ICRUDController
{
@ -143,7 +147,7 @@ final class ApiScopeGroupController extends AbstractRESTController implements IC
$list = $this->repository->getAll($page_nbr, $page_size, $filters, $fields);
$items = array();
foreach ($list->getItems() as $g)
foreach ($list->items() as $g)
{
array_push($items, $g->toArray());
}
@ -152,7 +156,7 @@ final class ApiScopeGroupController extends AbstractRESTController implements IC
array
(
'page' => $items,
'total_items' => $list->getTotal()
'total_items' => $list->total()
)
);
} catch (Exception $ex) {

View File

@ -1,5 +1,4 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,30 +11,34 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use oauth2\services\IAssymetricKeyService;
use utils\services\ILogService;
use oauth2\repositories\IAssymetricKeyRepository;
use OAuth2\Services\IAsymmetricKeyService;
use Utils\Exceptions\EntityNotFoundException;
use Utils\Services\ILogService;
use OAuth2\Repositories\IAsymmetricKeyRepository;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Exception;
class AssymetricKeyApiController extends AbstractRESTController
class AsymmetricKeyApiController extends AbstractRESTController
{
/**
* @var IAssymetricKeyService
* @var IAsymmetricKeyService
*/
protected $service;
/**
* @var IAssymetricKeyRepository
* @var IAsymmetricKeyRepository
*/
protected $repository;
/**
* @param IAssymetricKeyRepository $repository
* @param IAssymetricKeyService $service
* @param IAsymmetricKeyRepository $repository
* @param IAsymmetricKeyService $service
* @param ILogService $log_service
*/
public function __construct(
IAssymetricKeyRepository $repository,
IAssymetricKeyService $service,
IAsymmetricKeyRepository $repository,
IAsymmetricKeyService $service,
ILogService $log_service
) {
parent::__construct($log_service);
@ -83,11 +86,11 @@ class AssymetricKeyApiController extends AbstractRESTController
return $this->error400(array('error' => 'validation', 'messages' => $messages));
}
$res = $this->service->update(intval($id), $values);
$this->service->update(intval($id), $values);
return $res ? $this->ok() : $this->error400(array('error' => 'operation failed'));
return $this->ok();
} catch (AbsentClientException $ex1) {
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
@ -111,16 +114,20 @@ class AssymetricKeyApiController extends AbstractRESTController
$list = $this->repository->getAll($page_nbr, $page_size, $filters, $fields);
$items = array();
foreach ($list->getItems() as $private_key) {
foreach ($list->items() as $private_key) {
$data = $private_key->toArray();
$data['sha_256'] = $private_key->getSHA_256_Thumbprint();
array_push($items, $data);
}
return $this->ok(array(
'page' => $items,
'total_items' => $list->getTotal()
));
return $this->ok
(
array
(
'page' => $items,
'total_items' => $list->total()
)
);
} catch (Exception $ex) {
$this->log_service->error($ex);

View File

@ -0,0 +1,754 @@
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\ICRUDController;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use OAuth2\Exceptions\ExpiredAccessTokenException;
use OAuth2\Exceptions\InvalidApiScope;
use OAuth2\Repositories\IAccessTokenRepository;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Repositories\IRefreshTokenRepository;
use OAuth2\Services\ITokenService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Services\IClientService;
use Utils\Exceptions\EntityNotFoundException;
use Utils\Services\IAuthService;
use Utils\Services\ILogService;
use Services\Exceptions\ValidationException;
use Illuminate\Support\Facades\Log;
/**
* Class ClientApiController
* @package App\Http\Controllers\Api
*/
final class ClientApiController extends AbstractRESTController implements ICRUDController
{
/**
* @var IClientService
*/
private $client_service;
/**
* @var IApiScopeService
*/
private $scope_service;
/**
* @var ITokenService
*/
private $token_service;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IAccessTokenRepository
*/
private $access_token_repository;
/**
* @var IRefreshTokenRepository
*/
private $refresh_token_repository;
/**
* ClientApiController constructor.
* @param IApiScopeService $scope_service
* @param ITokenService $token_service
* @param IClientService $client_service
* @param IAuthService $auth_service
* @param ILogService $log_service
* @param IClientRepository $client_repository
* @param IAccessTokenRepository $access_token_repository
* @param IRefreshTokenRepository $refresh_token_repository
*/
public function __construct
(
IApiScopeService $scope_service,
ITokenService $token_service,
IClientService $client_service,
IAuthService $auth_service,
ILogService $log_service,
IClientRepository $client_repository,
IAccessTokenRepository $access_token_repository,
IRefreshTokenRepository $refresh_token_repository
)
{
parent::__construct($log_service);
$this->client_service = $client_service;
$this->scope_service = $scope_service;
$this->token_service = $token_service;
$this->auth_service = $auth_service;
$this->access_token_repository = $access_token_repository;
$this->refresh_token_repository = $refresh_token_repository;
$this->client_repository = $client_repository;
//set filters allowed values
$this->allowed_filter_fields = ['user_id'];
$this->allowed_projection_fields = ['*'];
}
public function get($id)
{
try {
$client = $this->client_repository->getClientByIdentifier($id);
if (is_null($client))
{
return $this->error404(array('error' => 'client not found'));
}
return $this->ok($client->toArray());
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* Deletes an existing client
* @param $id
* @return mixed
*/
public function delete($id)
{
try {
$res = $this->client_service->deleteClientByIdentifier($id);
return $res ? $this->deleted() : $this->error404(array('error' => 'operation failed'));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* Creates an existing client
* @return mixed
*/
public function create()
{
try
{
$values = Input::All();
// Build the validation constraint set.
$rules = array
(
'app_name' => 'required|freetext|max:255',
'app_description' => 'required|freetext|max:512',
'application_type' => 'required|applicationtype',
'website' => 'sometimes|required|url',
'admin_users' => 'sometimes|required|user_ids',
);
// Create a new validator instance.
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412(array('error' => 'validation', 'messages' => $messages));
}
$admin_users = isset($values['admin_users']) ? trim($values['admin_users']): null;
$admin_users = empty($admin_users) ? array() : explode(',',$admin_users);
$website = isset($values['website']) ? trim($values['website']): null;
$new_client = $this->client_service->register
(
$values['application_type'],
trim($values['app_name']),
trim($values['app_description']),
$website,
$admin_users
);
return $this->created
(
array
(
'id' => $new_client->id,
'client_id' => $new_client->client_id,
'client_secret' => $new_client->client_secret,
)
);
}
catch(ValidationException $ex2)
{
$this->log_service->error($ex2);
return $this->error412(array($ex2->getMessage()));
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function update()
{
try {
$values = Input::all();
$rules = array(
'id' => 'required|integer',
//'application_type' => 'required|application_type',
'app_name' => 'sometimes|required|freetext|max:255',
'app_description' => 'sometimes|required|freetext|max:512',
'website' => 'sometimes|required|url',
'active' => 'sometimes|required|boolean',
'locked' => 'sometimes|required|boolean',
'use_refresh_token' => 'sometimes|required|boolean',
'rotate_refresh_token' => 'sometimes|required|boolean',
'contacts' => 'sometimes|required|email_set',
'logo_uri' => 'sometimes|required|url',
'tos_uri' => 'sometimes|required|url',
'redirect_uris' => 'sometimes|required|custom_url_set:application_type',
'post_logout_redirect_uris' => 'sometimes|required|ssl_url_set',
'allowed_origins' => 'sometimes|required|ssl_url_set',
'logout_uri' => 'sometimes|required|url',
'logout_session_required' => 'sometimes|required|boolean',
'logout_use_iframe' => 'sometimes|required|boolean',
'policy_uri' => 'sometimes|required|url',
'jwks_uri' => 'sometimes|required|url',
'default_max_age' => 'sometimes|required|integer',
'logout_use_iframe' => 'sometimes|required|boolean',
'require_auth_time' => 'sometimes|required|boolean',
'token_endpoint_auth_method' => 'sometimes|required|token_endpoint_auth_method',
'token_endpoint_auth_signing_alg' => 'sometimes|required|signing_alg',
'subject_type' => 'sometimes|required|subject_type',
'userinfo_signed_response_alg' => 'sometimes|required|signing_alg',
'userinfo_encrypted_response_alg' => 'sometimes|required|encrypted_alg',
'userinfo_encrypted_response_enc' => 'sometimes|required|encrypted_enc',
'id_token_signed_response_alg' => 'sometimes|required|signing_alg',
'id_token_encrypted_response_alg' => 'sometimes|required|encrypted_alg',
'id_token_encrypted_response_enc' => 'sometimes|required|encrypted_enc',
'admin_users' => 'sometimes|required|user_ids',
);
// Creates a Validator instance and validates the data.
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412(array('error' => 'validation', 'messages' => $messages));
}
$this->client_service->update(intval($values['id']), $values);
return $this->ok();
}
catch (EntityNotFoundException $ex1)
{
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
}
catch(ValidationException $ex2)
{
$this->log_service->error($ex2);
return $this->error412(array($ex2->getMessage()));
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getByPage()
{
try {
$items = array();
$user = $this->auth_service->getCurrentUser();
if(is_null($user)) return $this->error403();
$clients = $user->getClients();
foreach ($clients as $client)
{
$data = $client->toArray();
$data['application_type'] = $client->getFriendlyApplicationType();
$data['is_own'] = $client->isOwner($this->auth_service->getCurrentUser());
$data['modified_by'] = $client->getEditedByNice();
array_push($items, $data);
}
return $this->ok
(
array
(
'page' => $items,
'total_items' => count($items)
)
);
}
catch (Exception $ex)
{
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $scope_id
* @return mixed
*/
public function addAllowedScope($id, $scope_id)
{
try
{
$this->client_service->addClientScope($id, $scope_id);
return $this->ok();
}
catch (EntityNotFoundException $ex1)
{
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
}
catch (InvalidApiScope $ex2)
{
$this->log_service->error($ex2);
return $this->error412(array('messages' => $ex2->getMessage()));
}
catch (Exception $ex)
{
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $scope_id
* @return mixed
*/
public function removeAllowedScope($id, $scope_id)
{
try
{
$this->client_service->deleteClientScope($id, $scope_id);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function activate($id)
{
try {
$this->client_service->activateClient($id, true);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function deactivate($id)
{
try {
$this->client_service->activateClient($id, false);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function regenerateClientSecret($id)
{
try
{
$client = $this->client_service->regenerateClientSecret($id);
return !is_null($client) ?
$this->ok
(
array
(
'new_secret' => $client->getClientSecret(),
'new_expiration_date' => $client->getClientSecretExpiration(),
)
) : $this->error404(array('error' => 'operation failed'));
}
catch (Exception $ex)
{
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function setRefreshTokenClient($id)
{
try {
$values = Input::All();
// Build the validation constraint set.
$rules = array(
'use_refresh_token' => 'required|boolean'
);
// 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));
}
$this->client_service->setRefreshTokenUsage($id, $values['use_refresh_token']);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function setRotateRefreshTokenPolicy($id)
{
try {
$values = Input::All();
// Build the validation constraint set.
$rules = array(
'rotate_refresh_token' => 'required|boolean'
);
// 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));
}
$this->client_service->setRotateRefreshTokenPolicy($id, $values['rotate_refresh_token']);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @param $value
* @param $hint
* @return mixed
*/
public function revokeToken($id, $value, $hint)
{
try {
$res = false;
$client = $this->client_repository->getClientByIdentifier($id);
switch ($hint) {
case 'access-token': {
$token = $this->token_service->getAccessToken($value, true);
if (is_null($token)) {
return $this->error404(array('error' => sprintf('access token %s does not exists!', $value)));
}
Log::debug(sprintf('access token client id %s - client id %s ',$token->getClientId() , $client->client_id));
if ($token->getClientId() !== $client->client_id) {
return $this->error412(array(
'error' => sprintf('access token %s does not belongs to client id !', $value, $id)
));
}
$res = $this->token_service->revokeAccessToken($value, true);
}
break;
case 'refresh-token': {
$token = $this->token_service->getRefreshToken($value, true);
if (is_null($token)) {
return $this->error404(array('error' => sprintf('refresh token %s does not exists!', $value)));
}
Log::debug(sprintf('refresh token client id %s - client id %s ',$token->getClientId() , $client->client_id));
if ($token->getClientId() !== $client->client_id) {
return $this->error412(array(
'error' => sprintf('refresh token %s does not belongs to client id !', $value, $id)
));
}
$res = $this->token_service->revokeRefreshToken($value, true);
}
break;
default:
break;
}
return $res ? $this->ok() : $this->error404(array('error' => 'operation failed'));
}
catch(ExpiredAccessTokenException $ex1){
$this->log_service->warning($ex1);
return $this->error404();
}
catch(Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function getAccessTokens($id)
{
try {
$page_nbr = intval(Input::get('offset', 1));
$page_size = intval(Input::get('limit', 10));
$client = $this->client_repository->getClientByIdentifier($id);
if(is_null($client))
throw new EntityNotFoundException();
$paginator = $this->access_token_repository->getAllValidByClientIdentifier($id, $page_nbr, $page_size);
$res = [];
foreach ($paginator->items() as $token) {
$res[] = [
'value' => $token->value,
'scope' => $token->scope,
'lifetime' => $token->getRemainingLifetime(),
'issued' => $token->created_at->format('Y-m-d H:i:s')
];
}
return $this->ok([
'total' => $paginator->total(),
'pages' => $paginator->total() > 0 ? ceil($paginator->total()/$page_size) : 0,
'items' => $res
]);
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404();
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function getRefreshTokens($id)
{
try {
$page_nbr = intval(Input::get('offset', 1));
$page_size = intval(Input::get('limit', 10));
$client = $this->client_repository->getClientByIdentifier($id);
if(is_null($client))
throw new EntityNotFoundException();
$paginator = $this->refresh_token_repository->getAllValidByClientIdentifier($id, $page_nbr, $page_size);
$res = [];
foreach ($paginator->items() as $token) {
$res[] = [
'value' => $token->value,
'scope' => $token->scope,
'lifetime' => $token->getRemainingLifetime(),
'issued' => $token->created_at->format('Y-m-d H:i:s')
];
}
return $this->ok([
'total' => $paginator->total(),
'pages' => $paginator->total() > 0 ? ceil($paginator->total()/$page_size) : 0,
'items' => $res
]);
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404();
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getAccessTokensByCurrentUser()
{
try {
$user = $this->auth_service->getCurrentUser();
$page_nbr = intval(Input::get('offset', 1));
$page_size = intval(Input::get('limit', 10));
$paginator = $this->access_token_repository->getAllValidByUserId($user->getId(), $page_nbr, $page_size);
$res = [];
foreach ($paginator->items() as $token) {
$res[] = [
'value' => $token->value,
'scope' => $token->scope,
'lifetime' => $token->getRemainingLifetime(),
'issued' => $token->created_at->format('Y-m-d H:i:s')
];
}
return $this->ok([
'total' => $paginator->total(),
'pages' => $paginator->total() > 0 ? ceil($paginator->total()/$page_size) : 0,
'items' => $res
]);
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404();
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getRefreshTokensByCurrentUser()
{
try {
$user = $this->auth_service->getCurrentUser();
$page_nbr = intval(Input::get('offset', 1));
$page_size = intval(Input::get('limit', 10));
$paginator = $this->refresh_token_repository->getAllValidByUserId($user->getId(), $page_nbr, $page_size);
$res = [];
foreach ($paginator->items() as $token) {
$res[] = [
'value' => $token->value,
'scope' => $token->scope,
'lifetime' => $token->getRemainingLifetime(),
'issued' => $token->created_at->format('Y-m-d H:i:s')
];
}
return $this->ok([
'total' => $paginator->total(),
'pages' => $paginator->total() > 0 ? ceil($paginator->total()/$page_size) : 0,
'items' => $res
]);
}
catch (EntityNotFoundException $ex1) {
$this->log_service->warning($ex1);
return $this->error404();
}
catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return mixed
*/
public function unlock($id)
{
try {
$this->client_service->unlockClient($id);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
} catch (Exception $ex) {
$this->log_service->error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,33 +1,40 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use oauth2\services\IClienPublicKeyService;
use utils\services\ILogService;
use oauth2\repositories\IClientPublicKeyRepository;
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Services\IClientPublicKeyService;
use Utils\Services\ILogService;
use OAuth2\Repositories\IClientPublicKeyRepository;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Services\Exceptions\ValidationException;
/**
* Class ClientPublicKeyApiController
* @package App\Http\Controllers\Api
*/
final class ClientPublicKeyApiController extends AssymetricKeyApiController
final class ClientPublicKeyApiController extends AsymmetricKeyApiController
{
/**
* @param IClientPublicKeyRepository $repository
* @param IClienPublicKeyService $service
* @param IClientPublicKeyService $service
* @param ILogService $log_service
*/
public function __construct
(
IClientPublicKeyRepository $repository,
IClienPublicKeyService $service,
IClientPublicKeyService $service,
ILogService $log_service
)
{
@ -60,8 +67,8 @@ final class ClientPublicKeyApiController extends AssymetricKeyApiController
'client_id' => 'required|integer',
'kid' => 'required|text|max:255',
'active' => 'required|boolean',
'valid_from' => 'date_format:m/d/Y',
'valid_to' => 'date_format:m/d/Y|after:valid_from',
'valid_from' => 'required|date_format:m/d/Y',
'valid_to' => 'required|date_format:m/d/Y|after:valid_from',
'pem_content' => 'required|public_key_pem|public_key_pem_length',
'usage' => 'required|public_key_usage',
'type' => 'required|public_key_type',
@ -115,7 +122,7 @@ final class ClientPublicKeyApiController extends AssymetricKeyApiController
);
$list = $this->repository->getAll($page_nbr, $page_size, $filters, $fields);
$items = array();
foreach ($list->getItems() as $private_key) {
foreach ($list->items() as $private_key) {
$data = $private_key->toArray();
$data['sha_256'] = $private_key->getSHA_256_Thumbprint();
array_push($items, $data);
@ -123,7 +130,7 @@ final class ClientPublicKeyApiController extends AssymetricKeyApiController
return $this->ok(array(
'page' => $items,
'total_items' => $list->getTotal()
'total_items' => $list->total()
));
} catch (Exception $ex) {
$this->log_service->error($ex);

View File

@ -1,7 +1,7 @@
<?php
<?php namespace App\Http\Controllers;
/**
* Interface ICRUDController
* @package App\Http\Controllers
*/
interface ICRUDController {

View File

@ -1,11 +1,27 @@
<?php
use utils\services\ILogService;
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use Utils\Services\ILogService;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class JsonController
* @package App\Http\Controllers
*/
abstract class JsonController extends BaseController {
abstract class JsonController extends Controller {
protected $log_service;
@ -60,6 +76,11 @@ abstract class JsonController extends BaseController {
return Response::json($data, 404);
}
protected function error403($data = array('message' => 'Forbidden'))
{
return Response::json($data, 403);
}
/**
* {
"message": "Validation Failed",

View File

@ -0,0 +1,50 @@
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\IResourceServerContext;
use Utils\Services\ILogService;
use App\Http\Controllers\Api\JsonController;
/**
* Class OAuth2ProtectedController
* @package App\Http\Controllers\Api\OAuth2
*/
abstract class OAuth2ProtectedController extends JsonController
{
/**
* @var IResourceServerContext
*/
protected $resource_server_context;
/**
* @var
*/
protected $repository;
/**
* OAuth2ProtectedController constructor.
* @param IResourceServerContext $resource_server_context
* @param ILogService $log_service
*/
public function __construct
(
IResourceServerContext $resource_server_context,
ILogService $log_service
)
{
parent::__construct($log_service);
$this->resource_server_context = $resource_server_context;
}
}

View File

@ -1,17 +1,28 @@
<?php
use oauth2\IResourceServerContext;
use utils\services\ILogService;
use oauth2\resource_server\IUserService;
use oauth2\services\IClientService;
use oauth2\heuristics\SigningKeyFinder;
use oauth2\heuristics\EncryptionKeyFinder;
use oauth2\builders\IdTokenBuilder;
use utils\http\HttpContentType;
<?php namespace App\Http\Controllers\Api\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Response;
use OAuth2\Builders\IdTokenBuilder;
use OAuth2\IResourceServerContext;
use OAuth2\Repositories\IClientRepository;
use OAuth2\ResourceServer\IUserService;
use OAuth2\Services\IClientService;
use Utils\Http\HttpContentType;
use Utils\Services\ILogService;
/**
* Class OAuth2UserApiController
* OAUTH2 Protected User REST API
* @package App\Http\Controllers\Api\OAuth2
*/
class OAuth2UserApiController extends OAuth2ProtectedController
{
@ -21,9 +32,9 @@ class OAuth2UserApiController extends OAuth2ProtectedController
private $user_service;
/**
* @var IClientService
* @var IClientRepository
*/
private $client_service;
private $client_repository;
/**
* @var IdTokenBuilder
@ -34,7 +45,7 @@ class OAuth2UserApiController extends OAuth2ProtectedController
* @param IUserService $user_service
* @param IResourceServerContext $resource_server_context
* @param ILogService $log_service
* @param IClientService $client_service
* @param IClientRepository $client_repository
* @param IdTokenBuilder $id_token_builder
*/
public function __construct
@ -42,15 +53,15 @@ class OAuth2UserApiController extends OAuth2ProtectedController
IUserService $user_service,
IResourceServerContext $resource_server_context,
ILogService $log_service,
IClientService $client_service,
IClientRepository $client_repository,
IdTokenBuilder $id_token_builder
)
{
parent::__construct($resource_server_context,$log_service);
$this->user_service = $user_service;
$this->client_service = $client_service;
$this->id_token_builder = $id_token_builder;
$this->user_service = $user_service;
$this->client_repository = $client_repository;
$this->id_token_builder = $id_token_builder;
}
/**
@ -77,7 +88,7 @@ class OAuth2UserApiController extends OAuth2ProtectedController
{
$claims = $this->user_service->getCurrentUserInfoClaims();
$client_id = $this->resource_server_context->getCurrentClientId();
$client = $this->client_service->getClientById($client_id);
$client = $this->client_repository->getClientById($client_id);
// The UserInfo Claims MUST be returned as the members of a JSON object unless a signed or encrypted response
// was requested during Client Registration.

View File

@ -1,5 +1,4 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -13,13 +12,19 @@
* limitations under the License.
**/
use oauth2\services\IServerPrivateKeyService;
use oauth2\repositories\IServerPrivateKeyRepository;
use utils\services\ILogService;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use OAuth2\Repositories\IServerPrivateKeyRepository;
use OAuth2\Services\IServerPrivateKeyService;
use Services\Exceptions\ValidationException;
use Utils\Services\ILogService;
/**
* Class ServerPrivateKeyApiController
* @package App\Http\Controllers\Api
*/
final class ServerPrivateKeyApiController extends AssymetricKeyApiController
final class ServerPrivateKeyApiController extends AsymmetricKeyApiController
{
/**
* @param IServerPrivateKeyRepository $repository

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers\Api;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,13 +12,19 @@
* limitations under the License.
**/
use utils\services\ILogService;
use openid\services\IUserService;
use oauth2\services\ITokenService;
use oauth2\exceptions\ExpiredAccessTokenException;
use auth\IUserRepository;
use App\Http\Controllers\ICRUDController;
use Auth\Repositories\IUserRepository;
use Exception;
use Illuminate\Support\Facades\Input;
use OAuth2\Exceptions\ExpiredAccessTokenException;
use OAuth2\Services\ITokenService;
use OpenId\Services\IUserService;
use Utils\Exceptions\EntityNotFoundException;
use Utils\Services\ILogService;
/**
* Class UserApiController
* @package App\Http\Controllers\Api
*/
class UserApiController extends AbstractRESTController implements ICRUDController {
@ -36,6 +42,13 @@ class UserApiController extends AbstractRESTController implements ICRUDControlle
*/
private $user_repository;
/**
* UserApiController constructor.
* @param IUserRepository $user_repository
* @param ILogService $log_service
* @param IUserService $user_service
* @param ITokenService $token_service
*/
public function __construct
(
IUserRepository $user_repository,
@ -59,7 +72,7 @@ class UserApiController extends AbstractRESTController implements ICRUDControlle
$this->user_service->unlockUser($id);
return $this->updated();
}
catch (AbsentClientException $ex1) {
catch (EntityNotFoundException $ex1) {
$this->log_service->error($ex1);
return $this->error404(array('error' => $ex1->getMessage()));
}
@ -117,7 +130,7 @@ class UserApiController extends AbstractRESTController implements ICRUDControlle
public function get($id)
{
try {
$user = $this->user_service->get($id);
$user = $this->user_repository->get($id);
if(is_null($user)){
return $this->error404(array('error' => 'user not found'));
}
@ -153,11 +166,14 @@ class UserApiController extends AbstractRESTController implements ICRUDControlle
{
$values = Input::all();
if(!isset($values['t'])) return $this->error404();
$term = $values['t'];
$users = $this->user_repository->getByEmailOrName($term);
$list = array();
if(count($users) > 0)
{
$list = array();
foreach($users as $u)
{
array_push($list, array
@ -167,8 +183,8 @@ class UserApiController extends AbstractRESTController implements ICRUDControlle
)
);
}
return $this->ok($list);
}
return $this->updated();
return $this->ok($list);
}
}

View File

@ -0,0 +1,27 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
/**
* Class Controller
* @package App\Http\Controllers
*/
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
}

View File

@ -0,0 +1,48 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use App\Http\Controllers\OpenId\OpenIdController;
use App\Http\Controllers\OpenId\DiscoveryController;
/**
* Class HomeController
* @package App\Http\Controllers
*/
class HomeController extends OpenIdController
{
private $discovery;
public function __construct(DiscoveryController $discovery)
{
$this->discovery = $discovery;
}
public function index()
{
if ($this->isDiscoveryRequest())
return $this->discovery->idp();
if (Auth::guest()) {
Session::flush();
Session::regenerate();
return View::make("home");
}
else
return Redirect::action("UserController@getProfile");
}
}

View File

@ -1,24 +1,43 @@
<?php
<?php namespace App\Http\Controllers\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use OAuth2\Exceptions\UriNotAllowedException;
use OAuth2\Factories\OAuth2AuthorizationRequestFactory;
use OAuth2\IOAuth2Protocol;
use OAuth2\OAuth2Message;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Requests\OAuth2AccessTokenValidationRequest;
use OAuth2\Requests\OAuth2LogoutRequest;
use OAuth2\Requests\OAuth2TokenRequest;
use OAuth2\Requests\OAuth2TokenRevocationRequest;
use OAuth2\Responses\OAuth2Response;
use OAuth2\Services\IClientService;
use OAuth2\Strategies\OAuth2ResponseStrategyFactoryMethod;
use Utils\Http\HttpContentType;
use Utils\Services\IAuthService;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use oauth2\IOAuth2Protocol;
use oauth2\requests\OAuth2TokenRequest;
use oauth2\strategies\OAuth2ResponseStrategyFactoryMethod;
use oauth2\OAuth2Message;
use oauth2\requests\OAuth2TokenRevocationRequest;
use oauth2\requests\OAuth2AccessTokenValidationRequest;
use oauth2\responses\OAuth2Response;
use oauth2\factories\OAuth2AuthorizationRequestFactory;
use oauth2\services\IMementoOAuth2SerializerService;
use oauth2\exceptions\InvalidAuthorizationRequestException;
use utils\services\IAuthService;
use utils\http\HttpContentType;
use oauth2\requests\OAuth2LogoutRequest;
use oauth2\exceptions\UriNotAllowedException;
use \oauth2\services\IClientService;
/**
* Class OAuth2ProviderController
*/
final class OAuth2ProviderController extends BaseController
final class OAuth2ProviderController extends Controller
{
/**
* @var IOAuth2Protocol
@ -31,25 +50,25 @@ final class OAuth2ProviderController extends BaseController
private $auth_service;
/**
* @var IClientService
* @var IClientRepository
*/
private $client_service;
private $client_repository;
/**
* @param IOAuth2Protocol $oauth2_protocol
* @param IClientService $client_service
* @param IClientRepository $client_repository
* @param IAuthService $auth_service
*/
public function __construct
(
IOAuth2Protocol $oauth2_protocol,
IClientService $client_service,
IClientRepository $client_repository,
IAuthService $auth_service
)
{
$this->oauth2_protocol = $oauth2_protocol;
$this->auth_service = $auth_service;
$this->client_service = $client_service;
$this->oauth2_protocol = $oauth2_protocol;
$this->auth_service = $auth_service;
$this->client_repository = $client_repository;
}
/**
@ -59,7 +78,7 @@ final class OAuth2ProviderController extends BaseController
* use of the "POST" method as well.
* @return mixed
*/
public function authorize()
public function auth()
{
try
{
@ -89,10 +108,10 @@ final class OAuth2ProviderController extends BaseController
{
return Response::view
(
'400',
'errors.400',
array
(
'error_code' => $ex1->getError(),
'error_code' => $ex1->getError(),
'error_description' => $ex1->getMessage()
),
400
@ -162,7 +181,7 @@ final class OAuth2ProviderController extends BaseController
}
/**
* http://tools.ietf.org/html/draft-richer-oauth-introspection-04
* @see http://tools.ietf.org/html/draft-richer-oauth-introspection-04
* Introspection Token HTTP Endpoint
* @return mixed
*/
@ -218,7 +237,7 @@ final class OAuth2ProviderController extends BaseController
}
/**
* http://openid.net/specs/openid-connect-session-1_0.html#OPiframe
* @see http://openid.net/specs/openid-connect-session-1_0.html#OPiframe
*/
public function checkSessionIFrame()
{
@ -227,12 +246,12 @@ final class OAuth2ProviderController extends BaseController
}
/**
* http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
* @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
public function endSession()
{
if(!$this->auth_service->isUserLogged())
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
$request = new OAuth2LogoutRequest
(
@ -245,7 +264,7 @@ final class OAuth2ProviderController extends BaseController
if(!$request->isValid())
{
Log::error('invalid OAuth2LogoutRequest!');
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
}
if(Request::isMethod('get') )
@ -254,7 +273,7 @@ final class OAuth2ProviderController extends BaseController
$clients = array();
foreach($this->auth_service->getLoggedRPs() as $client_id)
{
$client = $this->client_service->getClientById($client_id);
$client = $this->client_repository->getClientById($client_id);
if(!is_null($client)) array_push($clients, $client);
}
@ -285,7 +304,7 @@ final class OAuth2ProviderController extends BaseController
}
Log::error('invalid consent response!');
return Response::view('404', array(), 404);
return Response::view('errors.404', array(), 404);
}
public function cancelLogout()

View File

@ -0,0 +1,90 @@
<?php namespace App\Http\Controllers\OpenId;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OpenId\IOpenIdProtocol;
use OpenId\Services\IServerConfigurationService;
use Utils\Services\IAuthService;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Response;
/**
* Class DiscoveryController
* @package App\Http\Controllers\OpenId
*/
class DiscoveryController extends OpenIdController
{
/**
* @var IOpenIdProtocol
*/
private $openid_protocol;
/**
* @var IAuthService
*/
private $auth_service;
/**
* @var IServerConfigurationService
*/
private $server_config_service;
/**
* DiscoveryController constructor.
* @param IOpenIdProtocol $openid_protocol
* @param IAuthService $auth_service
* @param IServerConfigurationService $server_config_service
*/
public function __construct
(
IOpenIdProtocol $openid_protocol,
IAuthService $auth_service,
IServerConfigurationService $server_config_service
)
{
$this->openid_protocol = $openid_protocol;
$this->auth_service = $auth_service;
$this->server_config_service = $server_config_service;
}
/**
* XRDS discovery(eXtensible Resource Descriptor Sequence)
* @return xrds document on response
*/
public function idp()
{
$response = Response::make($this->openid_protocol->getXRDSDiscovery(IOpenIdProtocol::OpenIdXRDSModeIdp), 200);
$this->setDiscoveryResponseType($response);
return $response;
}
/**
* If the Claimed Identifier was not previously discovered by the Relying Party
* (the "openid.identity" in the request was "http://specs.openid.net/auth/2.0/identifier_select"
* or a different Identifier, or if the OP is sending an unsolicited positive assertion),
* the Relying Party MUST perform discovery on the Claimed Identifier in
* the response to make sure that the OP is authorized to make assertions about the Claimed Identifier.
* @param $identifier
* @return mixed
*/
public function user($identifier)
{
$user = $this->auth_service->getUserByOpenId($identifier);
if (is_null($user))
return View::make("errors.404");
$local_identifier = $this->server_config_service->getUserIdentityEndpointURL($identifier);
$response = Response::make($this->openid_protocol->getXRDSDiscovery(IOpenIdProtocol::OpenIdXRDSModeUser, $local_identifier), 200);
$this->setDiscoveryResponseType($response);
return $response;
}
}

View File

@ -1,4 +1,4 @@
<?php
<?php namespace App\Http\Controllers\OpenId;
/**
* Copyright 2015 Openstack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -11,12 +11,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use openid\XRDS\XRDSDocumentBuilder;
use Illuminate\Support\Facades\Request;
use OpenId\Xrds\XRDSDocumentBuilder;
use App\Http\Controllers\Controller;
/**
* Class OpenIdController
* @package App\Http\Controllers\OpenId
*/
abstract class OpenIdController extends BaseController {
abstract class OpenIdController extends Controller {
/**
* @return bool

View File

@ -0,0 +1,76 @@
<?php namespace App\Http\Controllers\OpenId;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Support\Facades\Input;
use OpenId\Exceptions\InvalidOpenIdMessageException;
use OpenId\Helpers\OpenIdErrorMessages;
use OpenId\IOpenIdProtocol;
use OpenId\OpenIdMessage;
use OpenId\Responses\OpenIdResponse;
use OpenId\Services\IMementoOpenIdSerializerService;
use OpenId\Strategies\OpenIdResponseStrategyFactoryMethod;
/**
* Class OpenIdProviderController
* @package App\Http\Controllers\OpenId
*/
class OpenIdProviderController extends Controller
{
/**
* @var IOpenIdProtocol
*/
private $openid_protocol;
/**
* @var IMementoOpenIdSerializerService
*/
private $memento_service;
/**
* @param IOpenIdProtocol $openid_protocol
* @param IMementoOpenIdSerializerService $memento_service
*/
public function __construct(IOpenIdProtocol $openid_protocol, IMementoOpenIdSerializerService $memento_service)
{
$this->openid_protocol = $openid_protocol;
$this->memento_service = $memento_service;
}
/**
* @return OpenIdResponse
* @throws Exception
* @throws InvalidOpenIdMessageException
*/
public function endpoint()
{
$msg = new OpenIdMessage(Input::all());
if ($this->memento_service->exists()) {
$msg = OpenIdMessage::buildFromMemento($this->memento_service->load());
}
if (!$msg->isValid())
throw new InvalidOpenIdMessageException(OpenIdErrorMessages::InvalidOpenIdMessage);
//get response and manage it taking in consideration its type (direct or indirect)
$response = $this->openid_protocol->handleOpenIdMessage($msg);
if ($response instanceof OpenIdResponse) {
$strategy = OpenIdResponseStrategyFactoryMethod::buildStrategy($response);
return $strategy->handle($response);
}
return $response;
}
}

View File

@ -1,33 +1,58 @@
<?php
<?php namespace App\Http\Controllers;
use oauth2\services\IApiScopeService;
use oauth2\services\IClientService;
use oauth2\services\IResourceServerService;
use oauth2\services\ITokenService;
use openid\services\IMementoOpenIdSerializerService;
use openid\services\IServerConfigurationService;
use openid\services\ITrustedSitesService;
use openid\services\IUserService;
use services\IUserActionService;
use strategies\DefaultLoginStrategy;
use strategies\OAuth2ConsentStrategy;
use strategies\OAuth2LoginStrategy;
use strategies\OpenIdConsentStrategy;
use strategies\OpenIdLoginStrategy;
use utils\IPHelper;
use utils\services\IAuthService;
use utils\services\IServerConfigurationService as IUtilsServerConfigurationService;
use oauth2\services\IMementoOAuth2SerializerService;
use oauth2\services\ISecurityContextService;
use auth\exceptions\AuthenticationException;
use auth\exceptions\UnverifiedEmailMemberException;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Controllers\OpenId\DiscoveryController;
use App\Http\Controllers\OpenId\OpenIdController;
use Auth\Exceptions\AuthenticationException;
use Auth\Exceptions\UnverifiedEmailMemberException;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use OAuth2\Repositories\IApiScopeRepository;
use OAuth2\Repositories\IClientRepository;
use OpenId\Services\IUserService;
use OAuth2\Services\IApiScopeService;
use OAuth2\Services\IClientService;
use OAuth2\Services\IMementoOAuth2SerializerService;
use OAuth2\Services\IResourceServerService;
use OAuth2\Services\ISecurityContextService;
use OAuth2\Services\ITokenService;
use OpenId\Services\IMementoOpenIdSerializerService;
use OpenId\Services\ITrustedSitesService;
use Services\IUserActionService;
use Strategies\DefaultLoginStrategy;
use Strategies\IConsentStrategy;
use Strategies\OAuth2ConsentStrategy;
use Strategies\OAuth2LoginStrategy;
use Strategies\OpenIdConsentStrategy;
use Strategies\OpenIdLoginStrategy;
use Utils\IPHelper;
use Utils\Services\IAuthService;
use Utils\Services\IServerConfigurationService;
use Utils\Services\IServerConfigurationService as IUtilsServerConfigurationService;
/**
* Class UserController
* @package App\Http\Controllers
*/
final class UserController extends OpenIdController
{
/**
* @var IMementoOpenIdSerializerService
*/
@ -65,13 +90,13 @@ final class UserController extends OpenIdController
*/
private $consent_strategy;
/**
* @var IClientService
* @var IClientRepository
*/
private $client_service;
private $client_repository;
/**
* @var IApiScopeService
* @var IApiScopeRepository
*/
private $scope_service;
private $scope_repository;
/**
* @var ITokenService
*/
@ -86,19 +111,21 @@ final class UserController extends OpenIdController
private $utils_configuration_service;
/**
* UserController constructor.
* @param IMementoOpenIdSerializerService $openid_memento_service
* @param IMementoOAuth2SerializerService $oauth2_memento_service
* @param IAuthService $auth_service
* @param IServerConfigurationService $server_configuration_service
* @param IUtilsServerConfigurationService $server_configuration_service
* @param ITrustedSitesService $trusted_sites_service
* @param DiscoveryController $discovery
* @param IUserService $user_service
* @param IUserActionService $user_action_service
* @param IClientService $client_service
* @param IApiScopeService $scope_service
* @param IClientRepository $client_repository
* @param IApiScopeRepository $scope_repository
* @param ITokenService $token_service
* @param IResourceServerService $resource_server_service
* @param IUtilsServerConfigurationService $utils_configuration_service
* @param ISecurityContextService $security_context_service
*/
public function __construct
(
@ -110,8 +137,8 @@ final class UserController extends OpenIdController
DiscoveryController $discovery,
IUserService $user_service,
IUserActionService $user_action_service,
IClientService $client_service,
IApiScopeService $scope_service,
IClientRepository $client_repository,
IApiScopeRepository $scope_repository,
ITokenService $token_service,
IResourceServerService $resource_server_service,
IUtilsServerConfigurationService $utils_configuration_service,
@ -119,21 +146,19 @@ final class UserController extends OpenIdController
)
{
$this->openid_memento_service = $openid_memento_service;
$this->oauth2_memento_service = $oauth2_memento_service;
$this->auth_service = $auth_service;
$this->openid_memento_service = $openid_memento_service;
$this->oauth2_memento_service = $oauth2_memento_service;
$this->auth_service = $auth_service;
$this->server_configuration_service = $server_configuration_service;
$this->trusted_sites_service = $trusted_sites_service;
$this->discovery = $discovery;
$this->user_service = $user_service;
$this->user_action_service = $user_action_service;
$this->client_service = $client_service;
$this->scope_service = $scope_service;
$this->token_service = $token_service;
$this->resource_server_service = $resource_server_service;
$this->utils_configuration_service = $utils_configuration_service;
//filters
$this->beforeFilter('csrf', array('only' => array('postLogin', 'postConsent')));
$this->trusted_sites_service = $trusted_sites_service;
$this->discovery = $discovery;
$this->user_service = $user_service;
$this->user_action_service = $user_action_service;
$this->client_repository = $client_repository;
$this->scope_repository = $scope_repository;
$this->token_service = $token_service;
$this->resource_server_service = $resource_server_service;
$this->utils_configuration_service = $utils_configuration_service;
if ($this->openid_memento_service->exists())
{
@ -169,8 +194,8 @@ final class UserController extends OpenIdController
(
$auth_service,
$oauth2_memento_service,
$scope_service,
$client_service
$scope_repository,
$client_repository
);
}
else
@ -291,7 +316,7 @@ final class UserController extends OpenIdController
{
if (is_null($this->consent_strategy))
{
return View::make("404");
return View::make("errors.404");
}
return $this->consent_strategy->getConsent();
@ -312,7 +337,7 @@ final class UserController extends OpenIdController
{
if (is_null($this->consent_strategy))
{
return View::make("404");
return View::make("errors.404");
}
return $this->consent_strategy->postConsent(Input::get("trust"));
@ -333,7 +358,7 @@ final class UserController extends OpenIdController
$user = $this->auth_service->getUserByOpenId($identifier);
if (is_null($user))
{
return View::make("404");
return View::make("errors.404");
}
if ($this->isDiscoveryRequest())
@ -375,7 +400,7 @@ final class UserController extends OpenIdController
catch (Exception $ex)
{
Log::error($ex);
return View::make("404");
return View::make("errors.404");
}
}
@ -383,7 +408,7 @@ final class UserController extends OpenIdController
{
$this->user_action_service->addUserAction
(
$this->auth_service->getCurrentUser(),
$this->auth_service->getCurrentUser()->getId(),
IPHelper::getUserIp(),
IUserActionService::LogoutAction
);
@ -419,8 +444,9 @@ final class UserController extends OpenIdController
public function postUserProfileOptions()
{
$show_full_name = Input::get("show_full_name");
$show_email = Input::get("show_email");
$show_pic = Input::get("show_pic");
$show_email = Input::get("show_email");
$show_pic = Input::get("show_pic");
$user = $this->auth_service->getCurrentUser();
$this->user_service->saveProfileInfo($user->getId(), $show_pic, $show_full_name, $show_email);

78
app/Http/Kernel.php Normal file
View File

@ -0,0 +1,78 @@
<?php namespace App\Http;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Foundation\Http\Kernel as HttpKernel;
/**
* Class Kernel
* @package App\Http
*/
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\SingleAccessPoint::class
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
],
'api' => [
'ssl',
'cors',
'oauth2.endpoint',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'ssl' => \App\Http\Middleware\SSLMiddleware::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'csrf' => \App\Http\Middleware\VerifyCsrfToken::class,
'oauth2.endpoint' => \App\Http\Middleware\OAuth2BearerAccessTokenRequestValidator::class,
'cors' => \App\Http\Middleware\CORSMiddleware::class,
'oauth2.currentuser.serveradmin' => \App\Http\Middleware\CurrentUserIsOAuth2ServerAdmin::class,
'oauth2.currentuser.serveradmin.json' => \App\Http\Middleware\CurrentUserIsOAuth2ServerAdminJson::class,
'openstackid.currentuser.serveradmin' => \App\Http\Middleware\CurrentUserIsOpenIdServerAdmin::class,
'openstackid.currentuser.serveradmin.json' => \App\Http\Middleware\CurrentUserIsOpenIdServerAdminJson::class,
'oauth2.currentuser.allow.client.edition' => \App\Http\Middleware\CurrentUserCanEditOAuth2Client::class,
'oauth2.currentuser.owns.client' => \App\Http\Middleware\CurrentUserOwnsOAuth2Client::class,
'currentuser.checkroute' => \App\Http\Middleware\CurrentUserCheckRouteParams::class,
];
}

View File

@ -0,0 +1,49 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
/**
* Class Authenticate
* @package App\Http\Middleware
*/
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
Session::put('url.intended', URL::full());
Session::save();
return Redirect::action('HomeController@index');
}
$redirect = Session::get('url.intended');
if (!empty($redirect)) {
Session::forget('url.intended');
Session::save();
return Redirect::to($redirect);
}
return $next($request);
}
}

View File

@ -0,0 +1,457 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Utils\Services\ICacheService;
use OAuth2\Models\IApiEndpoint;
use OAuth2\Repositories\IApiEndpointRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
/**
*
* @package App\Http\Middleware\
* Implementation of http://www.w3.org/TR/cors/
*/
final class CORSMiddleware
{
const CORS_IP_BLACKLIST_PREFIX = 'CORS_IP_BLACKLIST_PREFIX:';
private $headers = array();
/**
* A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept,
* Accept-Language, or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header
* field value media type (excluding parameters) is an ASCII case-insensitive match for
* application/x-www-form-urlencoded, multipart/form-data, or text/plain.
*/
protected static $simple_headers = array
(
'accept',
'accept-language',
'content-language',
'origin',
);
protected static $simple_content_header_values = array(
'application/x-www-form-urlencode',
'multipart/form-data',
'text/plain');
/**
* A method is said to be a simple method if it is a case-sensitive match for one of the following:
* - GET
* - HEAD
* - POST
*/
protected static $simple_http_methods = array('GET', 'HEAD', 'POST');
const DefaultAllowedHeaders = 'origin, content-type, accept, authorization, x-requested-with';
const DefaultAllowedMethods = 'GET, POST, OPTIONS, PUT, DELETE';
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiEndpoint;
*/
private $current_endpoint = null;
private $allowed_headers;
private $allowed_methods;
/**
* @var ICacheService
*/
private $cache_service;
public function __construct(IApiEndpointRepository $endpoint_repository, ICacheService $cache_service)
{
$this->endpoint_repository = $endpoint_repository;
$this->cache_service = $cache_service;
$this->allowed_headers = Config::get('cors.allowed_headers', self::DefaultAllowedHeaders);
$this->allowed_methods = Config::get('cors.allowed_methods', self::DefaultAllowedMethods);
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($response = $this->preProcess($request)) {
return $response;
}
//normal processing
$response = $next($request);
$this->postProcess($request, $response);
return $response;
}
private function generatePreflightCacheKey($request)
{
$cache_id = 'pre-flight-' . $request->getClientIp() . '-' . $request->getRequestUri() . '-' . $request->getMethod();
return $cache_id;
}
/**
* @param Request $request
* @return Response
*/
public function preProcess(Request $request)
{
$actual_request = false;
if ($this->isValidCORSRequest($request)) {
if (!$this->testOriginHeaderScrutiny($request)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
/* Step 01 : Determine the type of the incoming request */
$type = $this->getRequestType($request);
/* Step 02 : Process request according to is type */
switch ($type) {
case CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT: {
// HTTP request send by client to preflight a further 'Complex' request
// sets the original method on request in order to be able to find the
// correct route
$real_method = $request->headers->get('Access-Control-Request-Method');
$route_path = Route::getCurrentRoute()->getPath();
if (strpos($route_path, '/') != 0)
$route_path = '/' . $route_path;
$request->setMethod($real_method);
if (!$route_path || !$this->checkEndPoint($route_path, $real_method)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
// ----Step 2b: Store pre-flight request data in the Cache to keep (mark) the request as correctly followed the request pre-flight process
$data = new CORSRequestPreflightData($request, $this->current_endpoint->supportCredentials());
$cache_id = $this->generatePreflightCacheKey($request);
$this->cache_service->storeHash($cache_id, $data->toArray(), CORSRequestPreflightData::$cache_lifetime);
// ----Step 2c: Return corresponding response - This part should be customized with application specific constraints.....
return $this->makePreflightResponse($request);
}
break;
case CORSRequestPreflightType::COMPLEX_REQUEST: {
$cache_id = $this->generatePreflightCacheKey($request);; // ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
if (!count($data)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
// ----Step 2b: Check that pre-flight information declared during the pre-flight request match the current request on key information
$match = false;
// ------Start with comparison of "Origin" HTTP header (according to utility method impl. used to retrieve header reference cannot be null)...
if ($request->headers->get('Origin') === $data['origin']) {
// ------Continue with HTTP method...
if ($request->getMethod() === $data['expected_method']) {
// ------Finish with custom HTTP headers (use an method to avoid manual iteration on collection to increase the speed)...
$x_headers = self::getCustomHeaders($request);
$x_headers_pre = explode(',', $data['expected_custom_headers']);
sort($x_headers);
sort($x_headers_pre);
if (count(array_diff($x_headers, $x_headers_pre)) === 0) {
$match = true;
}
}
}
if (!$match) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
}
break;
case CORSRequestPreflightType::SIMPLE_REQUEST: {
// origins, do not set any additional headers and terminate this set of steps.
if (!$this->isAllowedOrigin($request)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
// If the resource supports credentials add a single Access-Control-Allow-Origin header, with the value
// of the Origin header as value, and add a single Access-Control-Allow-Credentials header with the
// case-sensitive string "true" as value.
// Otherwise, add a single Access-Control-Allow-Origin header, with either the value of the Origin header
// or the string "*" as value.
}
break;
}
}
if ($actual_request) {
// Save response headers
$cache_id = $this->generatePreflightCacheKey($request);
// ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
$this->headers['Access-Control-Allow-Origin'] = $request->headers->get('Origin');
if ((isset($data['allows_credentials']) && (bool)$data['allows_credentials'])) {
$this->headers['Access-Control-Allow-Credentials'] = 'true';
}
/**
* During a CORS request, the getResponseHeader() method can only access simple response headers.
* Simple response headers are defined as follows:
** Cache-Control
** Content-Language
** Content-Type
** Expires
** Last-Modified
** Pragma
* If you want clients to be able to access other headers,
* you have to use the Access-Control-Expose-Headers header.
* The value of this header is a comma-delimited list of response headers you want to expose
* to the client.
*/
$exposed_headers = Config::get('cors.exposed_headers', 'Content-Type, Expires');
if (!empty($exposed_headers)) {
$this->headers['Access-Control-Expose-Headers'] = $exposed_headers;
}
}
}
public function postProcess(Request $request, Response $response)
{
// add CORS response headers
if (count($this->headers) > 0) {
$response->headers->add($this->headers);
}
return $response;
}
/**
* @param Request $request
* @return Response
*/
private function makePreflightResponse(Request $request)
{
$response = new Response();
if (!$this->isAllowedOrigin($request)) {
$response->headers->set('Access-Control-Allow-Origin', 'null');
$response->setStatusCode(403);
return $response;
}
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
// The Access-Control-Request-Method header indicates which method will be used in the actual
// request as part of the preflight request
// check request method
if ($request->headers->get('Access-Control-Request-Method') != $this->current_endpoint->getHttpMethod()) {
$response->setStatusCode(405);
return $response;
}
// The Access-Control-Allow-Credentials header indicates whether the response to request
// can be exposed when the omit credentials flag is unset. When part of the response to a preflight request
// it indicates that the actual request can include user credentials.
if ($this->current_endpoint->supportCredentials()) {
$response->headers->set('Access-Control-Allow-Credentials', 'true');
}
if (Config::get('cors.use_pre_flight_caching', false)) {
// The Access-Control-Max-Age header indicates how long the response can be cached, so that for
// subsequent requests, within the specified time, no preflight request has to be made.
$response->headers->set('Access-Control-Max-Age', Config::get('cors.max_age', 32000));
}
// The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request,
// which header field names can be used during the actual request
$response->headers->set('Access-Control-Allow-Headers', $this->allowed_headers);
//The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request,
// which methods can be used during the actual request.
$response->headers->set('Access-Control-Allow-Methods', $this->allowed_methods);
// The Access-Control-Request-Headers header indicates which headers will be used in the actual request
// as part of the preflight request.
$headers = $request->headers->get('Access-Control-Request-Headers');
if ($headers) {
$headers = trim(strtolower($headers));
$allow_headers = explode(', ', $this->allowed_headers);
foreach (preg_split('{, *}', $headers) as $header) {
//if they are simple headers then skip them
if (in_array($header, self::$simple_headers, true)) {
continue;
}
//check is the requested header is on the list of allowed headers
if (!in_array($header, $allow_headers, true)) {
$response->setStatusCode(400);
$response->setContent('Unauthorized header ' . $header);
break;
}
}
}
//OK - No Content
$response->setStatusCode(204);
return $response;
}
/**
* @param Request $request
* @returns bool
*/
private function isValidCORSRequest(Request $request)
{
/**
* The presence of the Origin header does not necessarily mean that the request is a cross-origin request.
* While all cross-origin requests will contain an Origin header,
* Origin header on same-origin requests. But Chrome and Safari include an Origin header on
* same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header).
*/
return $request->headers->has('Origin');
}
/**
* https://www.owasp.org/index.php/CORS_OriginHeaderScrutiny
* Filter that will ensure the following points for each incoming HTTP CORS requests:
* - Have only one and non empty instance of the origin header,
* - Have only one and non empty instance of the host header,
* - The value of the origin header is present in a internal allowed domains list (white list). As we act before the
* step 2 of the CORS HTTP requests/responses exchange process, allowed domains list is yet provided to client,
* - Cache IP of the sender for 1 hour. If the sender send one time a origin domain that is not in the white list
* then all is requests will return an HTTP 403 response (protract allowed domain guessing).
* We use the method above because it's not possible to identify up to 100% that the request come from one expected
* client application, since:
* - All information of a HTTP request can be faked,
* - It's the browser (or others tools) that send the HTTP request then the IP address that we have access to is the
* client IP address.
* @param Request $request
* @return bool
*/
private function testOriginHeaderScrutiny(Request $request)
{
/* Step 0 : Check presence of client IP in black list */
$client_ip = $request->getClientIp();
if (Cache::has(self::CORS_IP_BLACKLIST_PREFIX . $client_ip)) {
return false;
}
/* Step 1 : Check that we have only one and non empty instance of the "Origin" header */
$origin = $request->headers->get('Origin', null, false);
if (is_array($origin) && count($origin) > 1) {
// If we reach this point it means that we have multiple instance of the "Origin" header
// Add client IP address to black listed client
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 2 : Check that we have only one and non empty instance of the "Host" header */
$host = $request->headers->get('Host', null, false);
//Have only one and non empty instance of the host header,
if (is_array($host) && count($host) > 1) {
// If we reach this point it means that we have multiple instance of the "Host" header
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 3 : Perform analysis - Origin header is required */
$origin = $request->headers->get('Origin');
$host = $request->headers->get('Host');
$server_name = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
// check origin not empty and allowed
if (!$this->isAllowedOrigin($origin)) {
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
if (is_null($host) || $server_name != $host) {
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 4 : Finalize request next step */
return true;
}
private function checkEndPoint($endpoint_path, $http_method)
{
$this->current_endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($endpoint_path, $http_method);
if (is_null($this->current_endpoint)) {
return false;
}
if (!$this->current_endpoint->supportCORS() || !$this->current_endpoint->isActive()) {
return false;
}
return true;
}
/**
* @param string $origin
* @return bool
*/
private function isAllowedOrigin($origin)
{
return true;
}
private static function getRequestType(Request $request)
{
$type = CORSRequestPreflightType::UNKNOWN;
$http_method = $request->getMethod();
$content_type = strtolower($request->getContentType());
$http_method = strtoupper($http_method);
if ($http_method === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method')) {
$type = CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT;
} else {
if (self::hasCustomHeaders($request)) {
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
} elseif ($http_method === 'POST' && !in_array($content_type, self::$simple_content_header_values, true)) {
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
} elseif (!in_array($http_method, self::$simple_http_methods, true)) {
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
} else {
$type = CORSRequestPreflightType::SIMPLE_REQUEST;
}
}
return $type;
}
private static function getCustomHeaders(Request $request)
{
$custom_headers = array();
foreach ($request->headers->all() as $k => $h) {
if (starts_with('X-', strtoupper(trim($k)))) {
array_push($custom_headers, strtoupper(trim($k)));
}
}
return $custom_headers;
}
private static function hasCustomHeaders(Request $request)
{
return count(self::getCustomHeaders($request)) > 0;
}
}

View File

@ -0,0 +1,82 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Symfony\Component\HttpFoundation\Request;
/**
* Class CORSRequestPreflightData
* @package App\Http\Middleware
*/
class CORSRequestPreflightData
{
// ttl on seconds
public static $cache_lifetime = 10;
public static $cache_attributes = array('sender', 'uri', 'origin', 'expected_method', 'expected_custom_headers', 'allows_credentials');
/** Final HTTP request expected method */
private $expected_method = null;
/** Final HTTP request expected custom headers */
private $expected_custom_headers = array();
/** Current HTTP request uri */
private $uri = null;
/** Current HTTP request origin header */
private $origin = null;
/** Current Sender IP address */
private $sender = null;
/**
* @var bool
*/
private $allows_credentials;
/**
* @param Request $request
* @param bool $allows_credentials
*/
public function __construct(Request $request, $allows_credentials)
{
$this->sender = $request->getClientIp();
$this->uri = $request->getRequestUri();
$this->origin = $request->headers->get('Origin');
$this->expected_method = $request->headers->get('Access-Control-Request-Method');
$this->allows_credentials = $allows_credentials;
$tmp = $request->headers->get("Access-Control-Request-Headers");
if (!empty($tmp))
{
$hs = explode(',', $tmp);
foreach ($hs as $h)
{
array_push($this->expected_custom_headers, strtoupper(trim($h)));
}
}
}
/**
* @return array
*/
public function toArray()
{
$res = array();
$res['sender'] = $this->sender;
$res['uri'] = $this->uri;
$res['origin'] = $this->origin;
$res['allows_credentials'] = $this->allows_credentials;
$res['expected_method'] = $this->expected_method;
$res['expected_custom_headers'] = implode(',', $this->expected_custom_headers);
return $res;
}
}

View File

@ -0,0 +1,36 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class CORSRequestPreflightType
* @package App\Http\Middleware
*/
final class CORSRequestPreflightType
{
/** HTTP request send by client to preflight a further 'Complex' request */
const REQUEST_FOR_PREFLIGHT = 0;
/** Normal HTTP request send by client that require preflight ie 'Complex' resquest in Preflight process */
const COMPLEX_REQUEST = 1;
/** Normal HTTP request send by client that do not require preflight ie 'Simple' resquest in Preflight process */
const SIMPLE_REQUEST = 2;
/** Cannot determine request type */
const UNKNOWN = -1;
}

View File

@ -0,0 +1,81 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Response;
use OAuth2\Repositories\IClientRepository;
use Utils\Services\IAuthService;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
use OAuth2\Services\OAuth2ServiceCatalog;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
/**
* Class CurrentUserCanEditOAuth2Client
* @package App\Http\Middleware
*/
final class CurrentUserCanEditOAuth2Client
{
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IAuthService
*/
private $auth_service;
public function __construct(IClientRepository $client_repository, IAuthService $auth_service)
{
$this->client_repository = $client_repository;
$this->auth_service = $auth_service;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
try{
$route = Route::getCurrentRoute();
$client_id = $route->getParameter('id');
if(is_null($client_id))
$client_id = $route->getParameter('client_id');
if(is_null($client_id))
$client_id = Input::get('client_id',null);;
$client = $this->client_repository->getClientByIdentifier($client_id);
$user = $this->auth_service->getCurrentUser();
if (is_null($client) || !$client->candEdit($user))
throw new Exception('invalid client id for current user');
} catch (Exception $ex) {
Log::error($ex);
return Response::json(array('error' => 'operation not allowed.'), 400);
}
return $next($request);
}
}

View File

@ -0,0 +1,63 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Response;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
/**
* Class CurrentUserCheckRouteParams
* @package App\Http\Middleware
*/
class CurrentUserCheckRouteParams
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
try{
$route = Route::getCurrentRoute();
$authentication_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::AuthenticationService);
$used_id = Input::get('user_id',null);
if(is_null($used_id))
$used_id = Input::get('id',null);
if(is_null($used_id))
$used_id = $route->getParameter('user_id');
if(is_null($used_id))
$used_id = $route->getParameter('id');
$user = $authentication_service->getCurrentUser();
if (is_null($used_id) || intval($used_id) !== intval($user->getId()))
throw new Exception(sprintf('user id %s does not match with current user id %s',$used_id,$user->getId()));
} catch (Exception $ex) {
Log::error($ex);
return Response::json(array('error' => 'operation not allowed.'), 400);
}
return $next($request);
}
}

View File

@ -0,0 +1,44 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOAuth2ServerAdmin
* @package App\Http\Middleware
*/
final class CurrentUserIsOAuth2ServerAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::view('errors.404', array(), 404);
}
if(!Auth::user()->isOAuth2ServerAdmin())
{
return Response::view('errors.404', array(), 404);
}
return $next($request);
}
}

View File

@ -0,0 +1,45 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOAuth2ServerAdminJson
* @package App\Http\Middleware
*/
final class CurrentUserIsOAuth2ServerAdminJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::json(array('error' => 'you are not allowed to perform this operation'), 403);
}
if(!Auth::user()->isOAuth2ServerAdmin())
{
return Response::json(array('error' => 'you are not allowed to perform this operation'), 403);
}
return $next($request);
}
}

View File

@ -0,0 +1,44 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOpenIdServerAdmin
* @package App\Http\Middleware
*/
final class CurrentUserIsOpenIdServerAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::view('errors.404', array(), 404);
}
if(!Auth::user()->isOpenstackIdAdmin())
{
return Response::view('errors.404', array(), 404);
}
return $next($request);
}
}

View File

@ -0,0 +1,44 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
/**
* Class CurrentUserIsOpenIdServerAdminJson
* @package App\Http\Middleware
*/
class CurrentUserIsOpenIdServerAdminJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
return Response::json(array('error' => 'you are not allowed to perform this operation'));
}
if(!Auth::user()->isOpenstackIdAdmin())
{
return Response::json(array('error' => 'you are not allowed to perform this operation'));
}
return $next($request);
}
}

View File

@ -0,0 +1,80 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Response;
use OAuth2\Repositories\IClientRepository;
use Utils\Services\IAuthService;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
use OAuth2\Services\OAuth2ServiceCatalog;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
/**
* Class CurrentUserOwnsOAuth2Client
* @package App\Http\Middleware
*/
class CurrentUserOwnsOAuth2Client
{
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var IAuthService
*/
private $auth_service;
public function __construct(IClientRepository $client_repository, IAuthService $auth_service)
{
$this->client_repository = $client_repository;
$this->auth_service = $auth_service;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
try{
$route = Route::getCurrentRoute();
$client_id = $route->getParameter('id');
if(is_null($client_id))
$client_id = $route->getParameter('client_id');
if(is_null($client_id))
$client_id = Input::get('client_id',null);;
$client = $this->client_repository->getClientByIdentifier($client_id);
$user = $this->auth_service->getCurrentUser();
if (is_null($client) || !$client->isOwner($user))
throw new Exception('invalid client id for current user');
} catch (Exception $ex) {
Log::error($ex);
return Response::json(array('error' => 'operation not allowed.'), 400);
}
return $next($request);
}
}

View File

@ -0,0 +1,51 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Log;
/**
* Class ETagsMiddleware
* @package App\Http\Middleware
*/
final class ETagsMiddleware
{
/**
* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response->getStatusCode() === 200 && $request->getMethod() === 'GET')
{
$etag = md5($response->getContent());
$requestETag = str_replace('"', '', $request->getETags());
$requestETag = str_replace('-gzip', '', $requestETag);
if ($requestETag && $requestETag[0] == $etag)
{
Log::debug('ETAG 304');
$response->setNotModified();
}
$response->setEtag($etag);
}
return $response;
}
}

View File

@ -0,0 +1,19 @@
<?php namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
/***
* Class EncryptCookies
* @package App\Http\Middleware
*/
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -1,63 +1,75 @@
<?php
use oauth2\services\IApiEndpointService;
use oauth2\services\ITokenService;
use oauth2\BearerAccessTokenAuthorizationHeaderParser;
use oauth2\OAuth2Protocol;
use oauth2\responses\OAuth2WWWAuthenticateErrorResponse;
use utils\services\ILogService;
use oauth2\exceptions\OAuth2ResourceServerException;
use oauth2\exceptions\InvalidGrantTypeException;
use oauth2\exceptions\ExpiredAccessTokenException;
use utils\services\ICheckPointService;
use oauth2\IResourceServerContext;
use oauth2\services\IClientService;
use oauth2\models\IClient;
use utils\http\HttpContentType;
use oauth2\exceptions\RevokedAccessTokenException;
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use OAuth2\BearerAccessTokenAuthorizationHeaderParser;
use OAuth2\Exceptions\ExpiredAccessTokenException;
use OAuth2\Exceptions\InvalidGrantTypeException;
use OAuth2\Exceptions\RevokedAccessTokenException;
use OAuth2\Models\IClient;
use OAuth2\OAuth2Protocol;
use OAuth2\Exceptions\OAuth2ResourceServerException;
use OAuth2\Repositories\IClientRepository;
use OAuth2\Responses\OAuth2WWWAuthenticateErrorResponse;
use OAuth2\Services\ITokenService;
use OAuth2\IResourceServerContext;
use OAuth2\Repositories\IApiEndpointRepository;
use OAuth2\Services\IClientService;
use URL\Normalizer;
use Illuminate\Support\Facades\Route;
use Exception;
use Utils\Services\ICheckPointService;
use Utils\Services\ILogService;
/**
* Class OAuth2BearerAccessTokenRequestValidator
* this class implements the logic to Accessing to Protected Resources
* http://tools.ietf.org/html/rfc6750
* http://tools.ietf.org/html/rfc6749#section-7
* @see http://tools.ietf.org/html/rfc6750
* @see http://tools.ietf.org/html/rfc6749#section-7
* @package App\Http\Middleware
*/
final class OAuth2BearerAccessTokenRequestValidator {
protected function getHeaders()
{
$headers = array();
if (function_exists('getallheaders')) {
// @codeCoverageIgnoreStart
foreach(getallheaders() as $name => $value){
$headers[strtolower($name)] = $value;
}
} else {
// @codeCoverageIgnoreEnd
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
$headers[strtolower($name)] = $value;
}
}
foreach(Request::header() as $name => $value){
if(!array_key_exists($name,$headers))
$headers[strtolower($name)] = $value[0];
}
}
return $headers;
}
final class OAuth2BearerAccessTokenRequestValidator
{
/**
* @var IApiEndpointService
* @var IResourceServerContext
*/
private $api_endpoint_service;
private $context;
/**
* @var array
*/
private $headers;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var ITokenService
*/
private $token_service;
/**
* @var IClientRepository
*/
private $client_repository;
/**
* @var ILogService
*/
@ -66,124 +78,111 @@ final class OAuth2BearerAccessTokenRequestValidator {
* @var ICheckPointService
*/
private $checkpoint_service;
/**
* @var IResourceServerContext
*/
private $resource_server_context;
/**
* @var array
*/
private $headers;
/**
* @var IClientService
*/
private $client_service;
/**
* @param IResourceServerContext $resource_server_context
* @param IApiEndpointService $api_endpoint_service
* OAuth2BearerAccessTokenRequestValidator constructor.
* @param IResourceServerContext $context
* @param IApiEndpointRepository $endpoint_repository
* @param ITokenService $token_service
* @param IClientRepository $client_repository
* @param ILogService $log_service
* @param ICheckPointService $checkpoint_service
* @param IClientService $client_service
*/
public function __construct
(
IResourceServerContext $resource_server_context,
IApiEndpointService $api_endpoint_service,
public function __construct(
IResourceServerContext $context,
IApiEndpointRepository $endpoint_repository,
ITokenService $token_service,
IClientRepository $client_repository,
ILogService $log_service,
ICheckPointService $checkpoint_service,
IClientService $client_service
)
{
$this->api_endpoint_service = $api_endpoint_service;
$this->token_service = $token_service;
$this->log_service = $log_service;
$this->checkpoint_service = $checkpoint_service;
$this->resource_server_context = $resource_server_context;
$this->headers = $this->getHeaders();
$this->client_service = $client_service;
ICheckPointService $checkpoint_service
) {
$this->context = $context;
$this->headers = $this->getHeaders();
$this->endpoint_repository = $endpoint_repository;
$this->token_service = $token_service;
$this->client_repository = $client_repository;
$this->log_service = $log_service;
$this->checkpoint_service = $checkpoint_service;
}
/**
* @param $route
* @param $request
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @return OAuth2WWWAuthenticateErrorResponse
*/
public function filter($route, $request)
public function handle($request, Closure $next)
{
$url = $route->getPath();
$url = $request->getRequestUri();
$method = $request->getMethod();
$realm = $request->getHost();
if(strpos($url, '/') != 0)
{
$url = '/'.$url;
}
$method = $request->getMethod();
$realm = $request->getHost();
// http://tools.ietf.org/id/draft-abarth-origin-03.html
$origin = $request->headers->has('Origin') ? $request->headers->get('Origin') : null;
try {
$route_path = Route::getCurrentRoute()->getPath();
if (strpos($route_path, '/') != 0)
$route_path = '/' . $route_path;
try
{
$endpoint = $this->api_endpoint_service->getApiEndpointByUrlAndMethod($url, $method);
//api endpoint must be registered on db and active
if(is_null($endpoint) || !$endpoint->isActive())
{
throw new OAuth2ResourceServerException
(
if (!$route_path) {
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
sprintf
(
'API endpoint does not exits! (%s:%s)',
$url,
$method
)
sprintf('API endpoint does not exits! (%s:%s)', $url, $method)
);
}
//check first http basic auth header
$auth_header = isset($this->headers['authorization'])?$this->headers['authorization']:null;
Log::debug($request->headers->__toString());
// http://tools.ietf.org/id/draft-abarth-origin-03.html
$origin = $request->headers->has('Origin') ? $request->headers->get('Origin') : null;
if (!empty($origin)) {
$nm = new Normalizer($origin);
$origin = $nm->normalize();
}
if(!is_null($auth_header) && !empty($auth_header))
//check first http basic auth header
$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
{
} else {
// http://tools.ietf.org/html/rfc6750#section-2- 2
// if access token is not on authorization header check on POST/GET params
$access_token_value = Input::get(OAuth2Protocol::OAuth2Protocol_AccessToken, '');
}
if(is_null($access_token_value) || empty($access_token_value))
{
if (is_null($access_token_value) || empty($access_token_value)) {
//if access token value is not set, then error
throw new OAuth2ResourceServerException
(
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'missing access token'
);
}
// get access token from service
$access_token = $this->token_service->getAccessToken($access_token_value);
if(is_null($access_token))
throw new ExpiredAccessTokenException(sprintf('Access token %s is expired!', $access_token_value));
//check token audience
$audience = explode(' ', $access_token->getAudience());
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route_path, $method);
if((!in_array($realm , $audience)))
throw new OAuth2ResourceServerException
(
401,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
sprintf('access token audience does not match - current_realm %s - access token audience %s',$realm, $access_token->getAudience())
//api endpoint must be registered on db and active
if (is_null($endpoint) || !$endpoint->isActive()) {
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
sprintf('API endpoint does not exits! (%s:%s)', $route_path, $method)
);
}
$access_token = $this->token_service->getAccessToken($access_token_value);
//check lifetime
if (is_null($access_token)) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
Log::debug(sprintf("token lifetime %s", $access_token->getRemainingLifetime()));
//check token audience
Log::debug('checking token audience ...');
$audience = explode(' ', $access_token->getAudience());
if ((!in_array($realm, $audience))) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
//check client existence
$client_id = $access_token->getClientId();
$client = $this->client_service->getClientById($client_id);
$client = $this->client_repository->getClientById($client_id);
if(is_null($client))
throw new OAuth2ResourceServerException
@ -192,7 +191,6 @@ final class OAuth2BearerAccessTokenRequestValidator {
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'invalid client'
);
//if js client , then check if the origin is allowed ....
if($client->getApplicationType() == IClient::ApplicationType_JS_Client)
{
@ -205,49 +203,51 @@ final class OAuth2BearerAccessTokenRequestValidator {
);
}
//check scopes
$endpoint_scopes = explode(' ',$endpoint->getScope());
$token_scopes = explode(' ',$access_token->getScope());
Log::debug('checking token scopes ...');
$endpoint_scopes = explode(' ', $endpoint->getScope());
$token_scopes = explode(' ', $access_token->getScope());
//check token available scopes vs. endpoint scopes
if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0)
{
$this->log_service->error_msg
(
sprintf
(
if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0) {
Log::warning(
sprintf(
'access token scopes (%s) does not allow to access to api url %s , needed scopes %s',
$access_token->getScope(),
$url,
implode(' OR ',$endpoint_scopes)
implode(' OR ', $endpoint_scopes)
)
);
throw new OAuth2ResourceServerException
(
throw new OAuth2ResourceServerException(
403,
OAuth2Protocol::OAuth2Protocol_Error_InsufficientScope,
'the request requires higher privileges than provided by the access token',
implode(' ',$endpoint_scopes)
implode(' ', $endpoint_scopes)
);
}
Log::debug('setting resource server context ...');
//set context for api and continue processing
$context = array
(
'access_token' => $access_token_value,
'expires_in' => $access_token->getRemainingLifetime(),
'client_id' => $client_id,
'scope' => $access_token->getScope()
'access_token' => $access_token_value,
'expires_in' => $access_token->getRemainingLifetime(),
'client_id' => $client_id,
'scope' => $access_token->getScope(),
'application_type' => $client->getApplicationType()
);
if(!is_null($access_token->getUserId()))
$context['user_id'] = $access_token->getUserId();
if (!is_null($access_token->getUserId()))
{
$context['user_id'] = $access_token->getUserId();
//$context['user_external_id'] = $access_token->getUserExternalId();
}
$this->resource_server_context->setAuthorizationContext($context);
$this->context->setAuthorizationContext($context);
}
catch(OAuth2ResourceServerException $ex1)
{
$this->log_service->error($ex1);
$this->log_service->warning($ex1);
$this->checkpoint_service->trackException($ex1);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
$ex1->getError(),
@ -261,7 +261,7 @@ final class OAuth2BearerAccessTokenRequestValidator {
}
catch(InvalidGrantTypeException $ex2)
{
$this->log_service->error($ex2);
$this->log_service->warning($ex2);
$this->checkpoint_service->trackException($ex2);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
@ -275,7 +275,7 @@ final class OAuth2BearerAccessTokenRequestValidator {
}
catch(ExpiredAccessTokenException $ex3)
{
$this->log_service->error($ex3);
$this->log_service->warning($ex3);
$this->checkpoint_service->trackException($ex3);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
@ -289,7 +289,7 @@ final class OAuth2BearerAccessTokenRequestValidator {
}
catch(RevokedAccessTokenException $ex4)
{
$this->log_service->error($ex4);
$this->log_service->warning($ex4);
$this->checkpoint_service->trackException($ex4);
$response = new OAuth2WWWAuthenticateErrorResponse($realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
@ -315,5 +315,36 @@ final class OAuth2BearerAccessTokenRequestValidator {
$http_response->header('WWW-Authenticate',$response->getWWWAuthenticateHeaderValue());
return $http_response;
}
$response = $next($request);
return $response;
}
/**
* @return array
*/
protected function getHeaders()
{
$headers = array();
if (function_exists('getallheaders')) {
foreach (getallheaders() as $name => $value) {
$headers[strtolower($name)] = $value;
}
} else {
// @codeCoverageIgnoreEnd
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
$headers[strtolower($name)] = $value;
}
}
foreach (Request::header() as $name => $value) {
if (!array_key_exists($name, $headers)) {
$headers[strtolower($name)] = $value[0];
}
}
}
return $headers;
}
}

View File

@ -0,0 +1,40 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Auth;
/**
* Class RedirectIfAuthenticated
* @package App\Http\Middleware
*/
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}

View File

@ -0,0 +1,33 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
/**
* Class SSLMiddleware
* @package App\Http\Middleware
*/
final class SSLMiddleware
{
public function handle($request, Closure $next)
{
if (!Request::secure() && Config::get("server.ssl_enabled", false)) {
return Redirect::secure(Request::getRequestUri());
}
return $next($request);
}
}

View File

@ -0,0 +1,44 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
/**
* Class SecurityHTTPHeadersWriterMiddleware
* https://www.owasp.org/index.php/List_of_useful_HTTP_headers
*
* @package App\Http\Middleware
*/
class SecurityHTTPHeadersWriterMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
$response = $next($request);
// https://www.owasp.org/index.php/List_of_useful_HTTP_headers
$response->headers->set('X-content-type-options','nosniff');
$response->headers->set('X-xss-protection','1; mode=block');
//cache
$response->headers->set('pragma','no-cache');
$response->headers->set('Expires','-1');
$response->headers->set('cache-control','no-store, must-revalidate, no-cache');
return $response;
}
}

View File

@ -0,0 +1,46 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Log;
use Utils\Services\ICheckPointService;
use Utils\Services\ServiceLocator;
use Utils\Services\UtilsServiceCatalog;
/**
* Class SingleAccessPoint
* @package App\Http\Middleware
*/
final class SingleAccessPoint
{
public function handle($request, Closure $next)
{
// Perform action
if(Config::get('server.Banning_Enable', true))
{
try {
//checkpoint security pattern entry point
$checkpoint_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::CheckPointService);
if ($checkpoint_service instanceof ICheckPointService && !$checkpoint_service->check()) {
return Response::view('errors.404', array(), 404);
}
} catch (Exception $ex) {
Log::error($ex);
return Response::view('errors.404', array(), 404);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}

View File

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 98 KiB

View File

@ -0,0 +1,10 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
//
}

255
app/Http/routes.php Normal file
View File

@ -0,0 +1,255 @@
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::pattern('id', '[0-9]+');
Route::pattern('uri_id', '[0-9]+');
Route::pattern('active', '(true|false)');
Route::pattern('hint', '(access-token|refresh-token)');
Route::pattern('scope_id', '[0-9]+');
Route::group(['namespace' => 'App\Http\Controllers', 'middleware' => 'web' ], function() {
// openid endpoints
Route::group(array('middleware' => ['ssl']), function () {
Route::get('/', "HomeController@index");
// OpenId endpoints
Route::group(['namespace' => 'OpenId' ], function() {
Route::get('/discovery', "DiscoveryController@idp");
Route::get("/discovery/users/{identifier}","DiscoveryController@user")->where(array('identifier' => '[\d\w\.\#]+'));
//op endpoint url
Route::post('/accounts/openid2', 'OpenIdProviderController@endpoint');
Route::get('/accounts/openid2', 'OpenIdProviderController@endpoint');
});
/*
* If the Claimed Identifier was not previously discovered by the Relying Party
* (the "openid.identity" in the request was "http://specs.openid.net/auth/2.0/identifier_select"
* or a different Identifier, or if the OP is sending an unsolicited positive assertion),
* the Relying Party MUST perform discovery on the Claimed Identifier in
* the response to make sure that the OP is authorized to make assertions about the Claimed Identifier.
*/
Route::get("/{identifier}", "UserController@getIdentity");
//user interaction
Route::get('/accounts/user/login', "UserController@getLogin");
Route::post('/accounts/user/login', ['middleware' => 'csrf', 'uses' => 'UserController@postLogin']);
Route::get('/accounts/user/login/cancel', "UserController@cancelLogin");
});
//oauth2 endpoints
Route::group(['namespace'=> 'OAuth2', 'middleware' => ['ssl']], function () {
Route::get('/.well-known/openid-configuration', "OAuth2ProviderController@discovery");
});
Route::group(['namespace' => 'OAuth2' , 'prefix' => 'oauth2', 'middleware' => ['ssl']], function () {
Route::get('/check-session', "OAuth2ProviderController@checkSessionIFrame");
Route::get('/end-session', "OAuth2ProviderController@endSession");
Route::get('/end-session/cancel', "OAuth2ProviderController@cancelLogout");
Route::post('/end-session', "OAuth2ProviderController@endSession");
//authorization endpoint
Route::any('/auth', "OAuth2ProviderController@auth");
// OIDC
// certificates
Route::get('/certs', "OAuth2ProviderController@certs");
// discovery document
Route::get('/.well-known/openid-configuration', "OAuth2ProviderController@discovery");
//token endpoint
Route::group(array('prefix' => 'token'), function () {
Route::post('/', "OAuth2ProviderController@token");
Route::post('/revoke', "OAuth2ProviderController@revoke");
Route::post('/introspection', "OAuth2ProviderController@introspection");
});
});
Route::group(array('middleware' => ['ssl', 'auth']), function () {
Route::get('/accounts/user/consent', "UserController@getConsent");
Route::post('/accounts/user/consent', ['middleware' => 'csrf', 'uses' => 'UserController@postConsent']);
Route::any("/accounts/user/logout", "UserController@logout");
Route::any("/accounts/user/profile", "UserController@getProfile");
Route::any("/accounts/user/profile/trusted_site/delete/{id}", "UserController@deleteTrustedSite");
Route::post('/accounts/user/profile/update', 'UserController@postUserProfileOptions');
});
Route::group(['prefix' => 'admin', 'middleware' => ['ssl', 'auth']], function () {
//client admin UI
Route::get('clients/edit/{id}', ['middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'AdminController@editRegisteredClient']);
Route::get('clients', 'AdminController@listOAuth2Clients');
Route::get('/grants', 'AdminController@editIssuedGrants');
//oauth2 server admin UI
Route::group(array('middleware' => ['oauth2.currentuser.serveradmin']), function () {
Route::get('/api-scope-groups', 'AdminController@listApiScopeGroups');
Route::get('/api-scope-groups/{id}', 'AdminController@editApiScopeGroup');
Route::get('/resource-servers', 'AdminController@listResourceServers');
Route::get('/resource-server/{id}', 'AdminController@editResourceServer');
Route::get('/api/{id}', 'AdminController@editApi');
Route::get('/scope/{id}', 'AdminController@editScope');
Route::get('/endpoint/{id}', 'AdminController@editEndpoint');
Route::get('/locked-clients', 'AdminController@listLockedClients');
// server private keys
Route::get('/private-keys', 'AdminController@listServerPrivateKeys');
});
Route::group(array('middleware' => ['openstackid.currentuser.serveradmin']), function () {
Route::get('/locked-users', 'AdminController@listLockedUsers');
Route::get('/server-config', 'AdminController@listServerConfig');
Route::post('/server-config', 'AdminController@saveServerConfig');
Route::get('/banned-ips', 'AdminController@listBannedIPs');
});
});
//Admin Backend API
Route::group([
'namespace' => 'Api',
'prefix' => 'admin/api/v1',
'middleware' => ['ssl', 'auth']], function () {
Route::group(array('prefix' => 'users'), function () {
Route::delete('/{id}/locked', array('middleware' => ['openstackid.currentuser.serveradmin.json'], 'uses' => 'UserApiController@unlock'));
Route::delete('/{id}/token/{value}', array('middleware' => ['currentuser.checkroute'], 'uses' => 'UserApiController@revokeToken'));
Route::get('/fetch', array('uses' => "UserApiController@fetch"));
});
Route::group(array('prefix' => 'banned-ips', 'middleware' => ['openstackid.currentuser.serveradmin.json']), function () {
Route::get('/{id}', "ApiBannedIPController@get");
Route::get('/', "ApiBannedIPController@getByPage");
Route::delete('/{id?}', "ApiBannedIPController@delete");
});
//client api
Route::group(array('prefix' => 'clients'), function () {
// public keys
Route::post('/{id}/public_keys', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientPublicKeyApiController@create'));
Route::get('/{id}/public_keys', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientPublicKeyApiController@getByPage'));
Route::delete('/{id}/public_keys/{public_key_id}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientPublicKeyApiController@delete'));
Route::put('/{id}/public_keys/{public_key_id}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientPublicKeyApiController@update'));
Route::post('/', array('middleware' => ['currentuser.checkroute'], 'uses' => 'ClientApiController@create'));
Route::put('/', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@update'));
Route::get('/{id}', "ClientApiController@get");
Route::get('/', array('middleware' => ['currentuser.checkroute'], 'uses' => 'ClientApiController@getByPage'));
Route::delete('/{id}', array('middleware' => ['oauth2.currentuser.owns.client'], 'uses' => 'ClientApiController@delete'));
//allowed redirect uris endpoints
Route::get('/{id}/uris', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@getRegisteredUris'));
Route::post('/{id}/uris', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@addAllowedRedirectUri'));
Route::delete('/{id}/uris/{uri_id}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@deleteClientAllowedUri'));
//allowedApiResourceServerControllert('/{id}/origins', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@geAllowedOrigins'));
Route::post('/{id}/origins', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@addAllowedOrigin'));
Route::delete('/{id}/origins/{origin_id}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@deleteClientAllowedOrigin'));
Route::delete('/{id}/lock', array('middleware' => ['openstackid.currentuser.serveradmin.json'], 'uses' => 'ClientApiController@unlock'));
Route::put('/{id}/secret', array('middleware' => ['oauth2.currentuser.owns.client'], 'uses' => 'ClientApiController@regenerateClientSecret'));
Route::put('/{id}/use-refresh-token', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@setRefreshTokenClient'));
Route::put('/{id}/rotate-refresh-token', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@setRotateRefreshTokenPolicy'));
Route::get('/{id}/access-token', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@getAccessTokens'));
Route::get('/{id}/refresh-token', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@getRefreshTokens'));
Route::get('/me/access-tokens', array('middleware' => [], 'uses' => 'ClientApiController@getAccessTokensByCurrentUser'));
Route::get('/me/refresh-tokens', array('middleware' => [], 'uses' => 'ClientApiController@getRefreshTokensByCurrentUser'));
Route::delete('/{id}/token/{value}/{hint}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@revokeToken'));
Route::put('/{id}/scopes/{scope_id}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@addAllowedScope'));
Route::delete('/{id}/scopes/{scope_id}', array('middleware' => ['oauth2.currentuser.allow.client.edition'], 'uses' => 'ClientApiController@removeAllowedScope'));
Route::put('/{id}/active', array('middleware' => ['oauth2.currentuser.owns.client'], 'uses' => 'ClientApiController@activate'));
Route::delete('/{id}/active', array('middleware' => ['oauth2.currentuser.owns.client'], 'uses' => 'ClientApiController@deactivate'));
});
// resource servers
Route::group(array('prefix' => 'resource-servers', 'middleware' => ['oauth2.currentuser.serveradmin.json']), function () {
Route::get('/{id}', "ApiResourceServerController@get");
Route::get('/', "ApiResourceServerController@getByPage");
Route::post('/', "ApiResourceServerController@create");
Route::delete('/{id}', "ApiResourceServerController@delete");
Route::put('/', "ApiResourceServerController@update");
Route::put('/{id}/client-secret', "ApiResourceServerController@regenerateClientSecret");
Route::put('/{id}/active', "ApiResourceServerController@activate");
Route::delete('/{id}/active', "ApiResourceServerController@deactivate");
});
// api scope groups
Route::group(array('prefix' => 'api-scope-groups', 'middleware' => ['oauth2.currentuser.serveradmin.json']), function () {
Route::get('/{id}', "ApiScopeGroupController@get");
Route::get('/', "ApiScopeGroupController@getByPage");
Route::put('/', "ApiScopeGroupController@update");
Route::post('/', "ApiScopeGroupController@create");
Route::delete('/{id}', "ApiScopeGroupController@delete");
Route::put('/{id}/active', "ApiScopeGroupController@activate");
Route::delete('/{id}/active', "ApiScopeGroupController@deactivate");
});
// apis
Route::group(array('prefix' => 'apis', 'middleware' => ['oauth2.currentuser.serveradmin.json']), function () {
Route::get('/{id}', "ApiController@get");
Route::get('/', "ApiController@getByPage");
Route::post('/', "ApiController@create");
Route::delete('/{id}', "ApiController@delete");
Route::put('/', "ApiController@update");
Route::put('/{id}/active', "ApiController@activate");
Route::delete('/{id}/active', "ApiController@deactivate");
});
// scopes
Route::group(array('prefix' => 'scopes', 'middleware' => ['oauth2.currentuser.serveradmin.json']), function () {
Route::get('/{id}', "ApiScopeController@get");
Route::get('/', "ApiScopeController@getByPage");
Route::post('/', "ApiScopeController@create");
Route::delete('/{id}', "ApiScopeController@delete");
Route::put('/', "ApiScopeController@update");
Route::put('/{id}/active', "ApiScopeController@activate");
Route::delete('/{id}/active', "ApiScopeController@deactivate");
});
// endpoints
Route::group(array('prefix' => 'endpoints', 'middleware' => ['oauth2.currentuser.serveradmin.json']), function () {
Route::get('/{id}', "ApiEndpointController@get");
Route::get('/', "ApiEndpointController@getByPage");
Route::post('/', "ApiEndpointController@create");
Route::delete('/{id}', "ApiEndpointController@delete");
Route::put('/', "ApiEndpointController@update");
Route::put('/{id}/scope/{scope_id}', "ApiEndpointController@addRequiredScope");
Route::delete('/{id}/scope/{scope_id}', "ApiEndpointController@removeRequiredScope");
Route::put('/{id}/active', "ApiEndpointController@activate");
Route::delete('/{id}/active', "ApiEndpointController@deactivate");
});
// private keys
Route::group(array('prefix' => 'private-keys', 'middleware' => ['oauth2.currentuser.serveradmin.json']), function () {
Route::get('/', "ServerPrivateKeyApiController@getByPage");
Route::post('/', "ServerPrivateKeyApiController@create");
Route::delete('/{id}', "ServerPrivateKeyApiController@delete");
Route::put('/{id}', "ServerPrivateKeyApiController@update");
});
});
});
//OAuth2 Protected API
Route::group(
[
'namespace' => 'App\Http\Controllers\Api\OAuth2',
'prefix' => 'api/v1',
'middleware' => ['api']
], function () {
Route::group(array('prefix' => 'users'), function () {
Route::get('/me', 'OAuth2UserApiController@me');
Route::get('/info', 'OAuth2UserApiController@userInfo');
Route::post('/info', 'OAuth2UserApiController@userInfo');
});
});

21
app/Jobs/Job.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
abstract class Job
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "onQueue" and "delay" queue helper methods.
|
*/
use Queueable;
}

1
app/Listeners/.gitkeep Normal file
View File

@ -0,0 +1 @@

View File

@ -0,0 +1,61 @@
<?php namespace App\Listeners;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use DateTime;
class QueryExecutedListener
{
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param QueryExecuted $event
* @return void
*/
public function handle(QueryExecuted $event)
{
if(Config::get("server.db_log_enabled", false)) {
$query = $event->sql;
$bindings = $event->bindings;
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$bindings[$i] = "'$binding'";
}
}
}
$time = $event->time;
$connection = $event->connectionName;
$data = compact('bindings', 'time', 'connection');
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
Log::info($query, $data);
//trace
/*$trace = '';
$entries = debug_backtrace();
unset($entries[0]);
foreach($entries as $entry){
if(!isset($entry['file']) || !isset($entry['line'])) continue;
$trace .= $entry['file'].' '.$entry['line'].PHP_EOL;
}
Log::debug($trace);*/
}
}
}

27
app/Models/BannedIP.php Normal file
View File

@ -0,0 +1,27 @@
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
/**
* Class BannedIP
* @package Models
*/
class BannedIP extends BaseModelEloquent
{
protected $table = 'banned_ips';
public function user()
{
return $this->belongsTo('Auth\User');
}
}

23
app/Models/Group.php Normal file
View File

@ -0,0 +1,23 @@
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\SilverStripeBaseModel;
/**
* Class Group
* @package Models
*/
class Group extends SilverStripeBaseModel {
protected $table = 'Group';
}

View File

@ -0,0 +1,27 @@
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Db\IBaseRepository;
/**
* Interface IWhiteListedIPRepository
* @package Models
*/
interface IWhiteListedIPRepository extends IBaseRepository
{
/**
* @param string $ip
* @return WhiteListedIP
*/
function getByIp($ip);
}

View File

@ -1,22 +1,36 @@
<?php
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use auth\AuthHelper;
use utils\model\BaseModelEloquent;
use Auth\AuthHelper;
use Exception;
use Utils\Model\SilverStripeBaseModel;
/**
* Class Member
* @package Models
*/
class Member extends BaseModelEloquent
class Member extends SilverStripeBaseModel
{
protected $primaryKey ='ID';
protected $table = 'Member';
//external os members db (SS)
protected $connection = 'os_members';
//no timestamps
public $timestamps = false;
/**
* @param string $password
* @return bool
* @throws Exception
*/
public function checkPassword($password)
{
$hash = AuthHelper::encrypt_password($password, $this->Salt, $this->PasswordEncryption);
@ -26,8 +40,7 @@ class Member extends BaseModelEloquent
public function groups()
{
return $this->belongsToMany('Group', 'Group_Members', 'MemberID', 'GroupID');
return $this->belongsToMany('Models\Group', 'Group_Members', 'MemberID', 'GroupID');
}
/**
@ -38,6 +51,9 @@ class Member extends BaseModelEloquent
return $this->isEmailVerified() && $this->isActive();
}
/**
* @return bool
*/
public function isActive(){
$attr = $this->getAttributes();
if(isset($attr['Active']))

View File

@ -0,0 +1,22 @@
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\SilverStripeBaseModel;
/**
* Class MemberPhoto
* @package Models
*/
class MemberPhoto extends SilverStripeBaseModel
{
protected $table = 'File';
}

View File

@ -0,0 +1,144 @@
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Auth\User;
use OAuth2\Models\IClient;
use Utils\Model\BaseModelEloquent;
use DateTime;
use DateInterval;
use DateTimeZone;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;
/**
* Class AccessToken
* @package Models\OAuth2
*/
class AccessToken extends BaseModelEloquent {
protected $fillable = array
(
'value',
'user_id',
'from_ip',
'associated_authorization_code',
'lifetime',
'scope',
'audience',
'created_at',
'updated_at',
'client_id',
'refresh_token_id'
);
protected $table = 'oauth2_access_token';
private $friendly_scopes;
public function refresh_token()
{
return $this->belongsTo('Models\OAuth2\RefreshToken');
}
/**
* @return RefreshToken
*/
public function getRefreshToken(){
return Cache::remember
(
'refresh_token_'.$this->refresh_token_id,
Config::get("cache_regions.region_refresh_token_lifetime", 1140),
function() {
return $this->refresh_token()->first();
}
);
}
public function client(){
return $this->belongsTo('Models\OAuth2\Client');
}
/**
* @return IClient
*/
public function getClient(){
return Cache::remember
(
'client_'.$this->client_id,
Config::get("cache_regions.region_clients_lifetime", 1140),
function() {
return $this->client()->first();
}
);
}
public function user(){
return $this->belongsTo('Auth\User');
}
/**
* @return User
*/
public function getUser(){
return Cache::remember
(
'user_'.$this->user_id,
Config::get("cache_regions.region_users_lifetime", 1140),
function() {
return $this->user()->first();
}
);
}
/**
* @return bool
*/
public function isVoid(){
//check lifetime...
$created_at = $this->created_at;
$created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S'));
$now = new DateTime(gmdate("Y-m-d H:i:s", time()), new DateTimeZone("UTC"));
return ($now > $created_at);
}
/**
* @return mixed
*/
public function getFriendlyScopes(){
return $this->friendly_scopes;
}
/**
* @param $friendly_scopes
*/
public function setFriendlyScopes($friendly_scopes){
$this->friendly_scopes = $friendly_scopes;
}
/**
* @return int
*/
public function getRemainingLifetime()
{
//check is refresh token is stills alive... (ZERO is infinite lifetime)
if (intval($this->lifetime) == 0) return 0;
$created_at = new DateTime($this->created_at, new DateTimeZone("UTC"));
$created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S'));
$now = new DateTime(gmdate("Y-m-d H:i:s", time()), new DateTimeZone("UTC"));
//check validity...
if ($now > $created_at)
return -1;
$seconds = abs($created_at->getTimestamp() - $now->getTimestamp());;
return $seconds;
}
}

View File

@ -1,8 +1,25 @@
<?php
use oauth2\models\IApi;
use utils\model\BaseModelEloquent;
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
use OAuth2\Models\IApi;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class Api
* @package Models\OAuth2
*/
class Api extends BaseModelEloquent implements IApi
{
@ -32,17 +49,17 @@ class Api extends BaseModelEloquent implements IApi
public function scopes()
{
return $this->hasMany('ApiScope', 'api_id');
return $this->hasMany('Models\OAuth2\ApiScope', 'api_id');
}
public function resource_server()
{
return $this->belongsTo('ResourceServer');
return $this->belongsTo('Models\OAuth2\ResourceServer');
}
public function endpoints()
{
return $this->hasMany('ApiEndpoint', 'api_id');
return $this->hasMany('Models\OAuth2\ApiEndpoint', 'api_id');
}
/**
@ -50,7 +67,14 @@ class Api extends BaseModelEloquent implements IApi
*/
public function getResourceServer()
{
return $this->resource_server()->first();
return Cache::remember
(
'resource_server_'.$this->resource_server_id,
Config::get("cache_regions.region_resource_server_lifetime", 60),
function() {
return $this->resource_server()->first();
}
);
}
public function getName()
@ -64,7 +88,6 @@ class Api extends BaseModelEloquent implements IApi
return $url;
}
public function getDescription()
{
return $this->description;

View File

@ -1,9 +1,23 @@
<?php
use oauth2\models\IApiEndpoint;
use utils\model\BaseModelEloquent;
class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint{
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
use OAuth2\Models\IApiEndpoint;
/**
* Class ApiEndpoint
* @package Models\OAuth2
*/
class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint {
protected $table = 'oauth2_api_endpoint';
@ -27,7 +41,7 @@ class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint{
public function api()
{
return $this->belongsTo('Api');
return $this->belongsTo('Models\OAuth2\Api');
}
public function getRoute()
@ -37,7 +51,7 @@ class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint{
public function scopes()
{
return $this->belongsToMany('ApiScope','oauth2_api_endpoint_api_scope','api_endpoint_id','scope_id');
return $this->belongsToMany('Models\OAuth2\ApiScope','oauth2_api_endpoint_api_scope','api_endpoint_id','scope_id');
}
public function getHttpMethod(){
@ -100,4 +114,13 @@ class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint{
{
return $this->allow_cors;
}
/**
* @return bool
*/
public function supportCredentials()
{
// TODO: Implement supportCredentials() method.
return false;
}
}

View File

@ -1,17 +1,32 @@
<?php
use oauth2\models\IApiScope;
use utils\model\BaseModelEloquent;
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IApi;
use OAuth2\Models\IApiScope;
use Utils\Model\BaseModelEloquent;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;
/**
* Class ApiScope
* @package Models\OAuth2
*/
class ApiScope extends BaseModelEloquent implements IApiScope
{
protected $table = 'oauth2_api_scope';
protected $hidden = array ('created_at', 'updated_at', 'pivot');
protected $fillable = array('name' ,'short_description', 'description','active','default','system', 'api_id', 'assigned_by_groups');
protected $hidden = [ 'created_at', 'updated_at', 'pivot'];
protected $fillable = [ 'name' ,'short_description', 'description','active','default','system', 'api_id', 'assigned_by_groups'];
public function getActiveAttribute(){
return (bool) $this->attributes['active'];
@ -71,33 +86,39 @@ class ApiScope extends BaseModelEloquent implements IApiScope
public function api()
{
return $this->belongsTo('Api');
return $this->belongsTo('Models\OAuth2\Api');
}
/**
* @return IApi
*/
public function getApi(){
return Cache::remember
(
'api_'.$this->api_id,
Config::get("cache_regions.region_api_lifetime", 1140),
function() {
return $this->api()->first();
}
);
}
public function getApiName()
{
$api = $this->api()->first();
$api = $this->getApi();
return !is_null($api)?$api->name:'';
}
public function getApiDescription(){
$api = $this->api()->first();
$api = $this->getApi();
return !is_null($api)? $api->description:'';
}
public function getApiLogo(){
$api = $this->api()->first();
$api = $this->getApi();
return !is_null($api) ? $api->getLogo():asset('/assets/apis/server.png');
}
/**
* @return \oauth2\models\IApi
*/
public function getApi()
{
return $this->api();
}
/**
* @return bool
*/

View File

@ -1,12 +1,6 @@
<?php
use oauth2\models\IApiScope;
use oauth2\models\IOAuth2User;
use utils\model\BaseModelEloquent;
use utils\model\IEntity;
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -17,6 +11,14 @@ use utils\model\IEntity;
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IApiScope;
use OAuth2\Models\IOAuth2User;
use Utils\Model\BaseModelEloquent;
use Utils\Model\IEntity;
/**
* Class ApiScopeGroup
* @package Models
*/
class ApiScopeGroup extends BaseModelEloquent implements IEntity
{
protected $table = 'oauth2_api_scope_group';
@ -25,16 +27,17 @@ class ApiScopeGroup extends BaseModelEloquent implements IEntity
public function scopes()
{
return $this->belongsToMany('ApiScope','oauth2_api_scope_group_scope','group_id','scope_id');
return $this->belongsToMany('Models\OAuth2\ApiScope','oauth2_api_scope_group_scope','group_id','scope_id');
}
public function users()
{
return $this->belongsToMany('auth\User','oauth2_api_scope_group_users','group_id','user_id');
return $this->belongsToMany('Auth\User','oauth2_api_scope_group_users','group_id','user_id');
}
/**
* @param IApiScope $scope
* @return $this
*/
public function addScope(IApiScope $scope)
{
@ -44,6 +47,7 @@ class ApiScopeGroup extends BaseModelEloquent implements IEntity
/**
* @param IOAuth2User $user
* @return $this
*/
public function addUser(IOAuth2User $user)
{
@ -53,6 +57,7 @@ class ApiScopeGroup extends BaseModelEloquent implements IEntity
/**
* @param IOAuth2User $scope
* @return $this
*/
public function removeScope(IOAuth2User $scope)
{
@ -60,6 +65,9 @@ class ApiScopeGroup extends BaseModelEloquent implements IEntity
return $this;
}
/**
* @return $this
*/
public function removeAllScopes()
{
$this->scopes()->detach();
@ -68,6 +76,7 @@ class ApiScopeGroup extends BaseModelEloquent implements IEntity
/**
* @param IOAuth2User $user
* @return $this
*/
public function removeUser(IOAuth2User $user)
{

View File

@ -1,7 +1,6 @@
<?php
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,25 +11,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\model\BaseModelEloquent;
use oauth2\models\IAssymetricKey;
use Utils\Model\BaseModelEloquent;
use OAuth2\Models\IAsymmetricKey;
use jwa\cryptographic_algorithms\ICryptoAlgorithm;
use jwa\cryptographic_algorithms\KeyManagementAlgorithms_Registry;
use jwa\cryptographic_algorithms\DigitalSignatures_MACs_Registry;
use DateTime;
use Exception;
/**
* Class AssymetricKey
* Class AsymmetricKey
*/
abstract class AssymetricKey extends BaseModelEloquent implements IAssymetricKey
abstract class AsymmetricKey extends BaseModelEloquent implements IAsymmetricKey
{
protected $table = 'oauth2_assymetric_keys';
protected $table = 'oauth2_asymmetric_keys';
protected $stiClassField = 'class_name';
protected $stiBaseClass = 'AssymetricKey';
protected $stiBaseClass = \Models\OAuth2\AsymmetricKey::class;
protected $fillable = array(
protected $fillable = array
(
'kid',
'pem_content',
'active',
@ -140,12 +141,12 @@ abstract class AssymetricKey extends BaseModelEloquent implements IAssymetricKey
}
/**
* checks validatiry range with now
* checks validity range with now
* @return bool
*/
public function isExpired()
{
$now = new \DateTime();
$now = new DateTime();
return ( $this->valid_from <= $now && $this->valid_to >= $now);
}

View File

@ -1,20 +1,37 @@
<?php
<?php namespace Models\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use jwa\cryptographic_algorithms\ContentEncryptionAlgorithms_Registry;
use jwa\cryptographic_algorithms\DigitalSignatures_MACs_Registry;
use jwa\cryptographic_algorithms\KeyManagementAlgorithms_Registry;
use oauth2\models\IClient;
use oauth2\models\IClientPublicKey;
use oauth2\models\JWTResponseInfo;
use oauth2\models\TokenEndpointAuthInfo;
use utils\model\BaseModelEloquent;
use oauth2\models\IApiScope;
use OAuth2\Models\IClient;
use OAuth2\Models\IClientPublicKey;
use OAuth2\Models\JWTResponseInfo;
use OAuth2\Models\TokenEndpointAuthInfo;
use Utils\Model\BaseModelEloquent;
use OAuth2\Models\IApiScope;
use Exception;
use DateTime;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class Client
* @package Models
*/
class Client extends BaseModelEloquent implements IClient
{
protected $fillable = array
(
'app_name',
@ -101,7 +118,7 @@ class Client extends BaseModelEloquent implements IClient
*/
public function public_keys()
{
return $this->hasMany('ClientPublicKey','oauth2_client_id','id');
return $this->hasMany('Models\OAuth2\ClientPublicKey','oauth2_client_id','id');
}
/**
@ -109,7 +126,7 @@ class Client extends BaseModelEloquent implements IClient
*/
public function admin_users()
{
return $this->belongsToMany('auth\User','oauth2_client_admin_users','oauth2_client_id','user_id');
return $this->belongsToMany('Auth\User','oauth2_client_admin_users','oauth2_client_id','user_id');
}
/**
@ -140,32 +157,32 @@ class Client extends BaseModelEloquent implements IClient
public function access_tokens()
{
return $this->hasMany('AccessToken');
return $this->hasMany('Models\OAuth2\AccessToken');
}
public function refresh_tokens()
{
return $this->hasMany('RefreshToken');
return $this->hasMany('Models\OAuth2\RefreshToken');
}
public function user()
{
return $this->belongsTo('auth\User');
return $this->belongsTo('Auth\User');
}
public function edited_by()
{
return $this->belongsTo('auth\User','edited_by_id');
return $this->belongsTo('Auth\User','edited_by_id');
}
public function resource_server()
{
return $this->belongsTo('ResourceServer');
return $this->belongsTo('Models\OAuth2\ResourceServer');
}
public function scopes()
{
return $this->belongsToMany('ApiScope','oauth2_client_api_scope','client_id','scope_id');
return $this->belongsToMany('Models\OAuth2\ApiScope','oauth2_client_api_scope','client_id','scope_id');
}
/**
@ -219,13 +236,14 @@ class Client extends BaseModelEloquent implements IClient
public function isScopeAllowed($scope)
{
$res = true;
$res = true;
$desired_scopes = explode(" ",$scope);
foreach($desired_scopes as $desired_scope){
//check if desired scope belongs to application given scopes
$db_scope = $this->scopes()->where('name', '=', $desired_scope)->where('active', '=', true)->first();
$api = !is_null($db_scope)?$db_scope->api()->first():null;
$resource_server = !is_null($api) ? $api->resource_server()->first():null;
$db_scope = $this->getActiveScope($desired_scope);
$api = !is_null($db_scope) ? $db_scope->getApi() : null;
$resource_server = !is_null($api) ? $api->getResourceServer() : null;
if(is_null($db_scope) ||(!is_null($api) && !$api->active) || (!is_null($resource_server) && !$resource_server->active)){
$res = false;
break;
@ -234,6 +252,21 @@ class Client extends BaseModelEloquent implements IClient
return $res;
}
/**
* @param string $name
* @return IApiScope
*/
public function getActiveScope($name){
return Cache::remember
(
'api_scope_'.$this->id.'_'.$name,
Config::get("cache_regions.region_api_scope_lifetime", 1140),
function() use($name){
return $this->scopes()->where('name', '=', $name)->where('active', '=', true)->first();
}
);
}
public function isUriAllowed($uri)
{
if(!filter_var($uri, FILTER_VALIDATE_URL)) return false;
@ -314,7 +347,13 @@ class Client extends BaseModelEloquent implements IClient
public function getResourceServer()
{
return $this->resource_server()->first();
return Cache::remember
(
'resource_server_'.$this->resource_server_id,
Config::get("cache_regions.region_resource_server_lifetime", 60),
function() {
return $this->resource_server()->first();
});
}
public function getApplicationType()
@ -382,16 +421,16 @@ class Client extends BaseModelEloquent implements IClient
}
/**
* @return \DateTime
* @return DateTime
*/
public function getClientSecretExpiration()
{
$exp_date = $this->client_secret_expires_at;
if(is_null($exp_date)) return null;
if($exp_date instanceof \DateTime)
if($exp_date instanceof DateTime)
return $exp_date;
return new \DateTime($exp_date);
return new DateTime($exp_date);
}
/**
@ -399,7 +438,7 @@ class Client extends BaseModelEloquent implements IClient
*/
public function isClientSecretExpired()
{
$now = new \DateTime();
$now = new DateTime();
$exp_date = $this->getClientSecretExpiration();
if(is_null($exp_date)) return false;
@ -610,7 +649,8 @@ class Client extends BaseModelEloquent implements IClient
}
/**
* @param mixed $user
* @param $user
* @return $this
*/
public function addAdminUser($user)
{
@ -619,7 +659,8 @@ class Client extends BaseModelEloquent implements IClient
}
/**
* @param mixed $user
* @param $user
* @return $this
*/
public function removeAdminUser($user)
{
@ -627,6 +668,9 @@ class Client extends BaseModelEloquent implements IClient
return $this;
}
/**
* @return $this
*/
public function removeAllAdminUsers(){
$this->admin_users()->detach();
return $this;
@ -657,6 +701,10 @@ class Client extends BaseModelEloquent implements IClient
return intval($this->user_id) === intval($user->id);
}
/**
* @param $user
* @return $this
*/
public function setOwner($user)
{
$this->user()->associate($user);
@ -693,4 +741,28 @@ class Client extends BaseModelEloquent implements IClient
$user = $this->user()->first();
return is_null($user)? 'N/A':$user->getEmail();
}
/**
* @return bool
*/
public function useRefreshToken()
{
return (bool)$this->use_refresh_token;
}
/**
* @return bool
*/
public function useRotateRefreshTokenPolicy()
{
return (bool)$this->rotate_refresh_token;
}
/**
* @return AccessToken[]
*/
public function getValidAccessTokens()
{
return $this->access_tokens()->whereRaw(" DATE_ADD(created_at, INTERVAL lifetime second) >= UTC_TIMESTAMP() ")->get();
}
}

View File

@ -1,27 +1,25 @@
<?php
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\model\BaseModelEloquent;
use oauth2\models\IClientPublicKey;
use oauth2\models\IClient;
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IClientPublicKey;
use OAuth2\Models\IClient;
use jwk\impl\RSAJWKFactory ;
use jwk\impl\RSAJWKPEMPublicKeySpecification;
use \jwk\IJWK;
use jwk\IJWK;
/**
* Class ClientPublicKey
*/
final class ClientPublicKey extends AssymetricKey implements IClientPublicKey
final class ClientPublicKey extends AsymmetricKey implements IClientPublicKey
{
/**
@ -29,7 +27,7 @@ final class ClientPublicKey extends AssymetricKey implements IClientPublicKey
*/
public function getOwner()
{
return $this->belongsTo('Client');
return $this->belongsTo('Models\OAuth2\Client');
}
/**

View File

@ -0,0 +1,22 @@
<?php namespace Models\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
/**
* Class OAuth2TrailException
* @package Models
*/
class OAuth2TrailException extends BaseModelEloquent
{
protected $table = 'oauth2_exception_trail';
}

View File

@ -0,0 +1,116 @@
<?php namespace Models\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Auth\User;
use Utils\Model\BaseModelEloquent;
use DateInterval;
use DateTime;
use DateTimeZone;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class RefreshToken
* Refresh Token Entity
*/
class RefreshToken extends BaseModelEloquent {
protected $table = 'oauth2_refresh_token';
private $friendly_scopes;
protected $fillable = array('value', 'from_ip', 'lifetime','scope','audience','void','created_at','updated_at','client_id');
public function access_tokens()
{
return $this->hasMany('Models\OAuth2\AccessToken');
}
public function client(){
return $this->belongsTo('Models\OAuth2\Client');
}
/**
* @return IClient
*/
public function getClient(){
return Cache::remember
(
'client_'.$this->client_id,
Config::get("cache_regions.region_clients_lifetime", 1140),
function() {
return $this->client()->first();
}
);
}
public function user(){
return $this->belongsTo('Auth\User');
}
/**
* @return User
*/
public function getUser(){
return Cache::remember
(
'user_'.$this->user_id,
Config::get("cache_regions.region_users_lifetime", 1140),
function() {
return $this->user()->first();
}
);
}
/**
* @return bool
*/
public function isVoid(){
if(intval($this->lifetime) == 0) return false;
//check lifetime...
$created_at = $this->created_at;
$created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S'));
$now = new DateTime(gmdate("Y-m-d H:i:s", time()), new DateTimeZone("UTC"));
return ($now > $created_at);
}
/**
* @return int
*/
public function getRemainingLifetime()
{
//check is refresh token is stills alive... (ZERO is infinite lifetime)
if (intval($this->lifetime) == 0) return 0;
$created_at = new DateTime($this->created_at, new DateTimeZone("UTC"));
$created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S'));
$now = new DateTime(gmdate("Y-m-d H:i:s", time()), new DateTimeZone("UTC"));
//check validity...
if ($now > $created_at)
return -1;
$seconds = abs($created_at->getTimestamp() - $now->getTimestamp());;
return $seconds;
}
public function getFriendlyScopes(){
return $this->friendly_scopes;
}
public function setFriendlyScopes($friendly_scopes){
$this->friendly_scopes = $friendly_scopes;
}
public function setVoid(){
$this->void = true;
}
}

View File

@ -1,10 +1,23 @@
<?php
<?php namespace Models\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use oauth2\models\IResourceServer;
use utils\model\BaseModelEloquent;
use OAuth2\Models\IResourceServer;
use Utils\Model\BaseModelEloquent;
/**
* Class ResourceServer
* @package Models\OAuth2
*/
class ResourceServer extends BaseModelEloquent implements IResourceServer
{
@ -26,12 +39,12 @@ class ResourceServer extends BaseModelEloquent implements IResourceServer
public function apis()
{
return $this->hasMany('Api', 'resource_server_id');
return $this->hasMany('Models\OAuth2\Api', 'resource_server_id');
}
public function client()
{
return $this->hasOne('Client');
return $this->hasOne('Models\OAuth2\Client');
}
/**

View File

@ -1,27 +1,28 @@
<?php
<?php namespace Models\OAuth2;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use jwk\IJWK;
use jwk\impl\RSAJWKFactory;
use jwk\impl\RSAJWKPEMPrivateKeySpecification;
use oauth2\models\IServerPrivateKey;
use OAuth2\Models\IServerPrivateKey;
use DateTime;
use Crypt_RSA;
use Illuminate\Support\Facades\Crypt;
/**
* Class ServerPrivateKey
* @package Models\OAuth2
*/
final class ServerPrivateKey extends AssymetricKey implements IServerPrivateKey
final class ServerPrivateKey extends AsymmetricKey implements IServerPrivateKey
{
/**
* @param array $attributes
@ -82,8 +83,8 @@ final class ServerPrivateKey extends AssymetricKey implements IServerPrivateKey
/**
* @param string $kid
* @param \DateTime $valid_from
* @param \DateTime $valid_to
* @param DateTime $valid_from
* @param DateTime $valid_to
* @param string $type
* @param string $use
* @param bool $active
@ -91,7 +92,18 @@ final class ServerPrivateKey extends AssymetricKey implements IServerPrivateKey
* @param null|string $password
* @return IServerPrivateKey
*/
static function build($kid, \DateTime $valid_from, \DateTime $valid_to, $type, $use, $alg, $active, $pem_content, $password = null)
static function build
(
$kid,
DateTime $valid_from,
DateTime $valid_to,
$type,
$use,
$alg,
$active,
$pem_content,
$password = null
)
{
$key = new self;
$key->kid = $kid;

View File

@ -0,0 +1,59 @@
<?php namespace Models\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IUserConsent;
use Utils\Model\BaseModelEloquent;
use OAuth2\Models\IClient;
use Auth\User;
/**
* Class UserConsent
* @package Models\OAuth2
*/
class UserConsent extends BaseModelEloquent implements IUserConsent {
protected $table = 'oauth2_user_consents';
public function user()
{
return $this->belongsTo('Auth\User');
}
public function client()
{
return $this->belongsTo('Models\OAuth2\Client');
}
/**
* @return string
*/
public function getScope()
{
return $this->scope;
}
/**
* @return IClient
*/
public function getClient()
{
return $this->client()->first();
}
/**
* @return User
*/
public function getUser()
{
return $this->user()->first();
}
}

View File

@ -1,16 +1,35 @@
<?php
use openid\model\IAssociation;
<?php namespace Models\OpenId;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OpenId\Models\IAssociation;
use Utils\Model\BaseModelEloquent;
use DateTime;
use DateTimeZone;
use DateInterval;
/**
* Class OpenIdAssociation
* @package Models\OpenId
*/
class OpenIdAssociation extends Eloquent implements IAssociation
class OpenIdAssociation extends BaseModelEloquent implements IAssociation
{
public $timestamps = false;
protected $table = 'openid_associations';
/**
* @return string
*/
public function getMacFunction()
{
return $this->mac_function;
@ -21,6 +40,9 @@ class OpenIdAssociation extends Eloquent implements IAssociation
// TODO: Implement setMacFunction() method.
}
/**
* @return string
*/
public function getSecret()
{
return $this->secret;

View File

@ -0,0 +1,71 @@
<?php namespace Models\OpenId;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OpenId\Models\ITrustedSite;
use Utils\Model\BaseModelEloquent;
/**
* Class OpenIdTrustedSite
* @package Models\OpenId
*/
class OpenIdTrustedSite extends BaseModelEloquent implements ITrustedSite
{
protected $fillable = array('realm','user_id', 'policy', 'data');
public $timestamps = false;
protected $table = 'openid_trusted_sites';
/**
* @return string
*/
public function getRealm()
{
return $this->realm;
}
public function getUITrustedData()
{
$data = $this->getData();
$str = '';
foreach ($data as $val) {
$str .= $val . ', ';
}
return trim($str, ', ');
}
public function getData()
{
$res = is_null($this->data)?'[]':$this->data;
return json_decode($res);
}
public function getUser()
{
return $this->user();
}
public function user()
{
return $this->belongsTo('Auth\User');
}
/**
* @return string
*/
public function getAuthorizationPolicy()
{
return $this->policy;
}
}

View File

@ -0,0 +1,24 @@
<?php namespace Models\OpenId;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
/**
* Class ServerExtension
* @package Models\OpenId
*/
class ServerExtension extends BaseModelEloquent
{
protected $fillable = array('name', 'namespace', 'active', 'extension_class', 'description', 'view_name');
protected $table = 'server_extensions';
}

View File

@ -0,0 +1,23 @@
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
/**
* Class ServerConfiguration
* @package Models
*/
class ServerConfiguration extends BaseModelEloquent
{
public $timestamps = false;
protected $table = 'server_configuration';
}

View File

@ -1,8 +1,6 @@
<?php
namespace providers;
<?php namespace Models;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,14 +11,18 @@ namespace providers;
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Session\SessionServiceProvider;
use Utils\Model\BaseModelEloquent;
/**
* Class UserAction
* @package Models
*/
class UserAction extends BaseModelEloquent
{
class BehatSessionServiceProvider extends SessionServiceProvider {
protected $table = 'user_actions';
protected function setupDefaultDriver()
public function user()
{
// Do nothing
// Allows command line execution to save sessions
return $this->belongsTo('Auth\User');
}
}

View File

@ -0,0 +1,21 @@
<?php namespace Models;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Model\BaseModelEloquent;
/**
* Class UserExceptionTrail
* @package Models
*/
class UserExceptionTrail extends BaseModelEloquent {
protected $table = 'user_exceptions_trail';
}

View File

@ -1,7 +1,6 @@
<?php
<?php namespace Models;
/**
* Copyright 2015 OpenStack Foundation
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -12,10 +11,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\model\BaseModelEloquent;
use Utils\Model\BaseModelEloquent;
/**
* Class WhiteListedIP
* @package Models
*/
class WhiteListedIP extends BaseModelEloquent
{

1
app/Policies/.gitkeep Normal file
View File

@ -0,0 +1 @@

View File

@ -0,0 +1,70 @@
<?php namespace App\Providers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Monolog\Handler\NativeMailerHandler;
use Illuminate\Support\Facades\Validator;
use Validators\CustomValidator;
/**
* Class AppServiceProvider
* @package App\Providers
*/
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$monolog = Log::getMonolog();
foreach($monolog->getHandlers() as $handler) {
$handler->setLevel(Config::get('log.level', 'error'));
}
//set email log
$to = Config::get('log.to_email');
$from = Config::get('log.from_email');
if (!empty($to) && !empty($from)) {
$subject = 'openstackid error';
$mono_log = Log::getMonolog();
$handler = new NativeMailerHandler($to, $subject, $from);
$handler->setLevel(Config::get('log.email_level', 'error'));
$mono_log->pushHandler($handler);
}
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

View File

@ -0,0 +1,43 @@
<?php namespace App\Providers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
/**
* Class AuthServiceProvider
* @package App\Providers
*/
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
//
}
}

View File

@ -0,0 +1,56 @@
<?php namespace App\Providers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Auth;
use App;
use Illuminate\Support\ServiceProvider;
use Auth\CustomAuthProvider as AuthProvider;
use OpenId\Services\OpenIdServiceCatalog;
use Utils\Services\UtilsServiceCatalog;
/**
* Class CustomAuthProvider
* @package App\Providers
*/
class CustomAuthProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
Auth::provider('custom', function($app, array $config) {
// Return an instance of Illuminate\Contracts\Auth\UserProvider...
return new AuthProvider(
App::make(\Auth\Repositories\IUserRepository::class),
App::make(\Auth\Repositories\IMemberRepository::class),
App::make(\Auth\IAuthenticationExtensionService::class),
App::make(OpenIdServiceCatalog::UserService),
App::make(UtilsServiceCatalog::CheckPointService),
App::make(UtilsServiceCatalog::TransactionService),
App::make(UtilsServiceCatalog::LogService)
);
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}

View File

@ -0,0 +1,45 @@
<?php namespace App\Providers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
/**
* Class EventServiceProvider
* @package App\Providers
*/
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Illuminate\Database\Events\QueryExecuted' => [
'App\Listeners\QueryExecutedListener',
],
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}

View File

@ -0,0 +1,48 @@
<?php namespace Providers\OAuth2;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\App;
use OAuth2\Strategies\ClientAuthContextValidatorFactory;
/**
* Class ClientAuthContextValidatorFactoryProvider
* @package Providers\OAuth2
*/
final class ClientAuthContextValidatorFactoryProvider extends ServiceProvider
{
public function boot()
{
ClientAuthContextValidatorFactory::setTokenEndpointUrl
(
URL::action('OAuth2\OAuth2ProviderController@token')
);
ClientAuthContextValidatorFactory::setJWKSetReader
(
App::make(\OAuth2\Services\IClientJWKSetReader::class)
);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// TODO: Implement register() method.
}
}

View File

@ -0,0 +1,53 @@
<?php namespace App\Providers;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
/**
* Class RouteServiceProvider
* @package App\Providers
*/
final class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
require app_path('Http/routes.php');
}
}

View File

@ -0,0 +1,86 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Cache;
use Utils\Model\IEntity;
/**
* Class AbstractCacheOAuth2TokenRepository
* @package Repositories
*/
abstract class AbstractCacheOAuth2TokenRepository extends BaseCacheRepository
{
function add(IEntity $entity)
{
Cache::forget($this->cache_base_key.'_'.$entity->value);
return parent::add($entity);
}
function update(IEntity $entity)
{
Cache::forget($this->cache_base_key.'_'.$entity->value);
return parent::update($entity);
}
function delete(IEntity $entity)
{
Cache::forget($this->cache_base_key.'_'.$entity->value);
return parent::delete($entity);
}
/**
* @param int $client_identifier
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
function getAllByClientIdentifier($client_identifier, $page_nbr = 1, $page_size = 10)
{
return $this->repository->getAllByClientIdentifier($client_identifier, $page_nbr, $page_size);
}
/**
* @param int $client_identifier
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
function getAllValidByClientIdentifier($client_identifier, $page_nbr = 1, $page_size = 10)
{
return $this->repository->getAllValidByClientIdentifier($client_identifier, $page_nbr, $page_size );
}
/**
* @param int $user_id
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
function getAllByUserId($user_id, $page_nbr = 1, $page_size = 10)
{
return $this->repository->getAllByUserId($user_id, $page_nbr, $page_size);
}
/**
* @param int $user_id
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
function getAllValidByUserId($user_id, $page_nbr = 1, $page_size = 10)
{
return $this->repository->getAllValidByUserId($user_id, $page_nbr, $page_size);
}
}

View File

@ -1,4 +1,4 @@
<?php
<?php namespace Repositories;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -11,16 +11,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
namespace repositories;
use DB;
use utils\model\IEntity;
use utils\db\IBaseRepository;
use Utils\Model\IEntity;
use Utils\Db\IBaseRepository;
/**
* Class AbstractEloquentEntityRepository
* @package repositories
* @package Repositories
*/
abstract class AbstractEloquentEntityRepository implements IBaseRepository
{
@ -30,15 +25,15 @@ abstract class AbstractEloquentEntityRepository implements IBaseRepository
protected $entity;
/**
* @param int $page_size
* @param int $page_nbr
* @param int $page_size
* @param array $filters
* @param array $fields
* @return mixed
*/
public function getAll($page_nbr = 1, $page_size = 10, array $filters = array(), array $fields = array('*'))
{
DB::getPaginator()->setCurrentPage($page_nbr);
return $this->entity->Filter($filters)->paginate($page_size, $fields);
return $this->entity->Filter($filters)->paginate($page_size, $fields, $pageName = 'Page', $page_nbr);
}
/**
@ -47,7 +42,7 @@ abstract class AbstractEloquentEntityRepository implements IBaseRepository
*/
public function update(IEntity $entity)
{
return $entity->Save();
return $entity->save();
}
/**

View File

@ -0,0 +1,80 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/**
* Class AbstractEloquentOAuth2TokenRepository
* @package Repositories
*/
abstract class AbstractEloquentOAuth2TokenRepository extends AbstractEloquentEntityRepository
{
/**
* @param int $client_identifier
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
public function getAllByClientIdentifier($client_identifier, $page_nbr = 1, $page_size = 10){
return $this->getAll($page_nbr, $page_size, [['name' => 'client_id', 'op' => '=','value' => $client_identifier]]);
}
/**
* @param int $user_id
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
public function getAllByUserId($user_id, $page_nbr = 1, $page_size = 10){
return $this->getAll($page_nbr, $page_size, [['name' => 'user_id', 'op' => '=','value' => $user_id]]);
}
/**
* @param int $client_identifier
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
function getAllValidByClientIdentifier($client_identifier, $page_nbr = 1, $page_size = 10)
{
return $this->getAll($page_nbr, $page_size, [
['name' => 'client_id', 'op' => '=','value' => $client_identifier ],
['raw' => 'DATE_ADD(created_at, INTERVAL lifetime second) >= UTC_TIMESTAMP()'],
]);
}
/**
* @param int $user_id
* @param int $page_nbr
* @param int $page_size
* @return LengthAwarePaginator
*/
function getAllValidByUserId($user_id, $page_nbr = 1, $page_size = 10)
{
return $this->getAll($page_nbr, $page_size, [
['name' => 'user_id', 'op' => '=','value' => $user_id ],
['raw' => 'DATE_ADD(created_at, INTERVAL lifetime second) >= UTC_TIMESTAMP()'],
]);
}
/**
* @param $hashed_value
* @return mixed
*/
function getByValue($hashed_value)
{
return $this->entity->where('value', '=', $hashed_value)->first();
}
}

View File

@ -0,0 +1,98 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Utils\Db\IBaseRepository;
use Utils\Model\IEntity;
use Illuminate\Support\Facades\Cache;
/**
* Class BaseCacheRepository
* @package Repositories
*/
abstract class BaseCacheRepository implements IBaseRepository
{
/**
* @var IBaseRepository
*/
protected $repository;
/**
* @var string
*/
protected $cache_base_key;
/**
* @var int
*/
protected $cache_minutes_lifetime;
/**
* BaseCacheRepository constructor.
* @param IBaseRepository $repository
*/
public function __construct(IBaseRepository $repository)
{
$this->repository = $repository;
}
/**
* @param int $id
* @return IEntity
*/
public function get($id)
{
return Cache::remember($this->cache_base_key.'_'.$id, $this->cache_minutes_lifetime, function() use($id) {
return $this->repository->get($id);
});
}
/**
* @param int $page_nbr
* @param int $page_size
* @param array $filters
* @param array $fields
* @return mixed
*/
public function getAll($page_nbr = 1, $page_size = 10, array $filters = [], array $fields = ['*'])
{
return $this->repository->getAll($page_nbr, $page_size, $filters, $fields);
}
/**
* @param IEntity $entity
* @return bool
*/
public function update(IEntity $entity)
{
return $this->repository->update($entity);
}
/**
* @param IEntity $entity
* @return bool
*/
public function add(IEntity $entity)
{
return $this->repository->add($entity);
}
/**
* @param IEntity $entity
* @return bool
*/
public function delete(IEntity $entity)
{
return $this->repository->delete($entity);
}
}

View File

@ -0,0 +1,69 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Config;
use Models\OAuth2\AccessToken;
use OAuth2\Repositories\IAccessTokenRepository;
use Illuminate\Support\Facades\Cache;
/**
* Class CacheAccessTokenRepository
* @package Repositories
*/
final class CacheAccessTokenRepository extends AbstractCacheOAuth2TokenRepository implements IAccessTokenRepository
{
/**
* CacheAccessTokenRepository constructor.
* @param EloquentAccessTokenRepository $repository
*/
public function __construct(EloquentAccessTokenRepository $repository)
{
$this->cache_base_key = 'access_token';
$this->cache_minutes_lifetime = Config::get("cache_regions.region_access_token_lifetime", 1140);
parent::__construct($repository);
}
/**
* @param string $hashed_value
* @return AccessToken
*/
function getByValue($hashed_value)
{
return Cache::remember($this->cache_base_key.'_'.$hashed_value, $this->cache_minutes_lifetime, function() use($hashed_value) {
return $this->repository->getByValue($hashed_value);
});
}
/**
* @param string $hashed_value
* @return AccessToken
*/
function getByAuthCode($hashed_value)
{
return Cache::remember($this->cache_base_key.'_'.$hashed_value, $this->cache_minutes_lifetime, function() use($hashed_value) {
return $this->repository->getByAuthCode($hashed_value);
});
}
/**
* @param int $refresh_token_id
* @return AccessToken[]
*/
function getByRefreshToken($refresh_token_id)
{
return $this->repository->getByRefreshToken($refresh_token_id);
}
}

View File

@ -0,0 +1,68 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IApiEndpoint;
use OAuth2\Repositories\IApiEndpointRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class CacheApiEndpointRepository
* @package Repositories
*/
final class CacheApiEndpointRepository extends BaseCacheRepository implements IApiEndpointRepository
{
public function __construct(EloquentApiEndpointRepository $repository)
{
$this->cache_base_key = 'api_endpoint';
$this->cache_minutes_lifetime = Config::get("cache_regions.region_api_endpoint_lifetime", 1140);
parent::__construct($repository);
}
/**
* @param string $url
* @param string $http_method
* @return IApiEndpoint
*/
public function getApiEndpointByUrlAndMethod($url, $http_method)
{
return Cache::remember($this->cache_base_key.'_'.$url.'_'.$http_method, $this->cache_minutes_lifetime, function() use($url, $http_method) {
return $this->repository->getApiEndpointByUrlAndMethod($url, $http_method);
});
}
/**
* @param string $url
* @param string $http_method
* @param int $api_id
* @return IApiEndpoint
*/
public function getApiEndpointByUrlAndMethodAndApi($url, $http_method, $api_id)
{
return Cache::remember($this->cache_base_key.'_'.$url.'_'.$http_method.'_'.$api_id, $this->cache_minutes_lifetime, function() use($url, $http_method, $api_id) {
return $this->repository->getApiEndpointByUrlAndMethodAndApi($url, $http_method, $api_id);
});
}
/**
* @param string $url
* @return IApiEndpoint
*/
public function getApiEndpointByUrl($url)
{
return Cache::remember($this->cache_base_key.'_'.$url, $this->cache_minutes_lifetime, function() use($url) {
return $this->repository->getApiEndpointByUrl($url);
});
}
}

View File

@ -0,0 +1,55 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IApi;
use OAuth2\Repositories\IApiRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class CacheApiRepository
* @package Repositories
*/
final class CacheApiRepository extends BaseCacheRepository implements IApiRepository
{
public function __construct(EloquentApiRepository $repository)
{
$this->cache_base_key = 'api';
$this->cache_minutes_lifetime = Config::get("cache_regions.region_api_lifetime", 1140);
parent::__construct($repository);
}
/**
* @param string $api_name
* @return IApi
*/
public function getByName($api_name)
{
return Cache::remember($this->cache_base_key.'_'.$api_name, $this->cache_minutes_lifetime, function() use($api_name) {
return $this->repository->getByName($api_name);
});
}
/**
* @param string $api_name
* @param int $resource_server_id
* @return IApi
*/
public function getByNameAndResourceServer($api_name, $resource_server_id)
{
return Cache::remember($this->cache_base_key.'_'.$api_name.'_'.$resource_server_id, $this->cache_minutes_lifetime, function() use($api_name, $resource_server_id) {
return $this->repository->getByNameAndResourceServer($api_name, $resource_server_id);
});
}
}

View File

@ -0,0 +1,73 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IApiScope;
use OAuth2\Repositories\IApiScopeRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class CacheApiScopeRepository
* @package Repositories
*/
final class CacheApiScopeRepository extends BaseCacheRepository implements IApiScopeRepository
{
public function __construct(EloquentApiScopeRepository $repository)
{
$this->cache_base_key = 'api_scope';
$this->cache_minutes_lifetime = $this->cache_minutes_lifetime = Config::get("cache_regions.region_api_scope_lifetime", 1140);
parent::__construct($repository);
}
/**
* @param array $scopes_names
* @return IApiScope[]
*/
public function getByName(array $scopes_names)
{
return Cache::remember($this->cache_base_key.'_'.join('_', $scopes_names), $this->cache_minutes_lifetime, function() use($scopes_names) {
return $this->repository->getByName($scopes_names);
});
}
/**
* @return IApiScope[]
*/
public function getDefaults()
{
return Cache::remember($this->cache_base_key.'_defaults', $this->cache_minutes_lifetime, function() {
return $this->repository->getDefaults();
});
}
/**
* @return IApiScope[]
*/
public function getActives()
{
return Cache::remember($this->cache_base_key.'_actives', $this->cache_minutes_lifetime, function() {
return $this->repository->getActives();
});
}
/**
* @return IApiScope[]
*/
public function getAssignableByGroups()
{
return Cache::remember($this->cache_base_key.'_assignables_by_groups', $this->cache_minutes_lifetime, function() {
return $this->repository->getAssignableByGroups();
});
}
}

View File

@ -0,0 +1,77 @@
<?php namespace Repositories;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use OAuth2\Models\IClient;
use OAuth2\Repositories\IClientRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
/**
* Class CacheClientRepository
* @package Repositories
*/
final class CacheClientRepository extends BaseCacheRepository implements IClientRepository
{
public function __construct(EloquentClientRepository $repository)
{
$this->cache_base_key = 'client';
$this->cache_minutes_lifetime = Config::get("cache_regions.region_clients_lifetime", 1140);
parent::__construct($repository);
}
/**
* @param string $app_name
* @return IClient
*/
public function getByApplicationName($app_name)
{
return Cache::remember($this->cache_base_key.'_'.$app_name, $this->cache_minutes_lifetime, function() use($app_name) {
return $this->repository->getByApplicationName($app_name);
});
}
/**
* @param string $client_id
* @return IClient
*/
public function getClientById($client_id)
{
return Cache::remember($this->cache_base_key.'_'.$client_id, $this->cache_minutes_lifetime, function() use($client_id) {
return $this->repository->getClientById($client_id);
});
}
/**
* @param int $id
* @return IClient
*/
public function getClientByIdentifier($id)
{
return Cache::remember($this->cache_base_key.'_'.$id, $this->cache_minutes_lifetime, function() use($id) {
return $this->repository->getClientByIdentifier($id);
});
}
/**
* @param string $origin
* @return IClient
*/
public function getByOrigin($origin)
{
return Cache::remember($this->cache_base_key.'_'.$origin, $this->cache_minutes_lifetime, function() use($origin) {
return $this->repository->getByOrigin($origin);
});
}
}

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