openstackid-resources/app/Http/Middleware/OAuth2BearerAccessTokenRequestValidator.php
smarcet 39e3c8e333 * Summit Registration Model/Endpoints
Doc

https://docs.google.com/document/d/1gOAceevwutF3QHYWD0_6aESQMZEiIz3YVBVXlyUuRy8

* Summit Registration External Feed

https://docs.google.com/document/d/1_2QZUK--A350jxh2USKBtVtisKrrcUcVjdKnbcZ7-4M/edit#

* Multi Stripe Config

* Added stripe payment configuration per summit
* Added webhook automatic creation
* Added CRUD endpoints for payment profiles per summit

GET api/v1/summits/{id}/payment-gateway-profiles

filters

active ['==']
application_type ['=@', '==']

scopes

summits/read/all
summits/payment-gateway-profiles/read

POST  api/v1/summits/{id}/payment-gateway-profiles

payload

'active'               => 'sometimes|boolean',
'application_type'     => 'sometimes|string|in:Registration,BookableRooms'
'provider'             => 'required|string|in:Stripe',
'test_mode_enabled'    => 'required|boolean',
'live_secret_key'      => 'sometimes|string',
'live_publishable_key' => 'required_with:live_secret_key|string',
'test_secret_key'      => 'sometimes|string',
'test_publishable_key' => 'required_with:test_secret_key|string'

scopes

summits/write
summits/payment-gateway-profiles/write

GET  api/v1/summits/{id}/payment-gateway-profiles/{payment_profile_id}

scopes

summits/read/all
summits/payment-gateway-profiles/read

PUT api/v1/summits/{id}/payment-gateway-profiles/{payment_profile_id}

payload

'active'               => 'sometimes|boolean',
'application_type'     => 'sometimes|string|in:Registration,BookableRooms'
'provider'             => 'required|string|in:Stripe',
'test_mode_enabled'    => 'required|boolean',
'live_secret_key'      => 'sometimes|string',
'live_publishable_key' => 'required_with:live_secret_key|string',
'test_secret_key'      => 'sometimes|string',
'test_publishable_key' => 'required_with:test_secret_key|string'

scopes

summits/payment-gateway-profiles/write
summits/write

DELETE api/v1/summits/{id}/payment-gateway-profiles/{payment_profile_id}

scopes

summits/payment-gateway-profiles/write
summits/write

Stripe Webhooks

default webhook

(SECRET set per application under .env, should be created previously on stripe default account)

POST api/public/v1/summits/all/payments/{application_name}/confirm

where application_name could be Registration or BookableRooms

otherwise if a stripe account is set per summit, when the profile gets activated
a webhook will be automatically be created using following url

POST api/public/v1/summits/{id}/payments/{application_name}/confirm

* Email API Integration

* moved all blade templates to mail api ( DB Seeding)
* defined email events flows per summmit
* created endpoint to set up templates per email events on each flow

PUT /api/v1/summits/{id}/email-flows-events/{event_id}

payload

email_template_identifier: string

* added endpoint to get all email events per summit

GET /api/v1/summits/{id}/email-flows-events

* added endpoint to get email event per summit/id

GET /api/v1/summits/{id}/email-flows-events/{event_id}

Summit Documents endpoints

add summit document

POST /api/v1/summits/{id}/summit-documents

payload

file (mandatory|file stream)
label ( mandatory|string)
name ( mandatory|string)
description (optional|string)

get all summit documents

GET /api/v1/summits/{id}/summit-documents

get by id

GET /api/v1/summits/{id}/summit-documents/{document_id}

update

PUT GET /api/v1/summits/{id}/summit-documents/{document_id}

file (optional|file stream)
label (optional|string)
name (optional|string)
description (optional|string)

delete

DELETE GET /api/v1/summits/{id}/summit-documents/{document_id}

add event type to doc

PUT /api/v1/summits/{id}/summit-documents/{document_id}/event-types/{event_type_id}

delete event type from doc

DELETE /api/v1/summits/{id}/summit-documents/{document_id}/event-types/{event_type_id}

add document to event type

PUT /api/v1/summits/{id}/event-types/{event_type_id}/summit-documents/{document_id}

delete document from event type

DELETE /api/v1/summits/{id}/event-types/{event_type_id}/summit-documents/{document_id}

Updated Summit events to support streaming url, meeting_url and etherpad link

* Summit Registration - Invite only

Summit Administrator Permission Groups

GET /api/v1/summit-administrator-groups

filter

* title
* member_first_name
* member_last_name
* member_full_name
* member_email
* summit_id
* member_id

ordering

id
title

scopes

%s/summit-administrator-groups/read

/api/v1/summit-administrator-groups/{group_id}

scopes

%s/summit-administrator-groups/read

POST /api/v1/summit-administrator-groups

title
summits
members

scopes

%s/summit-administrator-groups/write

PUT /api/v1/summit-administrator-groups/{group_id}

title
summits
members

scopes

%s/summit-administrator-groups/write

DELETE /api/v1/summit-administrator-groups/{group_id}

scopes

%s/summit-administrator-groups/write

PUT /api/v1/summit-administrator-groups/{group_id}/members/{member_id}

DELETE /api/v1/summit-administrator-groups/{group_id}/members/{member_id}

PUT /api/v1/summit-administrator-groups/{group_id}/summits/{summit_id}

DELETE /api/v1/summit-administrator-groups/{group_id}/summits/{summit_id}

Room Metrics

PUT /api/v1/summits/{id}/members/{member_id}/schedule/{event_id}/enter

Scopes

%s/me/summits/events/enter

PUT /api/v1/summits/{id}/members/{member_id}/schedule/{event_id}/leave

%s/me/summits/events/leave

update summit_event serializer

new fields

total_attendance_count
current_attendance_count
attendance
current_attendance

Added new Speakers Endpoints

GET /api/v1/summits/{id}/speakers/on-schedule

retrieves all speakers on summit schedule

filters

'first_name' => ['=@', '=='],
'last_name'  => ['=@', '=='],
'email'      => ['=@', '=='],
'id'         => ['=='],
'full_name'  => ['=@', '=='],
'start_date' => ['>', '<', '<=', '>=', '=='],
'end_date'   => ['>', '<', '<=', '>=', '=='],

Summit Events Image

POST /api/v1/summits/{id}/events/{event_id}/image
DELETE /api/v1/summits/{id}/events/{event_id}/image

Speakers Image Big Pic

POST /api/v1/speakers/{speaker_id}/big-photo
DELETE /api/v1/speakers/{speaker_id}/big-photo

CFP - multiple summits

Presentation Materials - Media Uploads

New Endpoints

GET api/v1/summit-media-file-types

filter
'name' => ['=@', '==']

order

id, name

POST api/v1/summit-media-file-types

payload

'name'  => 'required|string|max:255',
'description'  => 'sometimes|string|max:255',
'allowed_extensions' => 'required|string_array',

GET api/v1/summit-media-file-types/{id}

PUT api/v1/summit-media-file-types/{id}

payload

'name'  => 'sometimes|string|max:255',
'description'  => 'sometimes|string|max:255',
'allowed_extensions' => 'required|string_array',

DELETE api/v1/summit-media-file-types/{id}

GET api/v1/summits/{id}/media-upload-types

POST

payload

'name' => 'required|string|max:255',
'description' => 'sometimes|string|max:255',
'is_mandatory' => 'required|boolean',
'max_size' => 'required|int|megabyte_aligned',
'private_storage_type' => 'required|string|in:None,DropBox,Swift,Local',
'public_storage_type' => 'required|string|in:None,DropBox,Swift,Local'
'type_id' => 'required|int',
'presentation_types' => 'sometimes|int_array',

GET api/v1/summits/{id}/media-upload-types/{media_upload_type_id}

PUT api/v1/summits/{id}/media-upload-types/{media_upload_type_id}

payload

'name' => 'sometimes|string|max:255',
'description' => 'sometimes|string|max:255',
'is_mandatory' => 'sometimes|boolean',
'max_size' => 'sometimes|int|megabyte_aligned',
'private_storage_type' => 'sometimes|string|in:None,DropBox,Swift,Local',
'public_storage_type' => 'sometimes|string|in:None,DropBox,Swift,Local'
'type_id' => 'sometimes|int',
'presentation_types' => 'sometimes|int_array',

DELETE api/v1/summits/{id}/media-upload-types/{media_upload_type_id}

PUT api/v1/summits/{id}/media-upload-types/{media_upload_type_id}/presentation-types/{event_type_id}

DELETE api/v1/summits/{id}/media-upload-types/{media_upload_type_id}/presentation-types/{event_type_id}

GET api/v1/summits/{id}/presentations/{presentation_id}/media-uploads

POST api/v1/summits/{id}/presentations/{presentation_id}/media-uploads

payload multiform

file

media_upload_type_id

GET api/v1/summits/{id}/presentations/{presentation_id}/media-uploads/{media_upload_id}

PUT api/v1/summits/{id}/presentations/{presentation_id}/media-uploads/{media_upload_id}

payload multiform

file

DELETE api/v1/summits/{id}/presentations/{presentation_id}/media-uploads/{media_upload_id}

POST /api/v1/summits/{id}/media-upload-types/all/clone/{to_summit_id}

Summit Invitation Only endpoints V2

CRUD invitations

Change-Id: Ia23c247a59c3810f2a738265efdd890fe6f59dfb
Signed-off-by: smarcet <smarcet@gmail.com>
2020-09-21 09:52:07 -03:00

292 lines
11 KiB
PHP

<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use libs\oauth2\BearerAccessTokenAuthorizationHeaderParser;
use libs\oauth2\InvalidGrantTypeException;
use libs\oauth2\OAuth2Protocol;
use libs\oauth2\OAuth2ResourceServerException;
use libs\oauth2\OAuth2WWWAuthenticateErrorResponse;
use libs\utils\RequestUtils;
use models\oauth2\IResourceServerContext;
use App\Models\ResourceServer\IAccessTokenService;
use App\Models\ResourceServer\IApiEndpointRepository;
use URL\Normalizer;
/**
* Class OAuth2BearerAccessTokenRequestValidator
* http://tools.ietf.org/html/rfc6749#section-7
* @package App\Http\Middleware
*/
class OAuth2BearerAccessTokenRequestValidator
{
/**
* @var IResourceServerContext
*/
private $context;
/**
* @var array
*/
private $headers;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @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 \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 exists! (%s:%s)', $url, $method)
);
}
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();
}
//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, '');
}
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'
);
}
$endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($route, $method);
//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)
);
}
$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'
&& (is_null($origin) || empty($origin)|| 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 = $endpoint->getScopesNames();
Log::debug(sprintf("endpoint scopes %s", implode(' ',$endpoint_scopes)));
Log::debug(sprintf("token scopes %s", $token_info->getScope()));
$token_scopes = explode(' ', $token_info->getScope());
//check token available scopes vs. endpoint scopes
if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0) {
Log::warning(
sprintf(
'access token scopes (%s) does not allow to access to api url %s , needed scopes %s',
$token_info->getScope(),
$url,
implode(' OR ', $endpoint_scopes)
)
);
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 = [
'access_token' => $access_token_value,
'expires_in' => $token_info->getLifetime(),
'client_id' => $token_info->getClientId(),
'scope' => $token_info->getScope(),
'application_type' => $token_info->getApplicationType(),
'allowed_origins' => $token_info->getAllowedOrigins(),
'allowed_return_uris' => $token_info->getAllowedReturnUris()
];
if (!is_null($token_info->getUserId()))
{
Log::debug(sprintf("OAuth2BearerAccessTokenRequestValidator::handle user id is not null (%s)", $token_info->getUserId()));
$context['user_id'] = $token_info->getUserId();
$context['user_external_id'] = $token_info->getUserExternalId();
$context['user_identifier'] = $token_info->getUserIdentifier();
$context['user_email'] = $token_info->getUserEmail();
$context['user_first_name'] = $token_info->getUserFirstName();
$context['user_last_name'] = $token_info->getUserLastName();
$context['user_groups'] = $token_info->getUserGroups();
}
$this->context->setAuthorizationContext($context);
}
catch (OAuth2ResourceServerException $ex1)
{
Log::warning($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::warning($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 = [];
if (function_exists('getallheaders')) {
foreach (getallheaders() as $name => $value) {
$headers[strtolower($name)] = $value;
}
}
if(count($headers) == 0 )
{
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;
}
}