Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable api #1321

Open
wants to merge 24 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/Enums/CredentialType.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Enums;

use App\Traits\HasEnumLongDescription;
use BenSampo\Enum\Contracts\LocalizedEnum;
use BenSampo\Enum\Enum;

Expand All @@ -10,6 +11,8 @@
*/
final class CredentialType extends Enum implements LocalizedEnum
{
use HasEnumLongDescription;

/**
* Admin credential.
*/
Expand Down
4 changes: 2 additions & 2 deletions app/Events/User/UserInvited.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ public function __construct(User $user, ?User $invitedBy = null, ?PublicAdminist
/**
* Get the user issuing the invitation.
*
* @return User the user issuing the invitation
* @return User|string the user issuing the invitation
*/
public function getInvitedBy(): User
public function getInvitedBy()
{
return $this->invitedBy ?? '[API request]';
}
Expand Down
200 changes: 56 additions & 144 deletions app/Http/Controllers/CredentialsController.php

Large diffs are not rendered by default.

12 changes: 7 additions & 5 deletions app/Http/Controllers/SwaggerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

namespace App\Http\Controllers;

use App\Enums\CredentialType;
use App\Enums\UserPermission;
use App\Models\Credential;
use App\Models\PublicAdministration;
use App\Traits\HasRoleAwareUrls;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\Yaml\Yaml;

class SwaggerController extends Controller
{
Expand Down Expand Up @@ -39,7 +41,7 @@ public function index(Request $request, PublicAdministration $publicAdministrati

$credentials = Credential::where('public_administration_id', $currentPublicAdministration->id)->get()
->filter(function ($credential) {
return 'admin' === $credential->type;
return $credential->type->is(CredentialType::ADMIN);
});
$hasCredentials = 0 !== count($credentials);

Expand All @@ -59,21 +61,21 @@ public function index(Request $request, PublicAdministration $publicAdministrati
*/
public function apiSpecification(): JsonResponse
{
$path = resource_path('data/api.json');
$path = resource_path('data/api.yml');

if (!is_file($path) || !is_readable($path)) {
return response()
->json(['error' => 'API configuration file not readable'], 500);
}

$data = json_decode(file_get_contents($path));
$data = Yaml::parseFile($path, Yaml::PARSE_OBJECT_FOR_MAP);
$apiUrl = config('kong-service.api_url');
$apiVersion = config('app.api_version');
$basePath = config('kong-service.portal_base_path');

$data->servers = [
[
'url' => implode('/', array_filter([
'url' => implode('', array_filter([
$apiUrl,
$basePath,
$apiVersion,
Expand All @@ -87,7 +89,7 @@ public function apiSpecification(): JsonResponse
->oAuth
->flows
->clientCredentials
->tokenUrl = $apiUrl . '/portal/oauth2/token';
->tokenUrl = $apiUrl . '/oauth2/token';

return response()
->json($data, 200);
Expand Down
45 changes: 6 additions & 39 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use App\Models\PublicAdministration;
use App\Models\User;
use App\Traits\HasRoleAwareUrls;
use App\Traits\HasWebsiteDatatable;
use App\Traits\SendsResponse;
use App\Transformers\UserArrayTransformer;
use App\Transformers\UserTransformer;
Expand All @@ -40,6 +41,7 @@ class UserController extends Controller
{
use SendsResponse;
use HasRoleAwareUrls;
use HasWebsiteDatatable;

/**
* Display the users list.
Expand Down Expand Up @@ -530,42 +532,6 @@ protected function getAllRoles(User $user, PublicAdministration $publicAdministr
});
}

/**
* Get the datatable parameters for websites permission with specified source.
*
* @param string $source the source paramater for the websites permission datatable
* @param bool $readonly wether the datatable is readonly
*
* @return array the datatable parameters
*/
protected function getDatatableWebsitesPermissionsParams(string $source, bool $readonly = false): array
{
return [
'datatableOptions' => [
'searching' => [
'label' => __('cerca tra i siti web'),
],
'columnFilters' => [
'type' => [
'filterLabel' => __('tipologia'),
],
'status' => [
'filterLabel' => __('stato'),
],
],
],
'columns' => [
['data' => 'website_name', 'name' => __('nome del sito'), 'className' => 'text-wrap'],
['data' => 'type', 'name' => __('tipologia')],
['data' => 'status', 'name' => __('stato')],
['data' => ($readonly ? 'icons' : 'toggles'), 'name' => __('permessi sui dati analytics'), 'orderable' => false, 'searchable' => false],
],
'source' => $source . ($readonly ? '?readOnly' : ''),
'caption' => __('elenco dei siti web presenti su :app', ['app' => config('app.name')]),
'columnsOrder' => [['website_name', 'asc']],
];
}

/**
* Create a new user.
*
Expand Down Expand Up @@ -755,8 +721,9 @@ protected function manageUserPermissions(array $validatedData, PublicAdministrat
*/
protected function getUserApiUri(string $fn): string
{
return 'to-be-implemented';
// return config('kong-service.api_url') .
// str_replace('/api/', '/portal/', route('api.users.show', ['fn' => $fn], false));
$apiUrl = config('kong-service.api_url');
$apiBasePath = config('kong-service.portal_base_path');

return $apiUrl . str_replace('/api/', $apiBasePath, route('api.users.show', ['fn' => $fn], false));
}
}
10 changes: 5 additions & 5 deletions app/Http/Controllers/WebsiteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,7 @@ public function storeApi(StoreWebsiteRequest $request): JsonResponse
*/
public function show(Request $request, PublicAdministration $publicAdministration, Website $website)
{
$isApiRequest = $request->is('api/*');
if ($isApiRequest) {
if ($request->is('api/*')) {
return $this->websiteResponse($website);
}

Expand Down Expand Up @@ -915,8 +914,9 @@ private function updateWebsiteListCache(Website $website)
*/
private function getWebsiteAPIUri(Website $website): string
{
return 'to-be-implemented';
// return config('kong-service.api_url') .
// str_replace('/api/', '/portal/', route('api.websites.read', ['website' => $website], false));
$apiUrl = config('kong-service.api_url');
$apiBasePath = config('kong-service.portal_base_path');

return $apiUrl . str_replace('/api/', $apiBasePath, route('api.websites.read', ['website' => $website], false));
}
}
3 changes: 2 additions & 1 deletion app/Http/Middleware/AuthenticateApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Http\Middleware;

use App\Enums\CredentialType;
use App\Models\Credential;
use App\Models\User;
use App\Models\Website;
Expand Down Expand Up @@ -36,7 +37,7 @@ public function handle($request, Closure $next)
$credentialType = $customId->type;
}

if ('admin' !== $credentialType) {
if (CredentialType::ADMIN !== $credentialType) {
return response()->json([
'error' => 'forbidden',
'error_description' => 'Access to the requested resource is forbidden',
Expand Down
5 changes: 4 additions & 1 deletion app/Http/Requests/StoreCredentialsRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ public function rules(): array
{
return [
'credential_name' => 'required|unique:credentials,client_name|min:3|max:255',
'type' => 'required',
'type' => [
'required',
Rule::in([CredentialType::ADMIN, CredentialType::ANALYTICS]),
],
'permissions' => 'required_if:type,' . CredentialType::ANALYTICS . '|array',
'permissions.*' => 'array',
'permissions.*.*' => Rule::in([CredentialPermission::WRITE, CredentialPermission::READ]),
Expand Down
1 change: 1 addition & 0 deletions app/Http/Requests/UpdateCredentialRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function rules(): array
$rules = parent::rules();
$credential = $this->route('credential');

unset($rules['type']);
$rules['credential_name'] = [
'required',
'min:3',
Expand Down
2 changes: 1 addition & 1 deletion app/Listeners/UserEventsSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function onInvited(UserInvited $event): void
$publicAdministration->sendUserInvitedNotificationToAdministrators($user);
}
logger()->notice(
'New user invited: ' . $user->uuid . ' by ' . $invitedBy->uuid,
'New user invited: ' . $user->uuid . ' by ' . (($invitedBy->uuid ?? false) ? $invitedBy->uuid : $invitedBy),
$context
);
}
Expand Down
10 changes: 10 additions & 0 deletions app/Models/Credential.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Models;

use App\Enums\CredentialType;
use BenSampo\Enum\Traits\CastsEnums;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
Expand All @@ -16,6 +17,15 @@ class Credential extends Model
'consumer_id',
];

/**
* The attributes that should be cast to enums classes.
*
* @var array enum casted attributes
*/
protected $enumCasts = [
'type' => CredentialType::class,
];

/**
* Get the route key for the model.
*
Expand Down
47 changes: 47 additions & 0 deletions app/Traits/HasWebsiteDatatable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace App\Traits;

trait HasWebsiteDatatable
{
/**
* Get the datatable parameters for websites permission with specified source.
*
* @param string $source the source paramater for the websites permission datatable
* @param bool $readonly wether the datatable is readonly
*
* @return array the datatable parameters
*/
protected function getDatatableWebsitesPermissionsParams(string $source, bool $readonly = false): array
{
return [
'datatableOptions' => [
'searching' => [
'label' => __('cerca tra i siti web'),
],
'columnFilters' => [
'type' => [
'filterLabel' => __('tipologia'),
],
'status' => [
'filterLabel' => __('stato'),
],
],
],
'columns' => [
['data' => 'website_name', 'name' => __('nome del sito'), 'className' => 'text-wrap'],
['data' => 'type', 'name' => __('tipologia')],
['data' => 'status', 'name' => __('stato')],
[
'data' => ($readonly ? 'icons' : 'toggles'),
'name' => __('permessi sul sito web'),
'orderable' => false,
'searchable' => false,
],
],
'source' => $source . ($readonly ? '?readOnly' : ''),
'caption' => __('elenco dei siti web presenti su :app', ['app' => config('app.name')]),
'columnsOrder' => [['website_name', 'asc']],
];
}
}
25 changes: 1 addition & 24 deletions app/Traits/SendsResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ protected function websiteResponse(Website $website, ?array $notification = [],
$jsonResponse['status'] = $website->status->key;
$jsonResponse['status_description'] = $website->status->description;
$jsonResponse['trashed'] = $website->trashed();
unset($jsonResponse['analyticsId']);
}
}

Expand Down Expand Up @@ -178,30 +179,6 @@ protected function notModifiedResponse(?array $headers = [])
]);
}

/**
* Returns a success response for the specified credential.
*
* @param Credential $credential the credential
*
* @return JsonResponse|RedirectResponse the response in json or http redirect format
*/
protected function credentialResponse(Credential $credential)
{
return request()->expectsJson()
? response()->json([
'result' => 'ok',
'id' => $credential->consumer_id,
'credential_name' => e($credential->client_name),
'status' => 200,
])
: back()->withNotification([
'title' => __('credenziale modificata'),
'message' => __('Il sito web :website è stato eliminato.', ['website' => '<strong>' . e($credential->client_name) . '</strong>']),
'status' => 'info',
'icon' => 'it-info-circle',
]);
}

/**
* Returns an error response with the specified parameters.
*
Expand Down
3 changes: 1 addition & 2 deletions app/Transformers/CredentialsTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Transformers;

use App\Enums\CredentialType;
use App\Enums\UserPermission;
use App\Models\Credential;
use League\Fractal\TransformerAbstract;
Expand Down Expand Up @@ -32,7 +31,7 @@ public function transform(Credential $credential): array
]),
'raw' => e($credential->client_name),
],
'type' => CredentialType::getDescription($credential->type),
'type' => $credential->type->description,
'added_at' => $credential->created_at->format('d/m/Y'),
'icons' => [],
'buttons' => [],
Expand Down
1 change: 1 addition & 0 deletions app/Transformers/WebsiteArrayTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public function transform(Website $website): array
return [
'name' => $website->name,
'url' => $website->url,
'analyticsId' => $website->analytics_id,
'slug' => $website->slug,
'status' => WebsiteStatus::fromValue($website->status)->description,
'type' => WebsiteType::fromValue($website->type)->description,
Expand Down
2 changes: 1 addition & 1 deletion app/Transformers/WebsitesPermissionsTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,6 @@ protected function hasCredentialPermission(int $websiteId, string $permissionTyp

$websitePermissions = $credentialPermissions[$websitePermissionIndex];

return array_key_exists('permission', $websitePermissions) && str_contains($websitePermissions['permission'], $permissionType);
return array_key_exists('permissions', $websitePermissions) && str_contains($websitePermissions['permissions'], $permissionType);
}
}
2 changes: 2 additions & 0 deletions containers/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ services:
context: ./kong
args:
- KONG_VERSION=${KONG_VERSION}
- KONG_API_PORTAL_BASE_PATH=${KONG_API_PORTAL_BASE_PATH}
- KONG_API_MATOMO_BASE_PATH=${KONG_API_MATOMO_BASE_PATH}
depends_on:
- postgres
environment:
Expand Down
4 changes: 2 additions & 2 deletions containers/kong/kong-setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ if ! curl -s http://localhost:8001/services | grep -q "nginx"; then
curl --output /dev/null --silent -X POST http://localhost:8001/plugins/ --data "name=cors&config.origins=https://localhost"
curl --output /dev/null --silent -X POST http://localhost:8001/plugins/ --data "name=oauth2&config.enable_client_credentials=true&config.global_credentials=true&config.accept_http_if_already_terminated=true"
curl --output /dev/null --silent -X POST http://localhost:8001/services --data "name=portal&url=https://nginx/api"
curl --output /dev/null --silent -X POST http://localhost:8001/services/portal/routes --data "paths[]=/@KONG_API_PORTAL_BASE_PATH@&name=portal"
curl --output /dev/null --silent -X POST http://localhost:8001/services/portal/routes --data "paths[]=@KONG_API_PORTAL_BASE_PATH@&name=portal"
curl --output /dev/null --silent -X POST http://localhost:8001/services --data "name=matomo&url=http://express:7080"
curl --output /dev/null --silent -X POST http://localhost:8001/services/matomo/routes --data "paths[]=/@KONG_API_MATOMO_BASE_PATH@&name=matomo"
curl --output /dev/null --silent -X POST http://localhost:8001/services/matomo/routes --data "paths[]=@KONG_API_MATOMO_BASE_PATH@&name=matomo"
fi

echo "Kong plugins and routes are ready"
Loading