Summit Application API

WIP - Added Summit API

Change-Id: I5494db9414809a3ca5e278919d084e895b2ed05a
This commit is contained in:
Sebastian Marcet 2015-09-09 18:14:28 -03:00
parent 4d7159e93f
commit a093fc5a01
141 changed files with 11173 additions and 2255 deletions

View File

@ -43,4 +43,10 @@ CORS_EXPOSED_HEADERS=
CURL_TIMEOUT=60
CURL_ALLOWS_REDIRECT=false
CURL_VERIFY_SSL_CERT=true
CURL_VERIFY_SSL_CERT=true
SSL_ENABLED=false
OAUTH2_ENABLED=true
DB_LOG_ENABLED=false
ASSETS_BASE_URL=http://www.openstack.org
API_RESPONSE_CACHE_LIFETIME=10000

View File

@ -12,7 +12,7 @@ DB_USERNAME=root
DB_PASSWORD=Koguryo@1981
SS_DB_HOST=localhost
SS_DATABASE=os_local
SS_DATABASE=os_production2
SS_DB_USERNAME=root
SS_DB_PASSWORD=Koguryo@1981
@ -47,4 +47,6 @@ CORS_EXPOSED_HEADERS=
CURL_TIMEOUT=3600
CURL_ALLOWS_REDIRECT=false
CURL_VERIFY_SSL_CERT=false
CURL_VERIFY_SSL_CERT=false
DB_LOG_ENABLED=true
ASSETS_BASE_URL=http://www.openstack.org/

6
.gitignore vendored
View File

@ -1,6 +1,5 @@
/vendor
/node_modules
.env
composer.phar
composer.lock
.DS_Storeapp/storage
@ -23,6 +22,5 @@ ChangeLog
doc/build
*.egg
*.egg-info
.env.testing
.env.testing
.env

View File

@ -0,0 +1,45 @@
<?php namespace App\Events;
use Illuminate\Queue\SerializesModels;
use models\summit\SummitAttendee;
/**
* Class MyScheduleAdd
* @package App\Events
*/
class MyScheduleAdd extends Event
{
use SerializesModels;
/**
* @var SummitAttendee
*/
protected $attendee;
/**
* @var int
*/
protected $event_id;
/**
* MyScheduleAdd constructor.
* @param SummitAttendee $attendee
* @param int $event_id
*/
function __construct(SummitAttendee $attendee, $event_id)
{
$this->attendee = $attendee;
$this->event_id = $event_id;
}
/**
* @return SummitAttendee
*/
public function getAttendee(){ return $this->attendee;}
/**
* @return int
*/
public function getEventId(){ return $this->event_id;}
}

View File

@ -0,0 +1,12 @@
<?php namespace App\Events;
use Illuminate\Queue\SerializesModels;
/**
* Class MyScheduleRemove
* @package App\Events
*/
class MyScheduleRemove extends MyScheduleAdd
{
use SerializesModels;
}

View File

@ -3,40 +3,40 @@
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler {
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* A list of the exception types that should not be reported.
* @var array
*/
protected $dontReport = [
'Symfony\Component\HttpKernel\Exception\HttpException'
];
/**
* 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)
{
return parent::report($e);
}
/**
* 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)
{
return 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);
}
/**
* 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)
{
if (config('app.debug')) {
return parent::render($request, $e);
}
return response()->view('errors.404', [], 404);
}
}

View File

@ -1,99 +1,124 @@
<?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.
**/
/**
* 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\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use Exception;
/**
* Class JsonController
* @package App\Http\Controllers
*/
* Class JsonController
* @package App\Http\Controllers
*/
abstract class JsonController extends Controller
{
protected $log_service;
protected $log_service;
public function __construct()
{
}
public function __construct()
{
}
protected function error500(Exception $ex)
{
Log::error($ex);
return Response::json(array('message' => 'server error'), 500);
}
protected function error500(Exception $ex)
{
Log::error($ex);
protected function created($data = 'ok')
{
$res = Response::json($data, 201);
//jsonp
if (Input::has('callback'))
{
$res->setCallback(Input::get('callback'));
}
return $res;
}
return Response::json(array('message' => 'server error'), 500);
}
protected function deleted($data = 'ok')
{
$res = Response::json($data, 204);
//jsonp
if (Input::has('callback'))
{
$res->setCallback(Input::get('callback'));
}
return $res;
}
protected function created($data = 'ok')
{
$res = Response::json($data, 201);
//jsonp
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
}
protected function ok($data = 'ok')
{
$res = Response::json($data, 200);
//jsonp
if (Input::has('callback'))
{
$res->setCallback(Input::get('callback'));
}
return $res;
}
return $res;
}
protected function error400($data)
{
return Response::json($data, 400);
}
protected function deleted($data = 'ok')
{
$res = Response::json($data, 204);
//jsonp
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
}
protected function error404($data = array('message' => 'Entity Not Found'))
{
return Response::json($data, 404);
}
return $res;
}
/**
* {
"message": "Validation Failed",
"errors": [
{
"resource": "Issue",
"field": "title",
"code": "missing_field"
}
]
}
* @param $messages
* @return mixed
*/
protected function error412($messages)
{
return Response::json(array('message' => 'Validation Failed', 'errors' => $messages), 412);
}
protected function updated($data = 'ok')
{
$res = Response::json($data, 204);
//jsonp
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
}
return $res;
}
protected function ok($data = 'ok')
{
$res = Response::json($data, 200);
//jsonp
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
}
return $res;
}
protected function error400($data)
{
return Response::json($data, 400);
}
protected function error404($data = array('message' => 'Entity Not Found'))
{
return Response::json($data, 404);
}
protected function error403($data = array('message' => 'Forbidden'))
{
return Response::json($data, 403);
}
protected function error401($data = array('message' => 'You don\'t have access to this item through the API.'))
{
return Response::json($data, 401);
}
/**
* {
* "message": "Validation Failed",
* "errors": [
* {
* "resource": "Issue",
* "field": "title",
* "code": "missing_field"
* }
* ]
* }
* @param $messages
* @return mixed
*/
protected function error412($messages)
{
return Response::json(array('message' => 'Validation Failed', 'errors' => $messages), 412);
}
}

View File

@ -1,40 +1,45 @@
<?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.
**/
* 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 models\oauth2\IResourceServerContext;
use models\utils\IBaseRepository;
/**
* Class OAuth2ProtectedController
* OAuth2 Protected Base API
*/
* Class OAuth2ProtectedController
* OAuth2 Protected Base API
*/
abstract class OAuth2ProtectedController extends JsonController
{
/**
* @var IResourceServerContext
*/
protected $resource_server_context;
/**
* @var IResourceServerContext
*/
protected $resource_server_context;
protected $repository;
/**
* @var IBaseRepository
*/
protected $repository;
/**
* @param IResourceServerContext $resource_server_context
*/
public function __construct(IResourceServerContext $resource_server_context)
{
parent::__construct();
$this->resource_server_context = $resource_server_context;
}
/**
* @param IResourceServerContext $resource_server_context
*/
public function __construct(IResourceServerContext $resource_server_context)
{
parent::__construct();
$this->resource_server_context = $resource_server_context;
}
}

View File

@ -0,0 +1,51 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
/**
* Class CheckAttendeeStrategyFactory
* @package App\Http\Controllers
*/
final class CheckAttendeeStrategyFactory
{
const Me = 'me';
const Own = 'own';
/**
* @param string $type
* @param IResourceServerContext $resource_server_context
* @return ICheckAttendeeStrategy|null
*/
public static function build($type, IResourceServerContext $resource_server_context)
{
$strategy = null;
switch(strtolower($type))
{
case 'me':
$strategy = new CheckMeAttendeeStrategy($resource_server_context);
break;
case 'own':
$strategy = new CheckMyOwnAttendeeStrategy($resource_server_context);
break;
default:
throw new \InvalidArgumentException('not recognized type!');
break;
}
return $strategy;
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
/**
* Class CheckSpeakerStrategyFactory
* @package App\Http\Controllers
*/
final class CheckSpeakerStrategyFactory
{
const Me = 'me';
const Own = 'own';
/**
* @param string $type
* @param IResourceServerContext $resource_server_context
* @return ICheckSpeakerStrategy|null
*/
public static function build($type, IResourceServerContext $resource_server_context){
$strategy = null;
switch(strtolower($type))
{
case 'me':
$strategy = new CheckMeSpeakerStrategy($resource_server_context);
break;
default:
throw new \InvalidArgumentException('not recognized type!');
break;
}
return $strategy;
}
}

View File

@ -0,0 +1,32 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\summit\Summit;
use models\summit\SummitAttendee;
/**
* Interface ICheckAttendeeStrategy
* @package App\Http\Controllers
*/
interface ICheckAttendeeStrategy
{
/**
* @param mixed $attendee_id
* @param Summit $summit
* @return null|SummitAttendee
*/
public function check($attendee_id, Summit $summit);
}

View File

@ -0,0 +1,32 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\summit\PresentationSpeaker;
use models\summit\Summit;
/**
* Interface ICheckSpeakerStrategy
* @package App\Http\Controllers
*/
interface ICheckSpeakerStrategy
{
/**
* @param mixed $speaker_id
* @param Summit $summit
* @return null|PresentationSpeaker
*/
public function check($speaker_id, Summit $summit);
}

View File

@ -0,0 +1,30 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\summit\Summit;
/**
* Interface ISummitFinderStrategy
* @package App\Http\Controllers
*/
interface ISummitFinderStrategy
{
/**
* @param mixed $summit_id
* @return null|Summit
*/
public function find($summit_id);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,33 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\utils\IBaseRepository;
/**
* Class SummitFinderStrategyFactory
* @package App\Http\Controllers
*/
final class SummitFinderStrategyFactory
{
/**
* @param IBaseRepository $repository
* @return ISummitFinderStrategy
*/
public static function build(IBaseRepository $repository)
{
return new CurrentSummitFinderStrategy($repository);
}
}

View File

@ -0,0 +1,60 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
use models\summit\Summit;
use models\summit\SummitAttendee;
/**
* Class CheckMeAttendeeStrategy
* @package App\Http\Controllers
*/
class CheckMeAttendeeStrategy implements ICheckAttendeeStrategy
{
/**
* @var IResourceServerContext
*/
protected $resource_server_context;
/**
* CheckMeAttendeeStrategy constructor.
* @param IResourceServerContext $resource_server_context
*/
public function __construct(IResourceServerContext $resource_server_context)
{
$this->resource_server_context = $resource_server_context;
}
/**
* @param $attendee_id
* @param Summit $summit
* @return null|SummitAttendee
*/
public function check($attendee_id, Summit $summit)
{
if (strtolower($attendee_id) === 'me') {
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if (is_null($member_id)) {
return null;
}
$attendee = $summit->getAttendeeByMemberId($member_id);
} else {
$attendee = $summit->getAttendeeById(intval($attendee_id));
}
return $attendee;
}
}

View File

@ -0,0 +1,60 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
use models\summit\PresentationSpeaker;
use models\summit\Summit;
/**
* Class CheckMeSpeakerStrategy
* @package App\Http\Controllers
*/
class CheckMeSpeakerStrategy implements ICheckSpeakerStrategy
{
/**
* @var IResourceServerContext
*/
protected $resource_server_context;
/**
* CheckMeAttendeeStrategy constructor.
* @param IResourceServerContext $resource_server_context
*/
public function __construct(IResourceServerContext $resource_server_context)
{
$this->resource_server_context = $resource_server_context;
}
/**
* @param mixed $speaker_id
* @param Summit $summit
* @return null|PresentationSpeaker
*/
public function check($speaker_id, Summit $summit)
{
if (strtolower($speaker_id) === 'me') {
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if (is_null($member_id)) {
return $this->error404();
}
$speaker = $summit->getSpeakerByMemberId($member_id);
} else {
$speaker = $summit->getSpeakerById(intval($speaker_id));
}
return $speaker;
}
}

View File

@ -0,0 +1,43 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\oauth2\IResourceServerContext;
use models\summit\Summit;
use models\summit\SummitAttendee;
/**
* Class CheckMyOwnAttendeeStrategy
* @package App\Http\Controllers
*/
final class CheckMyOwnAttendeeStrategy extends CheckMeAttendeeStrategy implements ICheckAttendeeStrategy
{
/**
* @param int $attendee_id
* @param Summit $summit
* @return null|SummitAttendee
* @throws \HTTP401UnauthorizedException
*/
public function check($attendee_id, Summit $summit)
{
$attendee = parent::check($attendee_id, $summit);
if(!$attendee) return null;
$attendee_member_id = intval($attendee->member()->ID);
$member_id = $this->resource_server_context->getCurrentUserExternalId();
if(is_null($member_id) || ($attendee_member_id !== $member_id)) throw new \HTTP401UnauthorizedException;
return $attendee;
}
}

View File

@ -0,0 +1,46 @@
<?php
/**
* 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.
**/
namespace App\Http\Controllers;
use models\summit\Summit;
use repositories\summit\EloquentSummitRepository;
/**
* Class CurrentSummitFinderStrategy
* @package App\Http\Controllers
*/
class CurrentSummitFinderStrategy implements ISummitFinderStrategy
{
/**
* @var EloquentSummitRepository
*/
private $repository;
public function __construct(EloquentSummitRepository $repository)
{
$this->repository = $repository;
}
/**
* @param mixed $summit_id
* @return null|Summit
*/
public function find($summit_id)
{
$summit = $summit_id === 'current' ? $this->repository->getCurrent() : $this->repository->getById(intval($summit_id));
return $summit;
}
}

View File

@ -0,0 +1,18 @@
<?php
/**
* 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.
**/
final class HTTP401UnauthorizedException extends Exception
{
}

View File

@ -2,36 +2,35 @@
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\CORSMiddleware',
'App\Http\Middleware\SecurityHTTPHeadersWriterMiddleware',
];
/**
* The application's global HTTP middleware stack.
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\CORSMiddleware',
'App\Http\Middleware\SecurityHTTPHeadersWriterMiddleware',
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'oauth2.protected' => 'App\Http\Middleware\OAuth2BearerAccessTokenRequestValidator',
'rate.limit' => 'App\Http\Middleware\RateLimitMiddleware',
'etags' => 'App\Http\Middleware\ETagsMiddleware',
];
/**
* The application's route middleware.
* @var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'oauth2.protected' => 'App\Http\Middleware\OAuth2BearerAccessTokenRequestValidator',
'rate.limit' => 'App\Http\Middleware\RateLimitMiddleware',
'etags' => 'App\Http\Middleware\ETagsMiddleware',
'cache' => 'App\Http\Middleware\CacheMiddleware',
];
}

View File

@ -0,0 +1,118 @@
<?php
/**
* 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.
**/
namespace App\Http\Middleware;
use Closure;
use Config;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Http\JsonResponse;
use libs\utils\ICacheService;
use Log;
use models\oauth2\IResourceServerContext;
/**
* Class CacheMiddleware
* @package App\Http\Middleware
*/
final class CacheMiddleware implements Middleware
{
/**
* @var ICacheService
*/
private $cache_service;
/**
* @var IResourceServerContext
*/
private $context;
public function __construct(IResourceServerContext $context, ICacheService $cache_service)
{
$this->context = $context;
$this->cache_service = $cache_service;
}
/**
* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->getMethod() !== 'GET')
{
// shortcircuit
return $next($request);
}
$key = $request->getPathInfo();
$query = $request->getQueryString();
$current_time = time();
if(!empty($query))
{
$query = explode('&', $query);
foreach($query as $q)
{
$q = explode('=',$q);
if(strtolower($q[0]) === 'access_token'|| strtolower($q[0]) === 'token_type' ) continue;
$key .= ".".implode("=",$q);
}
}
$cache_lifetime = intval(Config::get('server.response_cache_lifetime', 300));
if (str_contains($request->getPathInfo(), '/me'))
{
$key .= ':' . $this->context->getCurrentUserExternalId();
}
$data = $this->cache_service->getSingleValue($key);
$time = $this->cache_service->getSingleValue($key.".generated");
if (empty($data) || empty($time))
{
$time = $current_time;
Log::debug(sprintf("cache value not found for key %s , getting from api...", $key));
// normal flow ...
$response = $next($request);
if ($response instanceof JsonResponse && $response->getStatusCode() === 200)
{
// and if its json, store it on cache ...
$data = $response->getData(true);
$this->cache_service->setSingleValue($key, json_encode($data), $cache_lifetime);
$this->cache_service->setSingleValue($key.".generated", $time, $cache_lifetime);
}
}
else
{
// cache hit ...
Log::debug(sprintf("cache hit for %s ...", $key));
$response = new JsonResponse(json_decode($data, true), 200, array
(
'content-type' => 'application/json',
)
);
}
$response->headers->set('xcontent-timestamp', $time);
$response->headers->set('Cache-Control', sprintf('private, max-age=%s', $cache_lifetime));
$response->headers->set('Expires', gmdate('D, d M Y H:i:s \G\M\T', $time + $cache_lifetime));
return $response;
}
}

View File

@ -1,44 +1,53 @@
<?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.
**/
* 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\Contracts\Routing\Middleware;
use Log;
class ETagsMiddleware implements Middleware
/**
* Class ETagsMiddleware
* @package App\Http\Middleware
*/
final class ETagsMiddleware implements Middleware
{
/**
* 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)
{
$etag = md5($response->getContent());
$requestETag = str_replace('"', '', $request->getETags());
if ($requestETag && $requestETag[0] == $etag)
{
$response->setNotModified();
}
$response->setEtag($etag);
}
return $response;
}
/**
* 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

@ -1,286 +1,277 @@
<?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.
**/
* 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\Contracts\Routing\Middleware;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use models\oauth2\IResourceServerContext;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use libs\oauth2\OAuth2Protocol;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use libs\oauth2\BearerAccessTokenAuthorizationHeaderParser;
use libs\oauth2\OAuth2ResourceServerException;
use libs\oauth2\InvalidGrantTypeException;
use libs\oauth2\OAuth2Protocol;
use libs\oauth2\OAuth2ResourceServerException;
use libs\oauth2\OAuth2WWWAuthenticateErrorResponse;
use models\resource_server\IApiEndpointRepository;
use models\resource_server\IAccessTokenService;
use libs\utils\RequestUtils;
use models\oauth2\IResourceServerContext;
use models\resource_server\IAccessTokenService;
use models\resource_server\IApiEndpointRepository;
use URL\Normalizer;
/**
* Class OAuth2BearerAccessTokenRequestValidator
* http://tools.ietf.org/html/rfc6749#section-7
* @package App\Http\Middleware
*/
class OAuth2BearerAccessTokenRequestValidator implements Middleware {
* Class OAuth2BearerAccessTokenRequestValidator
* http://tools.ietf.org/html/rfc6749#section-7
* @package App\Http\Middleware
*/
class OAuth2BearerAccessTokenRequestValidator implements Middleware
{
/**
* @var IResourceServerContext
*/
private $context;
/**
* @var IResourceServerContext
*/
private $context;
/**
* @var array
*/
private $headers;
/**
* @var array
*/
private $headers;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IAccessTokenService
*/
private $token_service;
/**
* @var IAccessTokenService
*/
private $token_service;
/**
* @param IResourceServerContext $context
* @param IApiEndpointRepository $endpoint_repository
* @param IAccessTokenService $token_service
*/
public function __construct(
IResourceServerContext $context,
IApiEndpointRepository $endpoint_repository,
IAccessTokenService $token_service
) {
$this->context = $context;
$this->headers = $this->getHeaders();
$this->endpoint_repository = $endpoint_repository;
$this->token_service = $token_service;
}
/**
* @param IResourceServerContext $context
* @param IApiEndpointRepository $endpoint_repository
* @param IAccessTokenService $token_service
*/
public function __construct(
IResourceServerContext $context,
IApiEndpointRepository $endpoint_repository,
IAccessTokenService $token_service
) {
$this->context = $context;
$this->headers = $this->getHeaders();
$this->endpoint_repository = $endpoint_repository;
$this->token_service = $token_service;
}
/**
* @param \Illuminate\Http\Request $request
* @param callable $next
* @return OAuth2WWWAuthenticateErrorResponse
*/
public function handle($request, Closure $next)
{
$url = $request->getRequestUri();
$method = $request->getMethod();
$realm = $request->getHost();
/**
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @return OAuth2WWWAuthenticateErrorResponse
*/
public function handle($request, Closure $next)
{
$url = $request->getRequestUri();
$method = $request->getMethod();
$realm = $request->getHost();
try
{
$route = RequestUtils::getCurrentRoutePath($request);
if (!$route)
{
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
sprintf('API endpoint does not exits! (%s:%s)', $url, $method)
);
}
// 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();
}
try {
$route = RequestUtils::getCurrentRoutePath($request);
if (!$route) {
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
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;
if (!is_null($auth_header) && !empty($auth_header))
{
$access_token_value = BearerAccessTokenAuthorizationHeaderParser::getInstance()->parse($auth_header);
}
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, '');
}
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($access_token_value) || empty($access_token_value))
{
//if access token value is not set, then error
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'missing access token'
);
}
//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 {
// 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, '');
}
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route, $method);
if (is_null($access_token_value) || empty($access_token_value)) {
//if access token value is not set, then error
throw new OAuth2ResourceServerException(
400,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'missing access token'
);
}
//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, $method)
);
}
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route, $method);
$token_info = $this->token_service->get($access_token_value);
//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, $method)
);
}
//check lifetime
if (is_null($token_info) || $token_info->getLifetime() <= 0)
{
throw new OAuth2ResourceServerException(
401,
OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient,
'invalid origin'
);
}
//check token audience
$audience = explode(' ', $token_info->getAudience());
if ((!in_array($realm, $audience)))
{
throw new OAuth2ResourceServerException(
401,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
'the access token provided is expired, revoked, malformed, or invalid for other reasons.'
);
}
if ($token_info->getApplicationType() === 'JS_CLIENT' && str_contains($token_info->getAllowedOrigins(), $origin) === false)
{
//check origins
throw new OAuth2ResourceServerException(
403,
OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient,
'invalid origin'
);
}
//check scopes
$endpoint_scopes = explode(' ', $endpoint->getScope());
$token_scopes = explode(' ', $token_info->getScope());
//check token available scopes vs. endpoint scopes
if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0)
{
Log::error(
sprintf(
'access token scopes (%s) does not allow to access to api url %s , needed scopes %s',
$token_info->getScope(),
$url,
implode(' OR ', $endpoint_scopes)
)
);
$token_info = $this->token_service->get($access_token_value);
if(!is_null($token_info))
Log::debug(sprintf("token lifetime %s", $token_info->getLifetime()));
//check lifetime
if (is_null($token_info)) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
//check token audience
Log::debug('checking token audience ...');
$audience = explode(' ', $token_info->getAudience());
if ((!in_array($realm, $audience))) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
if ($token_info->getApplicationType() === 'JS_CLIENT' && str_contains($token_info->getAllowedOrigins(),
$origin) === false
) {
//check origins
throw new OAuth2ResourceServerException(
403,
OAuth2Protocol::OAuth2Protocol_Error_UnauthorizedClient,
sprintf('invalid origin %s - allowed ones (%s)',$origin, $token_info->getAllowedOrigins())
);
}
//check scopes
Log::debug('checking token scopes ...');
$endpoint_scopes = explode(' ', $endpoint->getScope());
$token_scopes = explode(' ', $token_info->getScope());
throw new OAuth2ResourceServerException(
403,
OAuth2Protocol::OAuth2Protocol_Error_InsufficientScope,
'the request requires higher privileges than provided by the access token',
implode(' ', $endpoint_scopes)
);
}
//set context for api and continue processing
$context = array(
'access_token' => $access_token_value,
'expires_in' => $token_info->getLifetime(),
'client_id' => $token_info->getClientId(),
'scope' => $token_info->getScope()
);
//check token available scopes vs. endpoint scopes
if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0) {
Log::error(
sprintf(
'access token scopes (%s) does not allow to access to api url %s , needed scopes %s',
$token_info->getScope(),
$url,
implode(' OR ', $endpoint_scopes)
)
);
if (!is_null($token_info->getUserId()))
{
$context['user_id'] = $token_info->getUserId();
}
$this->context->setAuthorizationContext($context);
}
catch (OAuth2ResourceServerException $ex1)
{
Log::error($ex1);
$response = new OAuth2WWWAuthenticateErrorResponse(
$realm,
$ex1->getError(),
$ex1->getErrorDescription(),
$ex1->getScope(),
$ex1->getHttpCode()
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate', $response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch (InvalidGrantTypeException $ex2)
{
Log::error($ex2);
$response = new OAuth2WWWAuthenticateErrorResponse(
$realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
'the access token provided is expired, revoked, malformed, or invalid for other reasons.',
null,
401
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate', $response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch (\Exception $ex)
{
Log::error($ex);
$response = new OAuth2WWWAuthenticateErrorResponse(
$realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'invalid request',
null,
400
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate', $response->getWWWAuthenticateHeaderValue());
return $http_response;
}
$response = $next($request);
return $response;
}
throw new OAuth2ResourceServerException(
403,
OAuth2Protocol::OAuth2Protocol_Error_InsufficientScope,
'the request requires higher privileges than provided by the access token',
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' => $token_info->getLifetime(),
'client_id' => $token_info->getClientId(),
'scope' => $token_info->getScope(),
'application_type' => $token_info->getApplicationType()
);
/**
* @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;
}
if (!is_null($token_info->getUserId()))
{
$context['user_id'] = $token_info->getUserId();
$context['user_external_id'] = $token_info->getUserExternalId();
}
$this->context->setAuthorizationContext($context);
}
catch (OAuth2ResourceServerException $ex1)
{
Log::error($ex1);
$response = new OAuth2WWWAuthenticateErrorResponse(
$realm,
$ex1->getError(),
$ex1->getErrorDescription(),
$ex1->getScope(),
$ex1->getHttpCode()
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate', $response->getWWWAuthenticateHeaderValue());
return $http_response;
}
catch (InvalidGrantTypeException $ex2)
{
Log::error($ex2);
$response = new OAuth2WWWAuthenticateErrorResponse(
$realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidToken,
'the access token provided is expired, revoked, malformed, or invalid for other reasons.',
null,
401
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$http_response->header('WWW-Authenticate', $response->getWWWAuthenticateHeaderValue());
return $http_response;
} catch (\Exception $ex) {
Log::error($ex);
$response = new OAuth2WWWAuthenticateErrorResponse(
$realm,
OAuth2Protocol::OAuth2Protocol_Error_InvalidRequest,
'invalid request',
null,
400
);
$http_response = Response::json($response->getContent(), $response->getHttpCode());
$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

@ -1,106 +1,101 @@
<?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.
**/
* 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 libs\utils\ICacheService;
use models\resource_server\IApiEndpointRepository;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Support\Facades\Response;
use libs\utils\ICacheService;
use libs\utils\RequestUtils;
use models\resource_server\IApiEndpointRepository;
/**
* Class RateLimitMiddleware
* @package App\Http\Middleware
*/
* Class RateLimitMiddleware
* @package App\Http\Middleware
*/
final class RateLimitMiddleware implements Middleware
{
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var ICacheService
*/
private $cache_service;
/**
* @var ICacheService
*/
private $cache_service;
/**
* @param IApiEndpointRepository $endpoint_repository
* @param ICacheService $cache_service
*/
public function __construct(IApiEndpointRepository $endpoint_repository, ICacheService $cache_service)
{
$this->endpoint_repository = $endpoint_repository;
$this->cache_service = $cache_service;
}
/**
* @param IApiEndpointRepository $endpoint_repository
* @param ICacheService $cache_service
*/
public function __construct(IApiEndpointRepository $endpoint_repository, ICacheService $cache_service)
{
$this->endpoint_repository = $endpoint_repository;
$this->cache_service = $cache_service;
}
/**
* 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 was not changed then short circuit ...
if ($response->getStatusCode() === 304)
{
return $response;
}
/**
* 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 was not changed then short circuit ...
if ($response->getStatusCode() === 304) {
return $response;
}
$url = $request->getRequestUri();
$url = $request->getRequestUri();
try
{
$route = RequestUtils::getCurrentRoutePath($request);
$method = $request->getMethod();
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route, $method);
try {
$route = RequestUtils::getCurrentRoutePath($request);
$method = $request->getMethod();
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route, $method);
if (!is_null($endpoint->rate_limit) && ($requestsPerHour = (int)$endpoint->rate_limit) > 0)
{
//do rate limit checking
$key = sprintf('rate.limit.%s_%s_%s', $url, $method, $request->getClientIp());
// Add if doesn't exist
// Remember for 1 hour
$this->cache_service->addSingleValue($key, 0, 3600);
// Add to count
$count = $this->cache_service->incCounter($key);
if ( $count > $requestsPerHour )
{
// Short-circuit response - we're ignoring
$response = Response::json(array(
'message' => "You have triggered an abuse detection mechanism and have been temporarily blocked.
Please retry your request again later."), 403);
$ttl = (int) $this->cache_service->ttl($key);
$response->headers->set('X-RateLimit-Reset', $ttl, false);
}
$response->headers->set('X-Ratelimit-Limit', $requestsPerHour, false);
$remaining = $requestsPerHour-(int)$count;
if ($remaining < 0)
{
$remaining = 0;
}
$response->headers->set('X-Ratelimit-Remaining', $remaining, false);
}
}
catch (Exception $ex)
{
Log::error($ex);
}
return $response;
}
if (!is_null($endpoint->rate_limit) && ($requestsPerHour = (int)$endpoint->rate_limit) > 0) {
//do rate limit checking
$key = sprintf('rate.limit.%s_%s_%s', $url, $method, $request->getClientIp());
// Add if doesn't exist
// Remember for 1 hour
$this->cache_service->addSingleValue($key, 0, 3600);
// Add to count
$count = $this->cache_service->incCounter($key);
if ($count > $requestsPerHour) {
// Short-circuit response - we're ignoring
$response = Response::json(array(
'message' => "You have triggered an abuse detection mechanism and have been temporarily blocked.
Please retry your request again later."
), 403);
$ttl = (int)$this->cache_service->ttl($key);
$response->headers->set('X-RateLimit-Reset', $ttl, false);
}
$response->headers->set('X-Ratelimit-Limit', $requestsPerHour, false);
$remaining = $requestsPerHour - (int)$count;
if ($remaining < 0) {
$remaining = 0;
}
$response->headers->set('X-Ratelimit-Remaining', $remaining, false);
}
} catch (Exception $ex) {
Log::error($ex);
}
return $response;
}
}

View File

@ -44,7 +44,7 @@ class SecurityHTTPHeadersWriterMiddleware implements Middleware
* applies to the domain of the issuing HSTS Host and all of its
* subdomains:
*/
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
//$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
return $response;
}
}

View File

@ -0,0 +1,36 @@
<?php namespace utils;
/**
* 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.
**/
abstract class AbstractFilterElement
{
/**
* @var string
*/
protected $operator;
/**
* @param string $operator
*/
protected function __construct($operator)
{
$this->operator = $operator;
}
/**
* @return string
*/
public function getOperator(){
return $this->operator;
}
}

183
app/Http/Utils/Filter.php Normal file
View File

@ -0,0 +1,183 @@
<?php namespace utils;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* 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.
**/
final class Filter
{
/**
* @var array
*/
private $filters = array();
/**
* @var array
*/
private $bindings = array();
public function __construct($filters)
{
$this->filters = $filters;
}
/**
* @param string $field
* @return null|FilterElement
*/
public function getFilter($field)
{
foreach($this->filters as $f)
{
if($f->getField() === $field)
{
return $f;
}
}
return null;
}
/**
* @param Relation $relation
* @param array $mappings
* @return $this
*/
public function apply2Relation(Relation $relation, array $mappings)
{
foreach($this->filters as $filter)
{
if($filter instanceof FilterElement)
{
if(isset($mappings[$filter->getField()]))
{
$mapping = $mappings[$filter->getField()];
$mapping = explode(':', $mapping);
$value = $filter->getValue();
if(count($mapping) > 1)
{
$value = $this->convertValue($value, $mapping[1]);
}
$relation->getQuery()->where($mapping[0], $filter->getOperator(), $value);
}
}
else if(is_array($filter))
{
// OR
$relation->getQuery()->where(function ($query) use($filter, $mappings){
foreach($filter as $e) {
if($e instanceof FilterElement && isset($mappings[$e->getField()]))
{
$mapping = $mappings[$e->getField()];
$mapping = explode(':', $mapping);
$value = $e->getValue();
if(count($mapping) > 1)
{
$value = $this->convertValue($value, $mapping[1]);
}
$query->orWhere($mapping[0], $e->getOperator(),$value);
}
}
});
}
}
return $this;
}
/**
* @param string $value
* @param string $original_format
* @return mixed
*/
private function convertValue($value, $original_format)
{
switch($original_format)
{
case 'datetime_epoch':
$datetime = new \DateTime("@$value");
return $datetime->format("Y-m-d H:i:s");
break;
case 'json_int':
return intval($value);
break;
default:
return $value;
break;
}
}
/**
* @return array
*/
public function getSQLBindings()
{
return $this->bindings;
}
/**
* @param array $mappings
* @return string
*/
public function toRawSQL(array $mappings)
{
$sql = '';
$this->bindings = array();
foreach($this->filters as $filter)
{
if($filter instanceof FilterElement)
{
if(isset($mappings[$filter->getField()]))
{
$mapping = $mappings[$filter->getField()];
$mapping = explode(':', $mapping);
$value = $filter->getValue();
$op = $filter->getOperator();
if(count($mapping) > 1)
{
$filter->setValue( $this->convertValue($value, $mapping[1]));
}
$cond = sprintf(' %s %s :%s', $mapping[0], $op, $filter->getField());
$this->bindings[$filter->getField()] = $filter->getValue();
if(!empty($sql)) $sql .= " AND ";
$sql .= $cond;
}
}
else if(is_array($filter))
{
// OR
$sql .= " ( ";
$sql_or = '';
foreach($filter as $e)
{
if($e instanceof FilterElement && isset($mappings[$e->getField()]))
{
$mapping = $mappings[$e->getField()];
$mapping = explode(':', $mapping);
$value = $e->getValue();
$op = $e->getOperator();
if(count($mapping) > 1)
{
$e->setValue( $this->convertValue($value, $mapping[1]));
}
$cond = sprintf(' %s %s :%s', $mapping[0], $op, $e->getField());
$this->bindings[$e->getField()] = $e->getValue();
if(!empty($sql_or)) $sql_or .= " OR ";
$sql_or .= $cond;
}
}
$sql .= $sql_or. " ) ";
}
}
return $sql;
}
}

View File

@ -0,0 +1,106 @@
<?php namespace utils;
/**
* 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 FilterElement extends AbstractFilterElement
{
/**
* @var mixed
*/
private $value;
/**
* @var string
*/
private $field;
/**
* @param $field
* @param $value
* @param $operator
*/
protected function __construct($field, $value, $operator)
{
parent::__construct($operator);
$this->field = $field;
$this->value = $value;
}
/**
* @param mixed $value
* @return $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* @return string
*/
public function getField()
{
return $this->field;
}
/**
* @return string
*/
public function getValue()
{
switch($this->operator)
{
case 'like':
return "%".$this->value."%";
break;
default:
return $this->value;
break;
}
}
public static function makeEqual($field, $value)
{
return new self($field, $value, '=');
}
public static function makeGreather($field, $value)
{
return new self($field, $value, '>');
}
public static function makeGreatherOrEqual($field, $value)
{
return new self($field, $value, '=>');
}
public static function makeLower($field, $value)
{
return new self($field, $value, '>');
}
public static function makeLowerOrEqual($field, $value)
{
return new self($field, $value, '>=');
}
public static function makeNotEqual($field, $value)
{
return new self($field, $value, '<>');
}
public static function makeLike($field, $value)
{
return new self($field, $value, 'like');
}
}

View File

@ -0,0 +1,115 @@
<?php namespace utils;
/**
* 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.
**/
final class FilterParser
{
/**
* @param mixed $filters
* @param array $allowed_fields
* @return Filter
*/
public static function parse($filters, $allowed_fields = array())
{
$res = array();
$matches = array();
if(!is_array($filters))
$filters = array($filters);
foreach($filters as $filter) // parse AND filters
{
$f = null;
// parse OR filters
$or_filters = explode(',', $filter);
if(count($or_filters) > 1)
{
$f = array();
foreach ($or_filters as $of) {
//single filter
preg_match('/[=<>][=>@]{0,1}/', $of, $matches);
if(count($matches) === 1)
{
$op = $matches[0];
$operands = explode($op, $of);
$field = $operands[0];
$value = $operands[1];
if(!isset($allowed_fields[$field])) continue;
if(!in_array($op, $allowed_fields[$field])) continue;
$f_or = self::buildFilter($field, $op, $value);
if(!is_null($f_or))
array_push($f, $f_or);
}
}
}
else
{
//single filter
preg_match('/[=<>][=>@]{0,1}/', $filter, $matches);
if(count($matches) === 1)
{
$op = $matches[0];
$operands = explode($op, $filter);
$field = $operands[0];
$value = $operands[1];
if(!isset($allowed_fields[$field])) continue;
if(!in_array($op, $allowed_fields[$field])) continue;
$f = self::buildFilter($field, $op, $value);
}
}
if(!is_null($f))
array_push($res, $f);
}
return new Filter($res);
}
/**
* Factory Method
*
* @param string $field
* @param string $op
* @param string $value
* @return FilterElement|null
*/
private static function buildFilter($field, $op, $value)
{
switch($op)
{
case '==':
return FilterElement::makeEqual($field, $value);
break;
case '=@':
return FilterElement::makeLike($field, $value);
break;
case '>':
return FilterElement::makeGreather($field, $value);
break;
case '>=':
return FilterElement::makeGreatherOrEqual($field, $value);
break;
case '<':
return FilterElement::makeLower($field, $value);
break;
case '<=':
return FilterElement::makeLowerOrEqual($field, $value);
break;
case '<>':
return FilterElement::makeNotEqual($field, $value);
break;
}
return null;
}
}

66
app/Http/Utils/Order.php Normal file
View File

@ -0,0 +1,66 @@
<?php
/**
* 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.
**/
namespace utils;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* Class Order
* @package utils
*/
final class Order
{
/**
* @var array
*/
private $ordering;
public function __construct($ordering = array())
{
$this->ordering = $ordering;
}
public function apply2Relation(Relation $relation, array $mappings)
{
foreach ($this->ordering as $order) {
if ($order instanceof OrderElement) {
if (isset($mappings[$order->getField()])) {
$mapping = $mappings[$order->getField()];
$relation->getQuery()->orderBy($mapping, $order->getDirection());
}
}
}
return $this;
}
/**
* @param array $mappings
* @return string
*/
public function toRawSQL(array $mappings)
{
$sql = ' ORDER BY ';
foreach ($this->ordering as $order) {
if ($order instanceof OrderElement) {
if (isset($mappings[$order->getField()])) {
$mapping = $mappings[$order->getField()];
$sql .= sprintf('%s %s, ', $mapping, $order->getDirection());
}
}
}
return substr($sql, 0 , strlen($sql) - 2);
}
}

View File

@ -0,0 +1,74 @@
<?php
/**
* 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.
**/
namespace utils;
/**
* Class OrderElement
* @package utils
*/
final class OrderElement
{
/**
* @var string
*/
private $field;
/**
* @var string
*/
private $direction;
/**
* OrderElement constructor.
* @param $field
* @param $direction
*/
private function __construct($field, $direction)
{
$this->field = $field;
$this->direction = $direction;
}
public static function buildAscFor($field)
{
return new OrderElement($field, 'ASC');
}
public static function buildDescFor($field)
{
return new OrderElement($field, 'DESC');
}
/**
* @return string
*/
public function getField()
{
return $this->field;
}
public function isAsc()
{
return $this->direction === 'ASC';
}
/**
* @return string
*/
public function getDirection()
{
return $this->direction;
}
}

View File

@ -0,0 +1,57 @@
<?php
/**
* 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.
**/
namespace utils;
/**
* Class OrderParser
* @package utils
*/
final class OrderParser
{
/**
* @param string $orders
* @param array $allowed_fields
* @return Order
*/
public static function parse($orders, $allowed_fields = array())
{
$res = array();
$orders = explode(',', $orders);
//default ordering is asc
foreach($orders as $field)
{
$element = null;
if(strpos($field, '+') === 0)
{
$field = trim($field,'+');
if(!in_array($field, $allowed_fields)) continue;
$element = OrderElement::buildAscFor($field);
}
else if(strpos($field, '-') === 0)
{
$field = trim($field,'-');
if(!in_array($field, $allowed_fields)) continue;
$element = OrderElement::buildDescFor($field);
}
else
{
if(!in_array($field, $allowed_fields)) continue;
$element = OrderElement::buildAscFor($field);
}
array_push($res, $element);
}
return new Order($res);
}
}

View File

@ -0,0 +1,59 @@
<?php namespace utils;
/**
* 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 PagingInfo
{
/**
* @var int
*/
private $page;
/**
* @var int
*/
private $per_page;
/**
* @param int $page
* @param int $per_page
*/
public function __construct($page = 1, $per_page = 10)
{
$this->page = $page;
$this->per_page = $per_page;
}
/**
* @return int
*/
public function getCurrentPage()
{
return $this->page;
}
/**
* @return int
*/
public function getPerPage()
{
return $this->per_page;
}
/**
* @return int
*/
public function getOffset()
{
return ($this->page - 1) * $this->per_page;
}
}

View File

@ -0,0 +1,105 @@
<?php namespace utils;
/**
* 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.
**/
final class PagingResponse
{
/**
* @var int
*/
private $total;
/**
* @var int
*/
private $per_page;
/**
* @var int
*/
private $page;
/**
* @var int
*/
private $last_page;
/**
* @var array
*/
private $items;
/**
* @param int $total
* @param int $per_page
* @param int $page
* @param int $last_page
* @param array $items
*/
public function __construct($total, $per_page, $page, $last_page, array $items)
{
$this->total = $total;
$this->per_page = $per_page;
$this->page = $page;
$this->last_page = $last_page;
$this->items = $items;
}
public function getTotal()
{
return $this->total;
}
/**
* @return int
*/
public function getPerPage()
{
return $this->per_page;
}
/**
* @return int
*/
public function getCurrentPage()
{
return $this->page;
}
/**
* @return int
*/
public function getLastPage()
{
return $this->last_page;
}
/**
* @return array
*/
public function getItems()
{
return $this->items;
}
/**
* @return array
*/
public function toArray()
{
return array
(
'total' => $this->total,
'per_page' => $this->per_page,
'current_page' => $this->page,
'last_page' => $this->last_page,
'data' => $this->items,
);
}
}

View File

@ -11,30 +11,114 @@
|
*/
//OAuth2 Protected API
Route::group(array('prefix' => 'api/v1',
'before' => ['ssl', 'oauth2.enabled'],
'after' => '',
'middleware' => ['oauth2.protected', 'rate.limit','etags']), function () {
Route::group(array(
'prefix' => 'api/v1',
'before' => ['ssl', 'oauth2.enabled'],
'after' => '',
'middleware' => ['oauth2.protected', 'rate.limit','etags']
), function () {
Route::group(array('prefix' => 'marketplace'), function () {
Route::group(array('prefix' => 'marketplace'), function () {
Route::group(array('prefix' => 'public-clouds'), function () {
Route::get('', 'OAuth2PublicCloudApiController@getClouds');
Route::get('/{id}', 'OAuth2PublicCloudApiController@getCloud');
Route::get('/{id}/data-centers', 'OAuth2PublicCloudApiController@getCloudDataCenters');
});
Route::group(array('prefix' => 'public-clouds'), function () {
Route::get('', 'OAuth2PublicCloudApiController@getClouds');
Route::get('/{id}', 'OAuth2PublicCloudApiController@getCloud');
Route::get('/{id}/data-centers', 'OAuth2PublicCloudApiController@getCloudDataCenters');
});
Route::group(array('prefix' => 'private-clouds'), function () {
Route::get('', 'OAuth2PrivateCloudApiController@getClouds');
Route::get('/{id}', 'OAuth2PrivateCloudApiController@getCloud');
Route::get('/{id}/data-centers', 'OAuth2PrivateCloudApiController@getCloudDataCenters');
});
Route::group(array('prefix' => 'private-clouds'), function () {
Route::get('', 'OAuth2PrivateCloudApiController@getClouds');
Route::get('/{id}', 'OAuth2PrivateCloudApiController@getCloud');
Route::get('/{id}/data-centers', 'OAuth2PrivateCloudApiController@getCloudDataCenters');
});
Route::group(array('prefix' => 'consultants'), function () {
Route::get('', 'OAuth2ConsultantsApiController@getConsultants');
Route::get('/{id}', 'OAuth2ConsultantsApiController@getConsultant');
Route::get('/{id}/offices', 'OAuth2ConsultantsApiController@getOffices');
});
Route::group(array('prefix' => 'consultants'), function () {
Route::get('', 'OAuth2ConsultantsApiController@getConsultants');
Route::get('/{id}', 'OAuth2ConsultantsApiController@getConsultant');
Route::get('/{id}/offices', 'OAuth2ConsultantsApiController@getOffices');
});
});
});
});
// summits
Route::group(array('prefix' => 'summits'), function () {
Route::get('', 'OAuth2SummitApiController@getSummits');
Route::group(array('prefix' => '{id}'), function () {
Route::get('', [ 'middleware' => 'cache', 'uses' => 'OAuth2SummitApiController@getSummit'])->where('id', 'current|[0-9]+');
Route::get('entity-events', 'OAuth2SummitApiController@getSummitEntityEvents');
// attendees
Route::group(array('prefix' => 'attendees'), function () {
//Route::get('', 'OAuth2SummitApiController@getAttendees');
Route::group(array('prefix' => '{attendee_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getAttendee')->where('attendee_id', 'me|[0-9]+');
Route::group(array('prefix' => 'schedule'), function ()
{
Route::get('', 'OAuth2SummitApiController@getAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::group(array('prefix' => '{event_id}'), function (){
Route::post('', 'OAuth2SummitApiController@addEventToAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::delete('', 'OAuth2SummitApiController@removeEventFromAttendeeSchedule')->where('attendee_id', 'me|[0-9]+');
Route::put('/check-in', 'OAuth2SummitApiController@checkingAttendeeOnEvent')->where('attendee_id', 'me|[0-9]+');
});
});
});
});
// speakers
Route::group(array('prefix' => 'speakers'), function () {
Route::get('', 'OAuth2SummitApiController@getSpeakers');
Route::group(array('prefix' => '{speaker_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getSpeaker')->where('speaker_id', 'me|[0-9]+');
});
});
// events
Route::group(array('prefix' => 'events'), function () {
Route::get('', 'OAuth2SummitApiController@getEvents');
Route::get('/published', 'OAuth2SummitApiController@getScheduleEvents');
Route::post('', 'OAuth2SummitApiController@addEvent');
Route::group(array('prefix' => '{event_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getEvent');
Route::get('/published', 'OAuth2SummitApiController@getScheduleEvent');
Route::put('', 'OAuth2SummitApiController@updateEvent');
Route::delete('', 'OAuth2SummitApiController@deleteEvent');
Route::put('/publish', 'OAuth2SummitApiController@publishEvent');
Route::delete('/publish', 'OAuth2SummitApiController@unPublishEvent');
Route::post('/feedback', 'OAuth2SummitApiController@addEventFeedback');
Route::get('/feedback/{attendee_id?}', 'OAuth2SummitApiController@getEventFeedback')->where('attendee_id', 'me|[0-9]+');
});
});
// locations
Route::group(array('prefix' => 'locations'), function () {
Route::get('', 'OAuth2SummitApiController@getLocations');
Route::group(array('prefix' => '{location_id}'), function () {
Route::get('', 'OAuth2SummitApiController@getLocation');
});
});
// event types
Route::group(array('prefix' => 'event-types'), function () {
Route::get('', 'OAuth2SummitApiController@getEventTypes');
});
// summit types
Route::group(array('prefix' => 'summit-types'), function () {
Route::get('', 'OAuth2SummitApiController@getSummitTypes');
});
});
});
});

View File

@ -1,92 +1,93 @@
<?php namespace libs\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 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 OAuth2Protocol
{
const OAuth2Protocol_GrantType_AuthCode = 'authorization_code';
const OAuth2Protocol_GrantType_Implicit = 'implicit';
const OAuth2Protocol_GrantType_ResourceOwner_Password = 'password';
const OAuth2Protocol_GrantType_ClientCredentials = 'client_credentials';
const OAuth2Protocol_GrantType_RefreshToken = 'refresh_token';
const OAuth2Protocol_ResponseType_Code = 'code';
const OAuth2Protocol_ResponseType_Token = 'token';
const OAuth2Protocol_ResponseType = 'response_type';
const OAuth2Protocol_ClientId = 'client_id';
const OAuth2Protocol_UserId = 'user_id';
const OAuth2Protocol_ClientSecret = 'client_secret';
const OAuth2Protocol_Token = 'token';
const OAuth2Protocol_TokenType = 'token_type';
//http://tools.ietf.org/html/rfc7009#section-2.1
const OAuth2Protocol_TokenType_Hint = 'token_type_hint';
const OAuth2Protocol_AccessToken_ExpiresIn = 'expires_in';
const OAuth2Protocol_RefreshToken = 'refresh_token';
const OAuth2Protocol_AccessToken = 'access_token';
const OAuth2Protocol_RedirectUri = 'redirect_uri';
const OAuth2Protocol_Scope = 'scope';
const OAuth2Protocol_Audience = 'audience';
const OAuth2Protocol_State = 'state';
/**
* Indicates whether the user should be re-prompted for consent. The default is auto,
* so a given user should only see the consent page for a given set of scopes the first time
* through the sequence. If the value is force, then the user sees a consent page even if they
* previously gave consent to your application for a given set of scopes.
*/
const OAuth2Protocol_Approval_Prompt = 'approval_prompt';
const OAuth2Protocol_Approval_Prompt_Force = 'force';
const OAuth2Protocol_Approval_Prompt_Auto = 'auto';
const OAuth2Protocol_GrantType_AuthCode = 'authorization_code';
const OAuth2Protocol_GrantType_Implicit = 'implicit';
const OAuth2Protocol_GrantType_ResourceOwner_Password = 'password';
const OAuth2Protocol_GrantType_ClientCredentials = 'client_credentials';
const OAuth2Protocol_GrantType_RefreshToken = 'refresh_token';
const OAuth2Protocol_ResponseType_Code = 'code';
const OAuth2Protocol_ResponseType_Token = 'token';
const OAuth2Protocol_ResponseType = 'response_type';
const OAuth2Protocol_ClientId = 'client_id';
const OAuth2Protocol_UserId = 'user_id';
const OAuth2Protocol_ClientSecret = 'client_secret';
const OAuth2Protocol_Token = 'token';
const OAuth2Protocol_TokenType = 'token_type';
//http://tools.ietf.org/html/rfc7009#section-2.1
const OAuth2Protocol_TokenType_Hint = 'token_type_hint';
const OAuth2Protocol_AccessToken_ExpiresIn = 'expires_in';
const OAuth2Protocol_RefreshToken = 'refresh_token';
const OAuth2Protocol_AccessToken = 'access_token';
const OAuth2Protocol_RedirectUri = 'redirect_uri';
const OAuth2Protocol_Scope = 'scope';
const OAuth2Protocol_Audience = 'audience';
const OAuth2Protocol_State = 'state';
/**
* Indicates whether the user should be re-prompted for consent. The default is auto,
* so a given user should only see the consent page for a given set of scopes the first time
* through the sequence. If the value is force, then the user sees a consent page even if they
* previously gave consent to your application for a given set of scopes.
*/
const OAuth2Protocol_Approval_Prompt = 'approval_prompt';
const OAuth2Protocol_Approval_Prompt_Force = 'force';
const OAuth2Protocol_Approval_Prompt_Auto = 'auto';
/**
* Indicates whether your application needs to access an API when the user is not present at
* the browser. This parameter defaults to online. If your application needs to refresh access tokens
* when the user is not present at the browser, then use offline. This will result in your application
* obtaining a refresh token the first time your application exchanges an authorization code for a user.
*/
const OAuth2Protocol_AccessType = 'access_type';
const OAuth2Protocol_AccessType_Online = 'online';
const OAuth2Protocol_AccessType_Offline = 'offline';
/**
* Indicates whether your application needs to access an API when the user is not present at
* the browser. This parameter defaults to online. If your application needs to refresh access tokens
* when the user is not present at the browser, then use offline. This will result in your application
* obtaining a refresh token the first time your application exchanges an authorization code for a user.
*/
const OAuth2Protocol_AccessType = 'access_type';
const OAuth2Protocol_AccessType_Online = 'online';
const OAuth2Protocol_AccessType_Offline = 'offline';
const OAuth2Protocol_GrantType = 'grant_type';
const OAuth2Protocol_Error = 'error';
const OAuth2Protocol_ErrorDescription = 'error_description';
const OAuth2Protocol_ErrorUri = 'error_uri';
const OAuth2Protocol_Error_InvalidRequest = 'invalid_request';
const OAuth2Protocol_Error_UnauthorizedClient = 'unauthorized_client';
const OAuth2Protocol_Error_AccessDenied = 'access_denied';
const OAuth2Protocol_Error_UnsupportedResponseType = 'unsupported_response_type';
const OAuth2Protocol_Error_InvalidScope = 'invalid_scope';
const OAuth2Protocol_Error_UnsupportedGrantType = 'unsupported_grant_type';
const OAuth2Protocol_Error_InvalidGrant = 'invalid_grant';
//error codes definitions http://tools.ietf.org/html/rfc6749#section-4.1.2.1
const OAuth2Protocol_Error_ServerError = 'server_error';
const OAuth2Protocol_Error_TemporallyUnavailable = 'temporally_unavailable';
//http://tools.ietf.org/html/rfc7009#section-2.2.1
const OAuth2Protocol_Error_Unsupported_TokenType = ' unsupported_token_type';
//http://tools.ietf.org/html/rfc6750#section-3-1
const OAuth2Protocol_Error_InvalidToken = 'invalid_token';
const OAuth2Protocol_Error_InsufficientScope = 'insufficient_scope';
const OAuth2Protocol_GrantType = 'grant_type';
const OAuth2Protocol_Error = 'error';
const OAuth2Protocol_ErrorDescription = 'error_description';
const OAuth2Protocol_ErrorUri = 'error_uri';
const OAuth2Protocol_Error_InvalidRequest = 'invalid_request';
const OAuth2Protocol_Error_UnauthorizedClient = 'unauthorized_client';
const OAuth2Protocol_Error_AccessDenied = 'access_denied';
const OAuth2Protocol_Error_UnsupportedResponseType = 'unsupported_response_type';
const OAuth2Protocol_Error_InvalidScope = 'invalid_scope';
const OAuth2Protocol_Error_UnsupportedGrantType = 'unsupported_grant_type';
const OAuth2Protocol_Error_InvalidGrant = 'invalid_grant';
//error codes definitions http://tools.ietf.org/html/rfc6749#section-4.1.2.1
const OAuth2Protocol_Error_ServerError = 'server_error';
const OAuth2Protocol_Error_TemporallyUnavailable = 'temporally_unavailable';
//http://tools.ietf.org/html/rfc7009#section-2.2.1
const OAuth2Protocol_Error_Unsupported_TokenType = ' unsupported_token_type';
//http://tools.ietf.org/html/rfc6750#section-3-1
const OAuth2Protocol_Error_InvalidToken = 'invalid_token';
const OAuth2Protocol_Error_InsufficientScope = 'insufficient_scope';
public static $valid_responses_types = array(
self::OAuth2Protocol_ResponseType_Code => self::OAuth2Protocol_ResponseType_Code,
self::OAuth2Protocol_ResponseType_Token => self::OAuth2Protocol_ResponseType_Token
);
public static $protocol_definition = array(
self::OAuth2Protocol_ResponseType => self::OAuth2Protocol_ResponseType,
self::OAuth2Protocol_ClientId => self::OAuth2Protocol_ClientId,
self::OAuth2Protocol_RedirectUri => self::OAuth2Protocol_RedirectUri,
self::OAuth2Protocol_Scope => self::OAuth2Protocol_Scope,
self::OAuth2Protocol_State => self::OAuth2Protocol_State
);
public static $valid_responses_types = array(
self::OAuth2Protocol_ResponseType_Code => self::OAuth2Protocol_ResponseType_Code,
self::OAuth2Protocol_ResponseType_Token => self::OAuth2Protocol_ResponseType_Token
);
public static $protocol_definition = array(
self::OAuth2Protocol_ResponseType => self::OAuth2Protocol_ResponseType,
self::OAuth2Protocol_ClientId => self::OAuth2Protocol_ClientId,
self::OAuth2Protocol_RedirectUri => self::OAuth2Protocol_RedirectUri,
self::OAuth2Protocol_Scope => self::OAuth2Protocol_Scope,
self::OAuth2Protocol_State => self::OAuth2Protocol_State
);
}

View File

@ -1,71 +1,71 @@
<?php namespace libs\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 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 OAuth2WWWAuthenticateErrorResponse
* http://tools.ietf.org/html/rfc6750#section-3
* @package oauth2\responses
*/
* Class OAuth2WWWAuthenticateErrorResponse
* http://tools.ietf.org/html/rfc6750#section-3
* @package oauth2\responses
*/
class OAuth2WWWAuthenticateErrorResponse extends OAuth2DirectResponse
{
private $realm;
private $error;
private $error_description;
private $scope;
private $http_error;
private $realm;
private $error;
private $error_description;
private $scope;
private $http_error;
public function __construct($realm, $error, $error_description, $scope, $http_error)
{
parent::__construct($http_error, self::DirectResponseContentType);
$this->realm = $realm;
$this->error = $error;
$this->error_description = $error_description;
$this->scope = $scope;
$this->http_error = $http_error;
}
public function __construct($realm, $error, $error_description, $scope, $http_error)
{
parent::__construct($http_error, self::DirectResponseContentType);
$this->realm = $realm;
$this->error = $error;
$this->error_description = $error_description;
$this->scope = $scope;
$this->http_error = $http_error;
}
public function getWWWAuthenticateHeaderValue()
{
$value=sprintf('Bearer realm="%s"', $this->realm);
$value=$value.sprintf(', error="%s"', $this->error);
$value=$value.sprintf(', error_description="%s"', $this->error_description);
if (!is_null($this->scope))
{
$value=$value.sprintf(', scope="%s"', $this->scope);
}
return $value;
}
public function getWWWAuthenticateHeaderValue()
{
$value = sprintf('Bearer realm="%s"', $this->realm);
$value = $value . sprintf(', error="%s"', $this->error);
$value = $value . sprintf(', error_description="%s"', $this->error_description);
if (!is_null($this->scope)) {
$value = $value . sprintf(', scope="%s"', $this->scope);
}
return $value;
}
public function getContent()
{
$content = array(
'error' => $this->error,
'error_description' => $this->error_description
);
if (!is_null($this->scope))
{
$content['scope'] = $this->scope;
}
return $content;
}
public function getContent()
{
$content = array(
'error' => $this->error,
'error_description' => $this->error_description
);
if (!is_null($this->scope)) {
$content['scope'] = $this->scope;
}
public function getType()
{
return null;
}
return $content;
}
public function getType()
{
return null;
}
}

View File

@ -0,0 +1,33 @@
<?php
/**
* 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.
**/
namespace libs\utils;
/**
* Class DateTimeUtils
* @package libs\utils
*/
abstract class DateTimeUtils
{
const MicrosecondsPrecision = 6;
/**
* @return string
*/
public static function nowRfc2822(){
list($usec, $sec) = explode(' ', microtime());
$usec = substr($usec, 2, self::MicrosecondsPrecision);
return gmdate('Y-m-d H:i:s', $sec).'.'.$usec;
}
}

View File

@ -0,0 +1,34 @@
<?php
/**
* 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.
**/
namespace libs\utils;
use Closure;
/**
* Interface ITransactionService
* @package libs\utils
*/
interface ITransactionService
{
/**
* Execute a Closure within a transaction.
*
* @param Closure $callback
* @return mixed
*
* @throws \Exception
*/
public function transaction(Closure $callback);
}

View File

@ -0,0 +1,75 @@
<?php
/**
* 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.
**/
namespace libs\utils;
/**
* Class JsonUtils
* http://json.org/
* @package libs\utils
*/
abstract class JsonUtils
{
/**
* A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.
* A character is represented as a single character string. A string is very much like a C or Java string.
* @param string $value
* @return string
*/
public static function toJsonString($value)
{
return $value;
}
/**
* @param string $value
* @return bool
*/
public static function toJsonBoolean($value)
{
if(empty($value)) return false;
return boolval($value);
}
/**
* @param string $value
* @return int|null
*/
public static function toJsonInt($value)
{
if(empty($value)) return null;
return intval($value);
}
/**
* @param string $value
* @return float|null
*/
public static function toJsonFloat($value)
{
if(empty($value)) return null;
return number_format(floatval($value),2);
}
/**
* @param string $value
* @return int
*/
public static function toEpoch($value)
{
if(empty($value)) return 0;
$datetime = new \DateTime($value);
return $datetime->getTimestamp();
}
}

View File

@ -1,38 +0,0 @@
<?php namespace models\marketplace;
/**
* 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 models\utils\BaseModelEloquent;
use models\utils\IEntity;
class CompanyService extends BaseModelEloquent implements IEntity
{
protected $hidden = array('ClassName', 'MarketPlaceTypeID', 'EditedByID');
protected $table = 'CompanyService';
protected $connection = 'ss';
protected $stiClassField = 'ClassName';
protected $stiBaseClass = 'models\marketplace\CompanyService';
/**
* @return int
*/
public function getIdentifier()
{
return (int)$this->ID;
}
}

View File

@ -1,28 +0,0 @@
<?php namespace models\marketplace;
/**
* 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 Consultant extends CompanyService implements IConsultant
{
protected $connection = 'ss';
/**
* @return Office[]
*/
public function offices()
{
return $this->hasMany('models\marketplace\Office', 'ConsultantID', 'ID')->get();
}
}

View File

@ -1,45 +0,0 @@
<?php namespace models\marketplace;
/**
* 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 models\utils\IBaseRepository;
/**
* Interface ICompanyServiceRepository
* @package models\marketplace
*/
interface ICompanyServiceRepository extends IBaseRepository
{
const Status_All = 'all';
const Status_active = 'active';
const Status_non_active = 'non_active';
const Order_date = 'date';
const Order_name = 'name';
/**
* @param int $page
* @param int $per_page
* @param string $status
* @param string $order_by
* @param string $order_dir
* @return \IEntity[]
*/
public function getAll(
$page = 1,
$per_page = 1000,
$status = ICompanyServiceRepository::Status_All,
$order_by = ICompanyServiceRepository::Order_date,
$order_dir = 'asc'
);
}

View File

@ -1,30 +0,0 @@
<?php namespace models\marketplace;
/**
* 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 PublicCloudService
* @package models\marketplace
*/
class PublicCloudService extends CompanyService implements ICloudService
{
protected $connection = 'ss';
/**
* @return DataCenterRegion[]
*/
public function datacenters_regions()
{
return $this->hasMany('models\marketplace\DataCenterRegion', 'CloudServiceID', 'ID')->get();
}
}

View File

@ -1,154 +0,0 @@
<?php namespace models\resource_server;
/**
* 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 GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Config;
use libs\oauth2\OAuth2InvalidIntrospectionResponse;
use libs\utils\ICacheService;
use models\oauth2\AccessToken;
use libs\utils\ConfigurationException;
use libs\oauth2\InvalidGrantTypeException;
/**
* Class AccessTokenService
* @package models\resource_server
*/
final class AccessTokenService implements IAccessTokenService
{
/**
* @var ICacheService
*/
private $cache_service;
/**
* @param ICacheService $cache_service
*/
public function __construct(ICacheService $cache_service)
{
$this->cache_service = $cache_service;
}
/**
* @param string $token_value
* @return AccessToken
* @throws \Exception
*/
public function get($token_value)
{
$token = null;
$token_info = $this->cache_service->getHash(md5($token_value), array(
'access_token',
'scope',
'client_id',
'audience',
'user_id',
'expires_in',
'application_type',
'allowed_return_uris',
'allowed_origins'));
if (count($token_info) === 0)
{
$token_info = $this->makeRemoteCall($token_value);
$this->cache_service->storeHash(md5($token_value), $token_info, (int)$token_info['expires_in']);
}
else
{
$token_info['expires_in'] = $this->cache_service->ttl(md5($token_value));
}
$token = AccessToken::createFromParams(
$token_info['access_token'],
$token_info['scope'],
$token_info['client_id'],
$token_info['audience'],
$token_info['user_id'],
(int)$token_info['expires_in'],
$token_info['application_type'],
isset($token_info['allowed_return_uris']) ? $token_info['allowed_return_uris'] : null,
isset($token_info['allowed_origins']) ? $token_info['allowed_origins'] : null
);
return $token;
}
/**
* @param $token_value
* @return mixed
* @throws ConfigurationException
* @throws InvalidGrantTypeException
* @throws OAuth2InvalidIntrospectionResponse
*/
private function makeRemoteCall($token_value)
{
try
{
$client = new Client([
'defaults' => [
'timeout' => Config::get('curl.timeout', 60),
'allow_redirects' => Config::get('curl.allow_redirects', false),
'verify' => Config::get('curl.verify_ssl_cert', true)
]
]);
$client_id = Config::get('app.openstackid_client_id', '');
$client_secret = Config::get('app.openstackid_client_secret', '');
$auth_server_url = Config::get('app.openstackid_base_url', '');
if (empty($client_id))
{
throw new ConfigurationException('app.openstackid_client_id param is missing!');
}
if (empty($client_secret))
{
throw new ConfigurationException('app.openstackid_client_secret param is missing!');
}
if (empty($auth_server_url))
{
throw new ConfigurationException('app.openstackid_base_url param is missing!');
}
$response = $client->post(
$auth_server_url . '/oauth2/token/introspection',
[
'query' => ['token' => $token_value],
'headers' => ['Authorization' => " Basic " . base64_encode($client_id . ':' . $client_secret)]
]
);
$token_info = $response->json();
return $token_info;
}
catch (RequestException $ex)
{
$response = $ex->getResponse();
$body = $response->json();
$code = $response->getStatusCode();
if ($code === 400)
{
throw new InvalidGrantTypeException($body['error']);
}
throw new OAuth2InvalidIntrospectionResponse(sprintf('http code %s', $ex->getCode()));
}
}
}

View File

@ -1,30 +0,0 @@
<?php namespace models\resource_server;
/**
* 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 models\oauth2\AccessToken;
use libs\oauth2\OAuth2InvalidIntrospectionResponse;
/**
* Interface IAccessTokenService
* @package models\resource_server
*/
interface IAccessTokenService
{
/**
*@param string $token_value
*@return AccessToken
*@throws OAuth2InvalidIntrospectionResponse
*/
public function get($token_value);
}

View File

@ -1,91 +0,0 @@
<?php namespace models\resource_server;
/**
* 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.
**/
/**
* Interface IApiEndpoint
* @package models\resource_server
*/
interface IApiEndpoint
{
/**
* @return string
*/
public function getRoute();
/**
* @return string
*/
public function getHttpMethod();
/**
* @return string
*/
public function getName();
/**
* @param string $route
* @return void
*/
public function setRoute($route);
/**
* @param string $http_method
* @return void
*/
public function setHttpMethod($http_method);
/**
* @param string $name
* @return void
*/
public function setName($name);
/**
* @return string
*/
public function getScope();
/**
* @return bool
*/
public function isActive();
/**
* @param bool $active
* @return void
*/
public function setStatus($active);
/**
* @return bool
*/
public function supportCORS();
/**
* @return bool
*/
public function supportCredentials();
/**
* @return IApi
*/
public function api();
/**
* @return IApiScope[]
*/
public function scopes();
}

View File

@ -1,81 +1,198 @@
<?php namespace models\utils;
/**
* 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 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 DB;
use Eloquent;
use libs\utils\JsonUtils;
use ReflectionClass;
/**
* Class BaseModelEloquent
*/
* Class BaseModelEloquent
*/
class BaseModelEloquent extends Eloquent
{
private $class = null;
/**
* @param $query
* @param array $filters
* @return mixed
*/
public function scopeFilter($query, array $filters)
{
foreach ($filters as $filter)
{
$query = $query->where($filter['name'], $filter['op'], $filter['value']);
}
return $query;
}
private $class = null;
public function __construct($attributes = array())
{
parent::__construct($attributes);
$this->class = new ReflectionClass(get_class($this));
if ($this->useSti())
{
$this->setAttribute($this->stiClassField, $this->class->getName());
}
}
protected $array_mappings = array();
private function useSti()
{
return ($this->stiClassField && $this->stiBaseClass);
}
/**
* @param $query
* @param array $filters
* @return mixed
*/
public function scopeFilter($query, array $filters)
{
foreach ($filters as $filter) {
$query = $query->where($filter['name'], $filter['op'], $filter['value']);
}
public function newQuery($excludeDeleted = true)
{
$builder = parent::newQuery($excludeDeleted);
// If I am using STI, and I am not the base class,
// then filter on the class name.
if ($this->useSti() && get_class(new $this->stiBaseClass) !== get_class($this))
{
$builder->where($this->stiClassField, "=", $this->class->getShortName());
}
return $builder;
}
return $query;
}
public function newFromBuilder($attributes = array(), $connection = null)
{
if ($this->useSti() && $attributes->{$this->stiClassField})
{
$class = $this->class->getName();
$instance = new $class;
$instance->exists = true;
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
else
{
return parent::newFromBuilder($attributes, $connection);
}
}
public function __construct($attributes = array())
{
parent::__construct($attributes);
$this->class = new ReflectionClass(get_class($this));
if ($this->useSti()) {
$this->setAttribute($this->stiClassField, $this->class->getName());
}
}
public function toArray()
{
$values = parent::toArray();
if (count($this->array_mappings)) {
$new_values = array();
foreach ($this->array_mappings as $old_key => $new_key) {
$value = isset($values[$old_key])? $values[$old_key] :
(
isset($values['pivot'])? (
isset($values['pivot'][$old_key]) ? $values['pivot'][$old_key] : null
): null
);
$new_key = preg_split('/:/',$new_key);
if(count($new_key) > 1)
{
//we have a formatter ...
switch(strtolower($new_key[1]))
{
case 'datetime_epoch':
{
$datetime = new \DateTime($value);
$value = $datetime->getTimestamp();
}
break;
case 'json_string':
{
$value = JsonUtils::toJsonString($value);
}
break;
case 'json_boolean':
{
$value = JsonUtils::toJsonBoolean($value);
}
break;
case 'json_int':
{
$value = JsonUtils::toJsonInt($value);
}
break;
case 'json_float':
{
$value = JsonUtils::toJsonFloat($value);
}
break;
}
}
$new_values[$new_key[0]] = $value;
}
$values = $new_values;
}
return $values;
}
private function useSti()
{
return ($this->stiClassField && $this->stiBaseClass);
}
private function useMti()
{
return $this->mtiClassType;
}
public function newQuery($excludeDeleted = true)
{
$builder = parent::newQuery($excludeDeleted);
// If I am using STI, and I am not the base class,
// then filter on the class name.
if ($this->useMti()) {
$query = $builder->getQuery();
$class = $this->class->getName();
$parents = $this->get_class_lineage(new $class);
$base_table_set = false;
$current_class_name = null;
if ($this->mtiClassType === 'concrete') {
$current_class_name = $this->class->getShortName();
$query = $query->from($current_class_name);
$base_table_set = true;
}
foreach ($parents as $parent) {
if(!$this->isAllowedParent($parent))
{
continue;
}
$parent = new $parent;
if ($parent->mtiClassType === 'abstract') {
continue;
}
$table_name = $parent->class->getShortName();
if ($base_table_set === true) {
$query->leftJoin($table_name, $current_class_name . '.ID', '=', $table_name . '.ID');
} else {
$query = $query->from($table_name);
$base_table_set = true;
$current_class_name = $table_name;
}
}
} else {
if ($this->useSti() && get_class(new $this->stiBaseClass) !== get_class($this)) {
$builder->where($this->stiClassField, "=", $this->class->getShortName());
}
}
return $builder;
}
protected function isAllowedParent($parent_name)
{
$res = str_contains($parent_name, $this->class->getShortName()) ||
str_contains($parent_name,'Illuminate\Database\Eloquent\Model') ||
str_contains($parent_name, 'models\utils\BaseModelEloquent');
return !$res;
}
private function get_class_lineage($object)
{
$class_name = get_class($object);
$parents = array_values(class_parents($class_name));
return array_merge(array($class_name), $parents);
}
public function newFromBuilder($attributes = array(), $connection = null)
{
if ($this->useSti() && $attributes->{$this->stiClassField}) {
$class = $this->class->getName();
$instance = new $class;
$instance->exists = true;
$instance->setRawAttributes((array)$attributes, true);
return $instance;
} else {
return parent::newFromBuilder($attributes, $connection);
}
}
}

View File

@ -0,0 +1,62 @@
<?php
/**
* 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.
**/
namespace models\utils;
/**
* Class EloquentBaseRepository
* @package models\utils
*/
abstract class EloquentBaseRepository implements IBaseRepository
{
/**
* @var IEntity
*/
protected $entity;
/**
* @param int $id
* @return \models\utils\IEntity
*/
public function getById($id)
{
return $this->entity->find($id);
}
/**
* @param IEntity $entity
* @return void
*/
public function add($entity)
{
$entity->save();
}
/**
* @param IEntity $entity
* @return void
*/
public function delete($entity)
{
$entity->delete();
}
/**
* @return IEntity[]
*/
public function getAll()
{
return $this->entity->all()->all();
}
}

View File

@ -1,24 +1,31 @@
<?php namespace models\utils;
/**
* 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.
**/
/**
* Interface IBaseRepository
*/
interface IBaseRepository {
/**
* @param int $id
* @return IEntity
*/
public function getById($id);
* Interface IBaseRepository
*/
interface IBaseRepository
{
/**
* @param int $id
* @return IEntity
*/
public function getById($id);
/**
* @param IEntity $entity
* @return void
*/
public function add($entity);
/**
* @param IEntity $entity
* @return void
*/
public function delete($entity);
/**
* @return IEntity[]
*/
public function getAll();
}

View File

@ -0,0 +1,53 @@
<?php
/**
* 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.
**/
namespace models\utils;
/***
* Class SilverstripeBaseModel
* @package models\utils
*/
class SilverstripeBaseModel extends BaseModelEloquent implements IEntity
{
protected $primaryKey ='ID';
protected $connection = 'ss';
protected $stiClassField = 'ClassName';
const CREATED_AT = 'Created';
const UPDATED_AT = 'LastEdited';
protected function isAllowedParent($parent_name)
{
$res = parent::isAllowedParent($parent_name);
if(!$res) return false;
return !(str_contains($parent_name, 'SilverstripeBaseModel'));
}
public function __construct($attributes = array())
{
parent::__construct($attributes);
$this->ClassName = $this->table;
}
/**
* @return int
*/
public function getIdentifier()
{
return (int)$this->ID;
}
}

View File

@ -0,0 +1,19 @@
<?php namespace models\exceptions;
use Exception;
/**
* 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 EntityNotFoundException extends Exception
{
}

View File

@ -0,0 +1,26 @@
<?php
/**
* 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.
**/
namespace models\exceptions;
use Exception;
/**
* Class ValidationException
* @package models\exceptions
*/
class ValidationException extends Exception
{
}

View File

@ -0,0 +1,27 @@
<?php namespace models\main;
use models\utils\SilverstripeBaseModel;
/**
* 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 Company extends SilverstripeBaseModel
{
protected $table = 'Company';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
);
}

48
app/Models/main/File.php Normal file
View File

@ -0,0 +1,48 @@
<?php
/**
* 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.
**/
namespace models\main;
use models\utils\SilverstripeBaseModel;
/**
* Class File
* @package models\main
*/
class File extends SilverstripeBaseModel
{
protected $table = 'File';
protected $stiBaseClass = 'models\main\File';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
'Title' => 'description:json_string',
'Filename' => 'file_name:json_string',
'Content' => 'content:json_string',
'ClassName' => 'class_name',
);
/**
* @return int
*/
public function getIdentifier()
{
return (int)$this->ID;
}
}

26
app/Models/main/Image.php Normal file
View File

@ -0,0 +1,26 @@
<?php
/**
* 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.
**/
namespace models\main;
use models\utils\SilverstripeBaseModel;
/**
* Class Image
* @package models\main
*/
class Image extends File
{
protected $mtiClassType = 'abstract';
}

View File

@ -0,0 +1,38 @@
<?php
/**
* 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.
**/
namespace models\main;
use models\utils\SilverstripeBaseModel;
class Member extends SilverstripeBaseModel
{
protected $table = 'Member';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'FirstName' => 'first_name:json_string',
'Surname' => 'last_name:json_string',
'Email' => 'email:datetime_epoch',
);
/**
* @return Image
*/
public function photo()
{
return $this->hasOne('models\main\Image', 'ID', 'PhotoID')->first();
}
}

33
app/Models/main/Tag.php Normal file
View File

@ -0,0 +1,33 @@
<?php
/**
* 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.
**/
namespace models\main;
use models\utils\SilverstripeBaseModel;
/**
* Class Tag
* @package models\main
*/
class Tag extends SilverstripeBaseModel
{
protected $table = 'Tag';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Tag' => 'tag:json_string',
);
}

View File

@ -0,0 +1,39 @@
<?php namespace models\marketplace;
/**
* 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 models\utils\BaseModelEloquent;
use models\utils\IEntity;
class CompanyService extends BaseModelEloquent implements IEntity
{
protected $hidden = array('ClassName', 'MarketPlaceTypeID', 'EditedByID');
protected $table = 'CompanyService';
protected $connection = 'ss';
protected $stiClassField = 'ClassName';
protected $stiBaseClass = 'models\marketplace\CompanyService';
/**
* @return int
*/
public function getIdentifier()
{
return (int)$this->ID;
}
}

View File

@ -0,0 +1,29 @@
<?php namespace models\marketplace;
/**
* 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 Consultant extends CompanyService implements IConsultant
{
protected $connection = 'ss';
/**
* @return Office[]
*/
public function offices()
{
return $this->hasMany('models\marketplace\Office', 'ConsultantID', 'ID')->get();
}
}

View File

@ -0,0 +1,47 @@
<?php namespace models\marketplace;
/**
* 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 models\utils\IBaseRepository;
/**
* Interface ICompanyServiceRepository
* @package models\marketplace
*/
interface ICompanyServiceRepository extends IBaseRepository
{
const Status_All = 'all';
const Status_active = 'active';
const Status_non_active = 'non_active';
const Order_date = 'date';
const Order_name = 'name';
/**
* @param int $page
* @param int $per_page
* @param string $status
* @param string $order_by
* @param string $order_dir
* @return \IEntity[]
*/
public function getAll(
$page = 1,
$per_page = 1000,
$status = ICompanyServiceRepository::Status_All,
$order_by = ICompanyServiceRepository::Order_date,
$order_dir = 'asc'
);
}

View File

@ -0,0 +1,32 @@
<?php namespace models\marketplace;
/**
* 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 PublicCloudService
* @package models\marketplace
*/
class PublicCloudService extends CompanyService implements ICloudService
{
protected $connection = 'ss';
/**
* @return DataCenterRegion[]
*/
public function datacenters_regions()
{
return $this->hasMany('models\marketplace\DataCenterRegion', 'CloudServiceID', 'ID')->get();
}
}

View File

@ -1,120 +1,143 @@
<?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 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 AccessToken
* http://tools.ietf.org/html/rfc6749#section-1.4
* @package oauth2\models
*/
* Class AccessToken
* http://tools.ietf.org/html/rfc6749#section-1.4
* @package oauth2\models
*/
class AccessToken extends Token
{
/**
* @var
*/
private $auth_code;
private $auth_code;
/**
* @var
*/
private $refresh_token;
private $refresh_token;
/**
* @var string
*/
private $allowed_origins;
/**
* @var string
*/
private $allowed_origins;
/**
* @var string
*/
private $allowed_return_uris;
/**
* @var string
*/
private $allowed_return_uris;
/**
* @var string
*/
private $application_type;
/**
* @var string
*/
private $application_type;
public function __construct()
{
parent::__construct(72);
}
public function __construct()
{
parent::__construct(72);
}
/**
* @var null|int
*/
private $user_external_id;
/**
* @param $value
* @param $scope
* @param $client_id
* @param $audience
* @param $user_id
* @param $lifetime
* @param $application_type
* @param $allowed_return_uris
* @param $allowed_origins
* @return AccessToken
*/
public static function createFromParams(
$value,
$scope,
$client_id,
$audience,
$user_id,
$lifetime,
$application_type,
$allowed_return_uris,
$allowed_origins
) {
$instance = new self();
$instance->value = $value;
$instance->scope = $scope;
$instance->client_id = $client_id;
$instance->user_id = $user_id;
$instance->auth_code = null;
$instance->audience = $audience;
$instance->refresh_token = null;
$instance->lifetime = intval($lifetime);
$instance->is_hashed = false;
$instance->allowed_return_uris = $allowed_return_uris;
$instance->application_type = $application_type;
$instance->allowed_origins = $allowed_origins;
return $instance;
}
/**
* @param $value
* @param $scope
* @param $client_id
* @param $audience
* @param $user_id
* @param $user_external_id
* @param $lifetime
* @param $application_type
* @param $allowed_return_uris
* @param $allowed_origins
* @return AccessToken
*/
public static function createFromParams(
$value,
$scope,
$client_id,
$audience,
$user_id,
$user_external_id,
$lifetime,
$application_type,
$allowed_return_uris,
$allowed_origins
) {
$instance = new self();
$instance->value = $value;
$instance->scope = $scope;
$instance->client_id = $client_id;
$instance->user_id = $user_id;
$instance->user_external_id = $user_external_id;
$instance->auth_code = null;
$instance->audience = $audience;
$instance->refresh_token = null;
$instance->lifetime = intval($lifetime);
$instance->is_hashed = false;
$instance->allowed_return_uris = $allowed_return_uris;
$instance->application_type = $application_type;
$instance->allowed_origins = $allowed_origins;
public function getAuthCode()
{
return $this->auth_code;
}
return $instance;
}
public function getRefreshToken()
{
return $this->refresh_token;
}
public function getAuthCode()
{
return $this->auth_code;
}
public function getApplicationType()
{
return $this->application_type;
}
public function getRefreshToken()
{
return $this->refresh_token;
}
public function getAllowedOrigins()
{
return $this->allowed_origins;
}
public function getApplicationType()
{
return $this->application_type;
}
public function getAllowedReturnUris()
{
return $this->allowed_return_uris;
}
public function getAllowedOrigins()
{
return $this->allowed_origins;
}
public function toJSON()
{
return '{}';
}
public function getAllowedReturnUris()
{
return $this->allowed_return_uris;
}
public function fromJSON($json)
{
/**
* @return int|null
*/
public function getUserExternalId()
{
return $this->user_external_id;
}
}
public function toJSON()
{
return '{}';
}
public function fromJSON($json)
{
}
}

View File

@ -1,58 +1,69 @@
<?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 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.
**/
/**
* Interface IResourceServerContext
* Current Request OAUTH2 security context
* @package oauth2
*/
* Interface IResourceServerContext
* Current Request OAUTH2 security context
* @package oauth2
*/
interface IResourceServerContext
{
/**
* returns given scopes for current request
* @return array
*/
public function getCurrentScope();
/**
* returns given scopes for current request
* @return array
*/
public function getCurrentScope();
/**
* gets current access token values
* @return string
*/
public function getCurrentAccessToken();
/**
* gets current access token values
* @return string
*/
public function getCurrentAccessToken();
/**
* gets current access token lifetime
* @return mixed
*/
public function getCurrentAccessTokenLifetime();
/**
* gets current access token lifetime
* @return mixed
*/
public function getCurrentAccessTokenLifetime();
/**
* gets current client id
* @return string
*/
public function getCurrentClientId();
/**
* gets current client id
* @return string
*/
public function getCurrentClientId();
/**
* gets current user id (if was set)
* @return int
*/
public function getCurrentUserId();
/**
* gets current user id (if was set)
* @return int|null
*/
public function getCurrentUserId();
/**
* @param array $auth_context
* @return void
*/
public function setAuthorizationContext(array $auth_context);
/**
* @return int|null
*/
public function getCurrentUserExternalId();
/**
* @return string
*/
public function getApplicationType();
/**
* @param array $auth_context
* @return void
*/
public function setAuthorizationContext(array $auth_context);
}

View File

@ -1,76 +1,93 @@
<?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 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 ResourceServerContext
* @package models\oauth2
*/
class ResourceServerContext implements IResourceServerContext
* Class ResourceServerContext
* @package models\oauth2
*/
final class ResourceServerContext implements IResourceServerContext
{
/**
* @var array
*/
private $auth_context;
/**
* @var array
*/
private $auth_context;
/**
* @return array
*/
public function getCurrentScope()
{
return isset($this->auth_context['scope'])? explode(' ', $this->auth_context['scope']):array();
}
/**
* @return array
*/
public function getCurrentScope()
{
return isset($this->auth_context['scope']) ? explode(' ', $this->auth_context['scope']) : array();
}
/**
* @return null|string
*/
public function getCurrentAccessToken()
{
return isset($this->auth_context['access_token'])?$this->auth_context['access_token']:null;
}
/**
* @return null|string
*/
public function getCurrentAccessToken()
{
return isset($this->auth_context['access_token']) ? $this->auth_context['access_token'] : null;
}
/**
* @return null|string
*/
public function getCurrentAccessTokenLifetime()
{
return isset($this->auth_context['expires_in'])?$this->auth_context['expires_in']:null;
}
/**
* @return null|string
*/
public function getCurrentAccessTokenLifetime()
{
return isset($this->auth_context['expires_in']) ? $this->auth_context['expires_in'] : null;
}
/**
* @return null
*/
public function getCurrentClientId()
{
return isset($this->auth_context['client_id'])?$this->auth_context['client_id']:null;
}
/**
* @return null|string
*/
public function getCurrentClientId()
{
return isset($this->auth_context['client_id']) ? $this->auth_context['client_id'] : null;
}
/**
* @return null|int
*/
public function getCurrentUserId()
{
return isset($this->auth_context['user_id'])?intval($this->auth_context['user_id']):null;
}
/**
* @return null|int
*/
public function getCurrentUserId()
{
return isset($this->auth_context['user_id']) ? intval($this->auth_context['user_id']) : null;
}
/**
* @param array $auth_context
* @return void
*/
public function setAuthorizationContext(array $auth_context)
{
$this->auth_context = $auth_context;
}
/**
* @param array $auth_context
* @return void
*/
public function setAuthorizationContext(array $auth_context)
{
$this->auth_context = $auth_context;
}
/**
* @return int
*/
public function getCurrentUserExternalId()
{
return isset($this->auth_context['user_external_id']) ? intval($this->auth_context['user_external_id']) : null;
}
/**
* @return string
*/
public function getApplicationType()
{
return isset($this->auth_context['application_type']) ? $this->auth_context['application_type'] : null;
}
}

View File

@ -1,90 +1,93 @@
<?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 DateTime;
use DateInterval;
use DateTimeZone;
/**
* Class Token
* Defines the common behavior for all emitted tokens
* @package oauth2\models
*/
* 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 Token
* Defines the common behavior for all emitted tokens
* @package oauth2\models
*/
abstract class Token
{
const DefaultByteLength = 32;
const DefaultByteLength = 32;
protected $value;
protected $lifetime;
protected $value;
protected $lifetime;
protected $client_id;
protected $len;
protected $scope;
protected $audience;
protected $from_ip;
protected $is_hashed;
protected $user_id;
protected $client_id;
protected $len;
protected $scope;
protected $audience;
protected $from_ip;
protected $is_hashed;
/**
* @var null|int
*/
protected $user_id;
public function __construct($len = self::DefaultByteLength)
{
$this->len = $len;
$this->is_hashed = false;
}
public function __construct($len = self::DefaultByteLength)
{
$this->len = $len;
$this->is_hashed = false;
}
public function getValue()
{
return $this->value;
}
public function getValue()
{
return $this->value;
}
public function getLifetime()
{
return intval($this->lifetime);
}
public function getLifetime()
{
return intval($this->lifetime);
}
public function getScope()
{
return $this->scope;
}
public function getScope()
{
return $this->scope;
}
public function getClientId()
{
return $this->client_id;
}
public function getClientId()
{
return $this->client_id;
}
public function getAudience()
{
return $this->audience;
}
public function getAudience()
{
return $this->audience;
}
public function getFromIp()
{
return $this->from_ip;
}
public function getFromIp()
{
return $this->from_ip;
}
public function getUserId()
{
return $this->user_id;
}
/**
* @return null|int
*/
public function getUserId()
{
return $this->user_id;
}
public function isHashed()
{
return $this->is_hashed;
}
public function isHashed()
{
return $this->is_hashed;
}
public abstract function toJSON();
public abstract function toJSON();
public abstract function fromJSON($json);
public abstract function fromJSON($json);
}

View File

@ -0,0 +1,199 @@
<?php namespace models\resource_server;
/**
* 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 GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Config;
use libs\oauth2\InvalidGrantTypeException;
use libs\oauth2\OAuth2InvalidIntrospectionResponse;
use libs\oauth2\OAuth2Protocol;
use libs\utils\ConfigurationException;
use libs\utils\ICacheService;
use models\oauth2\AccessToken;
use Log;
/**
* Class AccessTokenService
* @package models\resource_server
*/
final class AccessTokenService implements IAccessTokenService
{
/**
* @var ICacheService
*/
private $cache_service;
/**
* @param ICacheService $cache_service
*/
public function __construct(ICacheService $cache_service)
{
$this->cache_service = $cache_service;
}
/**
* @param string $token_value
* @return AccessToken
* @throws \Exception
*/
public function get($token_value)
{
$token = null;
$cache_lifetime = intval(Config::get('server.access_token_cache_lifetime', 300));
if($this->cache_service->exists(md5($token_value).'.revoked'))
{
Log::debug(sprintf('token marked as revoked on cache (%s)',md5($token_value) ));
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
$token_info = $this->cache_service->getHash(md5($token_value), array
(
'access_token',
'scope',
'client_id',
'audience',
'user_id',
'user_external_id',
'expires_in',
'application_type',
'allowed_return_uris',
'allowed_origins'
));
if (count($token_info) === 0)
{
Log::debug("getting token from remote call ...");
$token_info = $this->makeRemoteCall($token_value);
$this->cache_service->storeHash(md5($token_value), $token_info, $cache_lifetime );
}
else
{
$cache_remaining_lifetime = intval($this->cache_service->ttl(md5($token_value)));
$expires_in = intval($token_info['expires_in']);
$token_info['expires_in'] = $expires_in - ( $cache_lifetime - $cache_remaining_lifetime);
Log::debug
(
sprintf
(
"original token life time %s - current token life time %s - token cache remaining lifetime %s",
$expires_in,
$token_info['expires_in'],
$cache_remaining_lifetime
)
);
}
$token = AccessToken::createFromParams
(
$token_info['access_token'],
$token_info['scope'],
$token_info['client_id'],
$token_info['audience'],
isset($token_info['user_id'])? intval($token_info['user_id']):null,
isset($token_info['user_external_id'])? intval($token_info['user_external_id']) : null,
(int)$token_info['expires_in'],
$token_info['application_type'],
isset($token_info['allowed_return_uris']) ? $token_info['allowed_return_uris'] : null,
isset($token_info['allowed_origins']) ? $token_info['allowed_origins'] : null
);
$str_token_info = "";
foreach($token_info as $k => $v){
$str_token_info .= sprintf("-%s=%s-", $k, $v);
}
Log::debug("token info : ". $str_token_info);
if($token->getLifetime() <= 0)
{
Log::debug("token lifetime is < 0 ... retrieving from IDP");
$this->cache_service->delete(md5($token_value));
$token = $this->get($token_value);
}
return $token;
}
/**
* @param $token_value
* @return mixed
* @throws ConfigurationException
* @throws InvalidGrantTypeException
* @throws OAuth2InvalidIntrospectionResponse
* @throws \Exception
*/
private function makeRemoteCall($token_value)
{
try {
$client = new Client([
'defaults' => [
'timeout' => Config::get('curl.timeout', 60),
'allow_redirects' => Config::get('curl.allow_redirects', false),
'verify' => Config::get('curl.verify_ssl_cert', true)
]
]);
$client_id = Config::get('app.openstackid_client_id', '');
$client_secret = Config::get('app.openstackid_client_secret', '');
$auth_server_url = Config::get('app.openstackid_base_url', '');
if (empty($client_id)) {
throw new ConfigurationException('app.openstackid_client_id param is missing!');
}
if (empty($client_secret)) {
throw new ConfigurationException('app.openstackid_client_secret param is missing!');
}
if (empty($auth_server_url)) {
throw new ConfigurationException('app.openstackid_base_url param is missing!');
}
$response = $client->post(
$auth_server_url . '/oauth2/token/introspection',
[
'query' => ['token' => $token_value],
'headers' => ['Authorization' => " Basic " . base64_encode($client_id . ':' . $client_secret)]
]
);
$content_type = $response->getHeader('content-type');
if(!str_contains($content_type, 'application/json'))
{
// invalid content type
throw new \Exception($response->getBody());
}
$token_info = $response->json();
return $token_info;
} catch (RequestException $ex)
{
Log::error($ex->getMessage());
$response = $ex->getResponse();
$content_type = $response->getHeader('content-type');
$is_json = str_contains($content_type, 'application/json');
$body = ($is_json) ? $response->json(): $response->getBody();
$code = $response->getStatusCode();
if ($code === 400 && $is_json && isset($body['error']) && $body['error'] === OAuth2Protocol::OAuth2Protocol_Error_InvalidToken)
{
$this->cache_service->setSingleValue(md5($token_value).'.revoked', md5($token_value));
throw new InvalidGrantTypeException($body['error']);
}
throw new OAuth2InvalidIntrospectionResponse(sprintf('http code %s', $ex->getCode()));
}
}
}

View File

@ -13,6 +13,7 @@
**/
use models\utils\BaseModelEloquent;
/**
* Class ApiEndpoint
* @package models\resource_server
@ -131,4 +132,12 @@ class ApiEndpoint extends BaseModelEloquent implements IApiEndpoint
{
return (bool)$this->allow_credentials;
}
/**
* @return int
*/
public function getIdentifier()
{
return (int)$this->id;
}
}

View File

@ -0,0 +1,31 @@
<?php namespace models\resource_server;
/**
* 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 libs\oauth2\OAuth2InvalidIntrospectionResponse;
use models\oauth2\AccessToken;
/**
* Interface IAccessTokenService
* @package models\resource_server
*/
interface IAccessTokenService
{
/**
* @param string $token_value
* @return AccessToken
* @throws OAuth2InvalidIntrospectionResponse
*/
public function get($token_value);
}

View File

@ -0,0 +1,93 @@
<?php namespace models\resource_server;
/**
* 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 models\utils\IEntity;
/**
* Interface IApiEndpoint
* @package models\resource_server
*/
interface IApiEndpoint extends IEntity
{
/**
* @return string
*/
public function getRoute();
/**
* @return string
*/
public function getHttpMethod();
/**
* @return string
*/
public function getName();
/**
* @param string $route
* @return void
*/
public function setRoute($route);
/**
* @param string $http_method
* @return void
*/
public function setHttpMethod($http_method);
/**
* @param string $name
* @return void
*/
public function setName($name);
/**
* @return string
*/
public function getScope();
/**
* @return bool
*/
public function isActive();
/**
* @param bool $active
* @return void
*/
public function setStatus($active);
/**
* @return bool
*/
public function supportCORS();
/**
* @return bool
*/
public function supportCredentials();
/**
* @return IApi
*/
public function api();
/**
* @return IApiScope[]
*/
public function scopes();
}

View File

@ -0,0 +1,35 @@
<?php namespace models\summit;
/**
* 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\Order;
use utils\PagingResponse;
use utils\PagingInfo;
use utils\Filter;
/**
* Interface ISpeakerRepository
* @package models\repositories
*/
interface ISpeakerRepository
{
/**
* @param Summit $summit
* @param PagingInfo $paging_info
* @param Filter|null $filter
* @param Order|null $order
* @return PagingResponse
*/
public function getSpeakersBySummit(Summit $summit, PagingInfo $paging_info, Filter $filter = null, Order $order = null);
}

View File

@ -0,0 +1,30 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\utils\IBaseRepository;
/**
* Interface ISummitEventRepository
* @package models\summit
*/
interface ISummitEventRepository extends IBaseRepository
{
/**
* @param SummitEvent $event
* @return SummitEvent[]
*/
public function getPublishedOnSameTimeFrame(SummitEvent $event);
}

View File

@ -0,0 +1,23 @@
<?php namespace models\summit;
use models\utils\IBaseRepository;
/**
* 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.
**/
interface ISummitRepository extends IBaseRepository
{
/**
* @return Summit
*/
public function getCurrent();
}

View File

@ -0,0 +1,137 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\main\Tag;
use DB;
/**
* Class Presentation
* @package models\summit
*/
class Presentation extends SummitEvent
{
protected $table = 'Presentation';
protected $mtiClassType = 'concrete';
/**
* @var bool
*/
private $from_speaker;
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Title' => 'title:json_string',
'Description' => 'description:json_string',
'StartDate' => 'start_date:datetime_epoch',
'EndDate' => 'end_date:datetime_epoch',
'LocationID' => 'location_id:json_int',
'TypeID' => 'type_id:json_int',
'ClassName' => 'class_name',
'CategoryID' => 'track_id:json_int',
'ModeratorID' => 'moderator_speaker_id:json_int',
'Level' => 'level',
'AllowFeedBack' => 'allow_feedback:json_boolean',
);
/**
* @return PresentationSpeaker[]
*/
public function speakers()
{
return $this->belongsToMany('models\summit\PresentationSpeaker','Presentation_Speakers','PresentationID','PresentationSpeakerID')->get();
}
public function getSpeakerIds()
{
$ids = array();
foreach($this->speakers() as $speaker)
{
array_push($ids, intval($speaker->ID));
}
return $ids;
}
public function setFromSpeaker()
{
$this->from_speaker = true;
}
/**
* @return array
*/
public function toArray()
{
$values = parent::toArray();
if(!$this->from_speaker)
$values['speakers'] = $this->getSpeakerIds();
$slides = array();
foreach($this->slides() as $s)
{
array_push($slides, $s->toArray());
}
$values['slides'] = $slides;
$videos = array();
foreach($this->videos() as $v)
{
array_push($videos, $v->toArray());
}
$values['videos'] = $videos;
return $values;
}
/**
* @return PresentationVideo[]
*/
public function videos()
{
$bindings = array('presentation_id' => $this->ID);
$rows = DB::connection('ss')->select("select * from `PresentationVideo` left join `PresentationMaterial` on `PresentationVideo`.`ID` = `PresentationMaterial`.`ID`
where `PresentationMaterial`.`PresentationID` = :presentation_id and `PresentationMaterial`.`PresentationID` is not null", $bindings);
$videos = array();
foreach($rows as $row)
{
$instance = new PresentationVideo;
$instance->setRawAttributes((array)$row, true);
array_push($videos, $instance);
}
return $videos;
}
/**
* @return PresentationSlide[]
*/
public function slides()
{
$bindings = array('presentation_id' => $this->ID);
$rows = DB::connection('ss')->select("select * from `PresentationSlide` left join `PresentationMaterial` on `PresentationSlide`.`ID` = `PresentationMaterial`.`ID`
where `PresentationMaterial`.`PresentationID` = :presentation_id and `PresentationMaterial`.`PresentationID` is not null", $bindings);
$slides = array();
foreach($rows as $row)
{
$instance = new PresentationSlide;
$instance->setRawAttributes((array)$row, true);
array_push($slides, $instance);
}
return $slides;
}
}

View File

@ -0,0 +1,57 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\utils\SilverstripeBaseModel;
/**
* Class PresentationCategory
* @package models\summit
*/
class PresentationCategory extends SilverstripeBaseModel
{
protected $table = 'PresentationCategory';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Title' => 'name:json_string',
);
/**
* @return PresentationCategoryGroup[]
*/
public function groups()
{
return $this->belongsToMany('models\summit\PresentationCategoryGroup','PresentationCategoryGroup_Categories','PresentationCategoryID', 'PresentationCategoryGroupID')->get();
}
/**
* @return array
*/
public function toArray()
{
$values = parent::toArray();
$groups = array();
foreach($this->groups() as $g)
{
array_push($groups, intval($g->ID));
}
$values['track_groups'] = $groups;
return $values;
}
}

View File

@ -0,0 +1,67 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\utils\SilverstripeBaseModel;
/**
* Class PresentationCategoryGroup
* @package models\summit
*/
class PresentationCategoryGroup extends SilverstripeBaseModel
{
protected $table = 'PresentationCategoryGroup';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
'Color' => 'color:json_string',
'Description' => 'description:json_string',
);
/**
* @return PresentationCategory[]
*/
public function categories()
{
return $this->belongsToMany('models\summit\PresentationCategory','PresentationCategoryGroup_Categories','PresentationCategoryGroupID','PresentationCategoryID')->get();
}
/**
* @return array
*/
public function toArray()
{
$values = parent::toArray();
$color = isset($values['color']) ? $values['color']:'';
if(empty($color))
$color = 'f0f0ee';
if (strpos($color,'#') === false) {
$color = '#'.$color;
}
$values['color'] = $color;
$categories = array();
foreach($this->categories() as $c)
{
array_push($categories, intval($c->ID));
}
$values['tracks'] = $categories;
return $values;
}
}

View File

@ -0,0 +1,41 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\utils\SilverstripeBaseModel;
/**
* Class PresentationMaterial
* @package models\summit
*/
class PresentationMaterial extends SilverstripeBaseModel
{
protected $table = 'PresentationMaterial';
protected $stiBaseClass = 'models\summit\PresentationMaterial';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_text',
'Description' => 'description:json_text',
'DisplayOnSite' => 'display_on_site:json_boolean',
'Featured' => 'featured:json_boolean',
'PresentationID' => 'presentation_id:json_int',
);
}

View File

@ -0,0 +1,59 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\main\Image;
use Config;
/**
* Class PresentationSlide
* @package models\summit
*/
class PresentationSlide extends PresentationMaterial
{
protected $table = 'PresentationSlide';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_text',
'Description' => 'description:json_text',
'DisplayOnSite' => 'display_on_site:json_boolean',
'Featured' => 'featured:json_boolean',
'PresentationID' => 'presentation_id:json_int',
'Link' => 'link:json_text',
);
/**
* @return Image
*/
public function slide()
{
return $this->hasOne('models\main\Image', 'ID', 'SlideID')->first();
}
public function toArray()
{
$values = parent::toArray();
$slide = $this->slide();
if(!is_null($slide))
{
$values['link'] = Config::get("server.assets_base_url", 'https://www.openstack.org/'). $slide->Filename;
}
return $values;
}
}

View File

@ -0,0 +1,99 @@
<?php
/**
* 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.
**/
namespace models\summit;
use DB;
use models\utils\SilverstripeBaseModel;
use Config;
use libs\utils\JsonUtils;
/**
* Class PresentationSpeaker
* @package models\summit
*/
class PresentationSpeaker extends SilverstripeBaseModel
{
protected $table = 'PresentationSpeaker';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'FirstName' => 'first_name:json_string',
'LastName' => 'last_name:json_string',
'Title' => 'title:json_string',
'Bio' => 'bio:json_string',
'IRCHandle' => 'irc',
'TwitterHandle' => 'twitter',
'MemberID' => 'member_id:json_int',
);
/**
* @return Presentation[]
*/
public function presentations()
{
return $this->belongsToMany('models\summit\Presentation','Presentation_Speakers','PresentationSpeakerID','PresentationID')->get();
}
public function getPresentationIds()
{
$ids = array();
foreach($this->presentations() as $p)
{
array_push($ids, intval($p->ID));
}
return $ids;
}
/**
* @return Image
*/
public function photo()
{
return $this->hasOne('models\main\Image', 'ID', 'PhotoID')->first();
}
/**
* @return Member
*/
public function member()
{
return $this->hasOne('models\main\Member', 'ID', 'MemberID')->first();
}
public function toArray()
{
$values = parent::toArray();
$values['presentations'] = $this->getPresentationIds();
$member = $this->member();
$values['pic'] = Config::get("server.assets_base_url", 'https://www.openstack.org/'). 'profile_images/speakers/'. $this->ID;
if(!is_null($member))
{
$values['gender'] = $member->Gender;
}
return $values;
}
/**
* @param int $presentation_id
* @return Presentation
*/
public function getPresentation($presentation_id)
{
return $this->belongsToMany('models\summit\Presentation','Presentation_Speakers','PresentationSpeakerID', 'PresentationID')
->where('PresentationID','=',$presentation_id)
->first();
}
}

View File

@ -0,0 +1,38 @@
<?php
/**
* 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.
**/
namespace models\summit;
/**
* Class PresentationVideo
* @package models\summit
*/
class PresentationVideo extends PresentationMaterial
{
protected $table = 'PresentationVideo';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_text',
'Description' => 'description:json_text',
'DisplayOnSite' => 'display_on_site:json_boolean',
'Featured' => 'featured:json_boolean',
'PresentationID' => 'presentation_id:json_int',
'YouTubeID' => 'youtube_id:json_text',
);
}

View File

@ -0,0 +1,490 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\main\Company;
use models\main\Image;
use DB;
use models\utils\SilverstripeBaseModel;
use utils\Filter;
use utils\Order;
/**
* Class Summit
* @package models\summit
*/
class Summit extends SilverstripeBaseModel
{
protected $table = 'Summit';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
'SummitBeginDate' => 'start_date:datetime_epoch',
'SummitEndDate' => 'end_date:datetime_epoch',
'StartShowingVenuesDate' => 'start_showing_venues_date:datetime_epoch',
'Active' => 'active:json_boolean',
);
protected $hidden = array
(
);
/**
* @return SummitAbstractLocation[]
*/
public function locations()
{
$res = $this->hasMany('models\summit\SummitAbstractLocation', 'SummitID', 'ID')->get();
$locations = array();
foreach($res as $l)
{
$class = 'models\\summit\\'.$l->ClassName;
$entity = $class::find($l->ID);
array_push($locations, $entity);
}
return $locations;
}
/**
* @return Image
*/
public function logo()
{
return $this->hasOne('models\main\Image', 'ID', 'LogoID')->first();
}
/**
* @param int $location_id
* @return SummitAbstractLocation
*/
public function getLocation($location_id)
{
$location = $this->hasMany('models\summit\SummitAbstractLocation', 'SummitID', 'ID')->where('SummitAbstractLocation.ID', '=', $location_id)->get()->first();
if(!is_null($location))
{
$class = 'models\\summit\\'.$location->ClassName;
$location = $class::find($location->ID);
}
return $location;
}
/**
* @return SummitEventType[]
*/
public function event_types()
{
return $this->hasMany('models\summit\SummitEventType', 'SummitID', 'ID')->get();
}
/**
* @param int $event_type_id
* @return SummitEventType
*/
public function getEventType($event_type_id)
{
return $this->hasMany('models\summit\SummitEventType', 'SummitID', 'ID')->where('ID','=', intval($event_type_id))->first();
}
/**
* @return SummitType[]
*/
public function summit_types()
{
return $this->hasMany('models\summit\SummitType', 'SummitID', 'ID')->get();
}
/**
* @param int $summit_type_id
* @return SummitType
*/
public function getSummitType($summit_type_id)
{
return $this->hasMany('models\summit\SummitType', 'SummitID', 'ID')->where('ID','=', intval($summit_type_id))->first();
}
/**
* @return SummitTicketType[]
*/
public function ticket_types()
{
return $this->hasMany('models\summit\SummitTicketType', 'SummitID', 'ID')->get();
}
/**
* @param int $page
* @param int $per_page
* @param Filter|null $filter
* @param Order|null $order
* @return array
*/
public function attendees($page = 1, $per_page = 100, Filter $filter = null, Order $order = null)
{
$rel = $this->hasMany('models\summit\SummitAttendee', 'SummitID', 'ID')->join('Member', 'Member.ID', '=', 'SummitAttendee.MemberID');
if(!is_null($filter))
{
$filter->apply2Relation($rel, array
(
'first_name' => 'Member.FirstName',
'last_name' => 'Member.Surname',
'email' => 'Member.Email',
));
}
if(!is_null($order))
{
$order->apply2Relation($rel, array
(
'first_name' => 'Member.FirstName',
'last_name' => 'Member.Surname',
));
}
$pagination_result = $rel->paginate($per_page);
$total = $pagination_result->total();
$items = $pagination_result->items();
$per_page = $pagination_result->perPage();
$current_page = $pagination_result->currentPage();
$last_page = $pagination_result->lastPage();
return array ($total,$per_page, $current_page, $last_page, $items);
}
/**
* @param int $page
* @param int $per_page
* @param Filter|null $filter
* @return array
*/
public function schedule($page = 1, $per_page = 100, Filter $filter = null)
{
$rel = $this->hasMany('models\summit\SummitEvent', 'SummitID', 'ID')
->where('Published','=','1');
if(!is_null($filter))
{
$filter->apply2Relation($rel, array
(
'title' => 'SummitEvent.Title',
'start_date' => 'SummitEvent.StartDate:datetime_epoch',
'end_date' => 'SummitEvent.EndDate:datetime_epoch',
));
}
$tags = !is_null($filter) ? $filter->getFilter('tags'): null;
if(!is_null($tags)) {
$op = $tags->getOperator();
$val = $tags->getValue();
$rel->getBaseQuery()->whereRaw(" EXISTS ( SELECT T.ID FROM Tag T INNER JOIN SummitEvent_Tags ST ON ST.TagID = T.ID WHERE ST.SummitEventID = SummitEvent.ID AND T.Tag {$op} '{$val}' ) ");
}
$rel = $rel->orderBy('StartDate','asc')->orderBy('EndDate','asc');
$pagination_result = $rel->paginate($per_page);
$total = $pagination_result->total();
$items = $pagination_result->items();
$per_page = $pagination_result->perPage();
$current_page = $pagination_result->currentPage();
$last_page = $pagination_result->lastPage();
$events = array();
foreach($items as $e)
{
$class = 'models\\summit\\'.$e->ClassName;
$entity = $class::find($e->ID);
array_push($events, $entity);
}
return array($total,$per_page, $current_page, $last_page, $events);
}
/**
* @param int $page
* @param int $per_page
* @param Filter|null $filter
* @return array
*/
public function events($page = 1, $per_page = 100, Filter $filter = null)
{
$rel = $this->hasMany('models\summit\SummitEvent', 'SummitID', 'ID');
if(!is_null($filter))
{
$filter->apply2Relation($rel, array
(
'title' => 'SummitEvent.Title',
'start_date' => 'SummitEvent.StartDate:datetime_epoch',
'end_date' => 'SummitEvent.EndDate:datetime_epoch',
));
}
$tags = !is_null($filter) ? $filter->getFilter('tags'): null;
if(!is_null($tags)) {
$op = $tags->getOperator();
$val = $tags->getValue();
$rel->getBaseQuery()->whereRaw(" EXISTS ( SELECT T.ID FROM Tag T INNER JOIN SummitEvent_Tags ST ON ST.TagID = T.ID WHERE ST.SummitEventID = SummitEvent.ID AND T.Tag {$op} '{$val}' ) ");
}
$rel = $rel->orderBy('StartDate','asc')->orderBy('EndDate','asc');
$pagination_result = $rel->paginate($per_page);
$total = $pagination_result->total();
$items = $pagination_result->items();
$per_page = $pagination_result->perPage();
$current_page = $pagination_result->currentPage();
$last_page = $pagination_result->lastPage();
$events = array();
foreach($items as $e)
{
$class = 'models\\summit\\'.$e->ClassName;
$entity = $class::find($e->ID);
array_push($events, $entity);
}
return array($total,$per_page, $current_page, $last_page, $events);
}
/**
* @param int $member_id
* @return SummitAttendee
*/
public function getAttendeeByMemberId($member_id)
{
return $this->hasMany('models\summit\SummitAttendee', 'SummitID', 'ID')->where('MemberID','=',$member_id)->first();
}
/**
* @param int $attendee_id
* @return SummitAttendee
*/
public function getAttendeeById($attendee_id)
{
return $this->hasMany('models\summit\SummitAttendee', 'SummitID', 'ID')->where('SummitAttendee.ID','=',$attendee_id)->first();
}
/**
* @param int $event_id
* @return null|SummitEvent
*/
public function getScheduleEvent($event_id)
{
$e = $this->hasMany('models\summit\SummitEvent', 'SummitID', 'ID')
->where('SummitEvent.ID','=', intval($event_id))
->where('Published','=','1')
->first();
if(is_null($e)) return null;
$class = 'models\\summit\\'.$e->ClassName;
return $class::find($e->ID);
}
/**
* @param int $event_id
* @return null|SummitEvent
*/
public function getEvent($event_id)
{
$e = $this->hasMany('models\summit\SummitEvent', 'SummitID', 'ID')
->where('SummitEvent.ID','=', intval($event_id))
->first();
if(is_null($e)) return null;
$class = 'models\\summit\\'.$e->ClassName;
return $class::find($e->ID);
}
/**
* @return PresentationCategory[]
*/
public function presentation_categories()
{
return $this->hasMany('models\summit\PresentationCategory', 'SummitID', 'ID')->get();
}
/**
* @return PresentationCategoryGroup[]
*/
public function category_groups()
{
return $this->hasMany('models\summit\PresentationCategoryGroup', 'SummitID', 'ID')->get();
}
/**
* @param int $group_id
* @return null|PresentationCategoryGroup
*/
public function getCategoryGroup($group_id)
{
return $this->hasMany('models\summit\PresentationCategoryGroup', 'SummitID', 'ID')
->where('PresentationCategoryGroup.ID','=', intval($group_id))
->first();
}
public function sponsors()
{
$summit_id = $this->ID;
$rows = DB::connection('ss')->select("SELECT DISTINCT C.* FROM SummitEvent_Sponsors S
INNER JOIN SummitEvent E ON E.ID = S.SummitEventID AND E.SummitID = {$summit_id}
INNER JOIN Company C ON C.ID = S.CompanyID");
$sponsors = array();
foreach($rows as $row)
{
$instance = new Company;
$instance->setRawAttributes((array)$row, true);
array_push($sponsors, $instance);
}
return $sponsors;
}
/**
* @param int $speaker_id
* @return null|PresentationSpeaker
*/
public function getSpeakerById($speaker_id)
{
return $this->hasMany('models\summit\PresentationSpeaker', 'SummitID', 'ID')->where('PresentationSpeaker.ID','=', intval($speaker_id))->first();
}
/**
* @param int $member_id
* @return null|PresentationSpeaker
*/
public function getSpeakerByMemberId($member_id)
{
return $this->hasMany('models\summit\PresentationSpeaker', 'SummitID', 'ID')->where('PresentationSpeaker.MemberID','=', intval($member_id))->first();
}
/**
* @param int|null $from_id
* @param \DateTime|null $from_date
* @return SummitEntityEvent[]
*/
public function getEntityEvents($from_id = null, \DateTime $from_date = null)
{
$relation = $this->hasMany('models\summit\SummitEntityEvent', 'SummitID', 'ID');
if(!is_null($from_id))
{
$relation = $relation->where('SummitEntityEvent.ID','>', intval($from_id));
}
if(!is_null($from_date))
{
$relation = $relation->where('SummitEntityEvent.Created','>=', $from_date);
}
return $relation
->orderBy('Created','asc')
->get();
}
public function toArray()
{
$values = parent::toArray();
$time_zone_list = timezone_identifiers_list();
$time_zone_id = $this->TimeZone;
$values['time_zone'] = null;
if(!empty($time_zone_id) && isset($time_zone_list[$time_zone_id]))
{
$time_zone_name = $time_zone_list[$time_zone_id];
$time_zone = new \DateTimeZone($time_zone_name);
$time_zone_info = $time_zone->getLocation();
$time_zone_info['name'] = $time_zone->getName();
$now = new \DateTime("now", $time_zone);
$time_zone_info['offset'] = $time_zone->getOffset($now);
$values['time_zone'] = $time_zone_info;
}
$values['logo'] = ($this->logo() !== null) ? Config::get("server.assets_base_url", 'https://www.openstack.org/'). $this->logo()->photo()->Filename : null;
if(empty($values['name']))
{
$values['name'] = $this->Title;
}
return $values;
}
/**
* @param $value
* @return null|string
*/
public function convertDateFromTimeZone2UTC($value)
{
$time_zone_id = $this->TimeZone;
if(empty($time_zone_id)) return $value;
$time_zone_list = timezone_identifiers_list();
if(isset($time_zone_list[$time_zone_id]) && !empty($value))
{
$utc_timezone = new \DateTimeZone("UTC");
$time_zone_name = $time_zone_list[$time_zone_id];
$time_zone = new \DateTimeZone($time_zone_name);
$date = new \DateTime($value, $time_zone);
$date->setTimezone($utc_timezone);
return $date->format("Y-m-d H:i:s");
}
return null;
}
/**
* @param $value
* @return null|string
*/
public function convertDateFromUTC2TimeZone($value)
{
$time_zone_id = $this->TimeZone;
if(empty($time_zone_id)) return $value;
$time_zone_list = timezone_identifiers_list();
if(isset($time_zone_list[$time_zone_id]) && !empty($value))
{
$utc_timezone = new \DateTimeZone("UTC");
$time_zone_name = $time_zone_list[$time_zone_id];
$time_zone = new \DateTimeZone($time_zone_name);
$date = new \DateTime($value, $utc_timezone);
$date->setTimezone($time_zone);
return $date->format("Y-m-d H:i:s");
}
return null;
}
/**
* @param SummitEvent $summit_event
* @return bool
*/
public function isEventInsideSummitDuration(SummitEvent $summit_event)
{
$event_start_date = $summit_event->StartDate;
$event_end_date = $summit_event->EndDate;
$summit_start_date = new \DateTime($this->convertDateFromUTC2TimeZone($this->SummitBeginDate));
$summit_end_date = new \DateTime($this->convertDateFromUTC2TimeZone($this->SummitEndDate));
return $event_start_date >= $summit_start_date && $event_start_date <= $summit_end_date &&
$event_end_date <= $summit_end_date && $event_end_date >= $event_start_date;
}
/**
* @return \DateTime
*/
public function getLocalBeginDate()
{
return new \DateTime($this->convertDateFromUTC2TimeZone($this->SummitBeginDate));
}
/**
* @return \DateTime
*/
public function getLocalEndDate()
{
return new \DateTime($this->convertDateFromUTC2TimeZone($this->SummitEndDate));
}
}

View File

@ -0,0 +1,49 @@
<?php
/**
* 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.
**/
namespace models\summit;
use models\utils\IEntity;
use models\utils\SilverstripeBaseModel;
/**
* Class SummitAbstractLocation
* @package models\summit
*/
class SummitAbstractLocation extends SilverstripeBaseModel implements IEntity
{
protected $table = 'SummitAbstractLocation';
protected $stiBaseClass = 'models\summit\SummitAbstractLocation';
protected $mtiClassType = 'concrete';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'Name' => 'name:json_string',
'Description' => 'description:json_string',
'ClassName' => 'class_name',
'LocationType' => 'location_type',
);
/**
* @return int
*/
public function getIdentifier()
{
return (int)$this->ID;
}
}

View File

@ -0,0 +1,21 @@
<?php
/**
* 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.
**/
namespace models\summit;
class SummitAirport extends SummitExternalLocation
{
protected $mtiClassType = 'concrete';
}

View File

@ -0,0 +1,190 @@
<?php
/**
* 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.
**/
namespace models\summit;
use libs\utils\JsonUtils;
use models\exceptions\ValidationException;
use models\utils\SilverstripeBaseModel;
use DB;
use Config;
/**
* Class SummitAttendee
* @package models\summit
*/
class SummitAttendee extends SilverstripeBaseModel
{
protected $table = 'SummitAttendee';
protected $array_mappings = array
(
'ID' => 'id:json_int',
'SummitHallCheckedIn' => 'summit_hall_checked_in:json_boolean',
'SummitHallCheckedInDate' => 'summit_hall_checked_in_date:datetime_epoch',
'SharedContactInfo' => 'shared_contact_info:json_boolean',
'MemberID' => 'member_id:json_int',
);
/**
* @return SummitEvent[]
*/
public function schedule()
{
$res = $this->belongsToMany
(
'models\summit\SummitEvent',
'SummitAttendee_Schedule',
'SummitAttendeeID',
'SummitEventID'
)->withPivot('IsCheckedIn')->get();
$events = array();
foreach($res as $e)
{
$class = 'models\\summit\\'.$e->ClassName;
$entity = $class::find($e->ID);
$entity->attributes['IsCheckedIn'] = $e->pivot->IsCheckedIn;
array_push($events, $entity);
}
return $events;
}
/**
* @return SummitEventFeedback[]
*/
public function emitted_feedback(){
return SummitEventFeedback::where('OwnerID', '=', $this->MemberID)->orderBy('ID','asc')->get();
}
/**
* @return int[]
*/
public function getScheduleIds()
{
$res = $this->belongsToMany
(
'models\summit\SummitEvent',
'SummitAttendee_Schedule',
'SummitAttendeeID',
'SummitEventID'
)->withPivot('IsCheckedIn')->get();
$ids = array();
foreach($res as $e)
{
array_push($ids, intval($e->ID));
}
return $ids;
}
public function add2Schedule(SummitEvent $event)
{
if($this->isOnSchedule($event)) throw new ValidationException(sprintf('Event %s already belongs to attendee %s schedule.', $event->ID, $this->ID));
$this->belongsToMany
(
'models\summit\SummitEvent',
'SummitAttendee_Schedule',
'SummitAttendeeID',
'SummitEventID'
)->attach($event->ID,['IsCheckedIn' => false] );
return true;
}
public function removeFromSchedule(SummitEvent $event)
{
if(!$this->isOnSchedule($event)) throw new ValidationException(sprintf('Event %s does not belongs to attendee %s schedule.', $event->ID, $this->ID));
$this->belongsToMany
(
'models\summit\SummitEvent',
'SummitAttendee_Schedule',
'SummitAttendeeID',
'SummitEventID'
)->detach($event->ID);
return true;
}
public function isOnSchedule(SummitEvent $event)
{
return $this->belongsToMany
(
'models\summit\SummitEvent',
'SummitAttendee_Schedule',
'SummitAttendeeID',
'SummitEventID'
)->where('SummitEventID', '=', $event->ID)->count() > 0;
}
public function checkIn(SummitEvent $event)
{
if(!$this->isOnSchedule($event)) throw new ValidationException(sprintf('Event %s does not belongs to attendee %s schedule.', $event->ID, $this->ID));
$this->belongsToMany
(
'models\summit\SummitEvent',
'SummitAttendee_Schedule',
'SummitAttendeeID',
'SummitEventID'
)->withPivot('IsCheckedIn')->updateExistingPivot($event->ID, ['IsCheckedIn' => true]);
return true;
}
/**
* @return Member
*/
public function member()
{
return $this->hasOne('models\main\Member', 'ID', 'MemberID')->first();
}
/**
* @return SummitAttendeeTicket[]
*/
public function tickets()
{
return $this->hasMany('models\summit\SummitAttendeeTicket', 'OwnerID', 'ID')->get();
}
public function toArray()
{
$values = parent::toArray();
$member = $this->member();
$values['schedule'] = $this->getScheduleIds();
$tickets = array();
foreach($this->tickets() as $t)
{
array_push($tickets, intval($t->ticket_type()->ID));
}
$values['tickets'] = $tickets;
if(!is_null($member))
{
$values['first_name'] = JsonUtils::toJsonString($member->FirstName);
$values['last_name'] = JsonUtils::toJsonString($member->Surname);
$values['gender'] = $member->Gender;
$values['bio'] = JsonUtils::toJsonString($member->Bio);
$values['pic'] = Config::get("server.assets_base_url", 'https://www.openstack.org/'). 'profile_images/members/'. $member->ID;
$values['linked_in'] = $member->LinkedInProfile;
$values['irc'] = $member->IRCHandle;
$values['twitter'] = $member->TwitterName;
}
return $values;
}
/**
* @return Summit
*/
public function getSummit()
{
return $this->hasOne('models\summit\Summit', 'ID', 'SummitID')->first();
}
}

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