Skip to content

Commit

Permalink
pass to cakephp4 (#708)
Browse files Browse the repository at this point in the history
* feat: composer dependencies

* fix: bootstrap

* fix: routes

* fix: Application

* fix: ProjectMiddleware

* fix: beforeFilter and beforeRender signature

* fix: enable login page view

* fix: use EventInterface

* test: use PHP 7.4, 8.0 and 8.1

* chore: aiax twig

* feat: refactor helper method + test

* fix: move flash templates

* fix: use `do`

* fix: flash paths

* fix: handle view vars

* fix: Url.build signature

* chore: problematic `unlockField` commented (temp)

* chore fix: make scrutinizer happy

* chore fix: make scrutinizer happy

* fix: Form.unlockField

* fix: remove form from filter_box

* fix: url.build and array default

* chore: rename $builder to $routes

* fix: `Cache` methods signatures

* fix: '_serialize' var

* chore: array safe check

* fix: phpcs

* fix: phpcs

* refactor: update tests (#716)

* refactor: update tests

* fix: update tests

* chore: git ignore

* refactor: phpunit xml format

* fix: middleware test

* fix: remove unused import

* chore: use web-tools 3.9 - PHP 8

* chore: remove PCOV clobber

* fix: loadRoutes in tests

* fix: setUp

* fix: setUp

* feat: loadRoutes in setUp in tests

* fix: setUp

* fix: setUp

* fix: Auth tests

* refactor: Plugin & LinkHelper classes

* test: fix varioustests

* chore: code style fixes

* chore: cover method

Co-authored-by: dante di domenico <dante@didoda.com>

* chore: PHP version [ci skip]

* chore: 3.0.0 version [ci skip]

Co-authored-by: stefanorosanelli <stefano.rosanelli@gmail.com>
  • Loading branch information
didoda and stefanorosanelli authored Mar 17, 2022
1 parent 8f9a13f commit ecaee85
Show file tree
Hide file tree
Showing 81 changed files with 478 additions and 252 deletions.
9 changes: 3 additions & 6 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:

strategy:
matrix:
php-version: [7.2]
php-version: [7.4]

steps:
- name: 'Checkout current revision'
Expand Down Expand Up @@ -62,7 +62,7 @@ jobs:

strategy:
matrix:
php-version: [7.2, 7.3, 7.4]
php-version: [7.4, 8.0, 8.1]

steps:
- name: 'Checkout current revision'
Expand Down Expand Up @@ -109,7 +109,7 @@ jobs:

strategy:
matrix:
php-version: [7.2, 7.3, 7.4]
php-version: [7.4, 8.0, 8.1]

steps:
- name: 'Checkout current revision'
Expand Down Expand Up @@ -161,9 +161,6 @@ jobs:
- name: 'Install dependencies with Composer'
run: 'composer install --prefer-dist --no-interaction'

- name: 'Setup PCOV clobber'
run: 'composer require pcov/clobber && vendor/bin/pcov clobber'

- name: 'Run PHPUnit with coverage'
run: 'vendor/bin/phpunit --coverage-clover=clover.xml'

Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
!/tmp/.gitkeep
/vendor/*
!/vendor/.gitkeep
/.phpunit.result.cache

# plugins folders #
##########################
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Official Backend Admin WebApp for [BEdita4 API](https://gihub.com/bedita/bedita)

## Prerequisites

* [PHP](https://www.php.net/) >= 7.1
* [PHP](https://www.php.net/) 7.4, 8.0 and 8.1
* [Composer](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx)
* [Node](https://nodejs.org) 14 or 16
* [Yarn](https://yarnpkg.com) >= 1.15
Expand Down
30 changes: 15 additions & 15 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,24 @@
}
],
"require": {
"php": ">=7.2",
"bedita/i18n": "^1.7",
"bedita/web-tools": "^1.9",
"cakephp/authentication": "^1.0",
"cakephp/cakephp": "^3.10",
"cakephp/plugin-installer": "^1.1",
"josegonzalez/dotenv": "2.*",
"mobiledetect/mobiledetectlib": "2.*",
"phpoffice/phpspreadsheet": "^1.15",
"php": ">=7.4",
"bedita/i18n": "^3.3",
"bedita/web-tools": "^3.9",
"cakephp/authentication": "^2.9",
"cakephp/cakephp": "~4.3.0",
"cakephp/plugin-installer": "^1.3",
"josegonzalez/dotenv": "^3.2",
"mobiledetect/mobiledetectlib": "^2.8",
"phpoffice/phpspreadsheet": "^1.22",
"wikimedia/composer-merge-plugin": "^2.0.1"
},
"require-dev": {
"cakephp/bake": "^1.12",
"cakephp/cakephp-codesniffer": "~3.3.0",
"cakephp/debug_kit": "^3.19.0",
"dereuromark/cakephp-ide-helper": "~0.14.10",
"phpstan/phpstan": "^1.3",
"phpunit/phpunit": "^6.5",
"cakephp/bake": "^2.6",
"cakephp/cakephp-codesniffer": "~4.5.1",
"cakephp/debug_kit": "^4.7.1",
"dereuromark/cakephp-ide-helper": "~1.17.0",
"phpstan/phpstan": "^1.4",
"phpunit/phpunit": "^9",
"psy/psysh": "@stable"
},
"autoload": {
Expand Down
14 changes: 5 additions & 9 deletions config/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@
require CORE_PATH . 'config' . DS . 'bootstrap.php';

use Cake\Cache\Cache;
use Cake\Console\ConsoleErrorHandler;
use Cake\Core\Configure;
use Cake\Core\Configure\Engine\IniConfig;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\Database\Type;
use Cake\Datasource\ConnectionManager;
use Cake\Error\ConsoleErrorHandler;
use Cake\Error\ErrorHandler;
use Cake\Http\ServerRequest;
use Cake\Log\Log;
Expand Down Expand Up @@ -199,14 +199,10 @@
* locale specific date formats. For details see
* @link https://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data
*/
Type::build('time')
->useImmutable();
Type::build('date')
->useImmutable();
Type::build('datetime')
->useImmutable();
Type::build('timestamp')
->useImmutable();
Type::build('time');
Type::build('date');
Type::build('datetime');
Type::build('timestamp');

/*
* Custom Inflector rules, can be set to correctly pluralize or singularize
Expand Down
13 changes: 7 additions & 6 deletions config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
*/

use Cake\Core\Configure;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
use Cake\Utility\Inflector;

/**
Expand All @@ -41,7 +40,9 @@
* inconsistently cased URLs when used with `:plugin`, `:controller` and
* `:action` markers.
*/
Router::defaultRouteClass(DashedRoute::class);

/** @var \Cake\Routing\RouteBuilder $routes */
$routes->setRouteClass(DashedRoute::class);

if (Configure::read('Maintenance')) {
$routes->connect(
Expand All @@ -53,7 +54,7 @@
return;
}

Router::scope('/', function (RouteBuilder $routes) {
$routes->scope('/', function (RouteBuilder $routes) {

// Reset & change password
$routes->connect(
Expand Down Expand Up @@ -92,7 +93,7 @@
);

// Admin.
Router::prefix('admin', ['_namePrefix' => 'admin:'], function (RouteBuilder $routes) {
$routes->prefix('admin', ['_namePrefix' => 'admin:'], function (RouteBuilder $routes) {

foreach (['applications', 'async_jobs', 'config', 'endpoints', 'roles'] as $controller) {
// Routes connected here are prefixed with '/admin'
Expand Down Expand Up @@ -141,7 +142,7 @@
);

// Model.
Router::prefix('model', ['_namePrefix' => 'model:'], function (RouteBuilder $routes) {
$routes->prefix('model', ['_namePrefix' => 'model:'], function (RouteBuilder $routes) {

foreach (['object_types', 'property_types', 'relations', 'categories', 'tags'] as $controller) {
// Routes connected here are prefixed with '/model'
Expand Down
2 changes: 1 addition & 1 deletion config/version.ini
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[Manager]
version = 2.2.1
version = 3.0.0
1 change: 1 addition & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
<config name="installed_paths" value="../../cakephp/cakephp-codesniffer"/>

<rule ref="CakePHP">
<exclude name="SlevomatCodingStandard.TypeHints.DeclareStrictTypes" />
</rule>
</ruleset>
71 changes: 30 additions & 41 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,43 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
colors="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="./tests/bootstrap.php"
>
<php>
<ini name="memory_limit" value="-1"/>
<ini name="apc.enable_cli" value="1"/>
</php>

<!-- Add any additional test suites you want to run here -->
<testsuites>
<testsuite name="BEdita 4 Manager">
<directory>./tests/TestCase</directory>
</testsuite>
<!-- Add plugin test suites here. -->
</testsuites>

<!-- Setup a listener for fixtures -->
<listeners>
<listener
class="\Cake\TestSuite\Fixture\FixtureInjector"
file="./vendor/cakephp/cakephp/src/TestSuite/Fixture/FixtureInjector.php">
<arguments>
<object class="\Cake\TestSuite\Fixture\FixtureManager" />
</arguments>
</listener>
</listeners>

<!-- Ignore vendor tests in code coverage reports -->
<filter>
<whitelist>
<directory suffix=".php">./src/</directory>
<exclude>
<file>./src/Console/Installer.php</file>
<file>./src/Shell/ConsoleShell.php</file>
</exclude>
</whitelist>
</filter>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" processIsolation="false" stopOnFailure="false" bootstrap="./tests/bootstrap.php" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">./src/</directory>
</include>
<exclude>
<file>./src/Console/Installer.php</file>
<file>./src/Shell/ConsoleShell.php</file>
</exclude>
</coverage>
<php>
<ini name="memory_limit" value="-1"/>
<ini name="apc.enable_cli" value="1"/>
</php>
<!-- Add any additional test suites you want to run here -->
<testsuites>
<testsuite name="BEdita 4 Manager">
<directory>./tests/TestCase</directory>
</testsuite>
<!-- Add plugin test suites here. -->
</testsuites>
<!-- Setup a listener for fixtures -->
<listeners>
<listener class="\Cake\TestSuite\Fixture\FixtureInjector" file="./vendor/cakephp/cakephp/src/TestSuite/Fixture/FixtureInjector.php">
<arguments>
<object class="\Cake\TestSuite\Fixture\FixtureManager"/>
</arguments>
</listener>
</listeners>
<!-- Ignore vendor tests in code coverage reports -->
</phpunit>
12 changes: 6 additions & 6 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@
use App\Authentication\Identifier\ApiIdentifier;
use App\Middleware\ProjectMiddleware;
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Identifier\IdentifierInterface;
use Authentication\Middleware\AuthenticationMiddleware;
use BEdita\I18n\Middleware\I18nMiddleware;
use BEdita\WebTools\BaseApplication;
use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\Http\BaseApplication;
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
Expand Down Expand Up @@ -98,7 +98,7 @@ public function middleware($middlewareQueue): MiddlewareQueue
$middlewareQueue
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(null, Configure::read('Error')))
->add(new ErrorHandlerMiddleware(Configure::read('Error')))

// Load current project configuration if `multiproject` instance
// Manager plugins will also be loaded here via `loadPluginsFromConfig()`
Expand Down Expand Up @@ -137,7 +137,7 @@ protected function csrfMiddleware(): CsrfProtectionMiddleware
// Csrf Middleware
$csrf = new CsrfProtectionMiddleware(['httponly' => true]);
// Token check will be skipped when callback returns `true`.
$csrf->whitelistCallback(function ($request) {
$csrf->skipCheckCallback(function ($request) {
$actions = (array)Configure::read(sprintf('CsrfExceptions.%s', $request->getParam('controller')));
// Skip token check for API URLs.
if (in_array($request->getParam('action'), $actions)) {
Expand Down Expand Up @@ -170,7 +170,7 @@ public static function loadProjectConfig(?string $project, string $projectsPath)
/**
* @inheritDoc
*/
public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response): AuthenticationService
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService([
'unauthenticatedRedirect' => '/login',
Expand Down
67 changes: 67 additions & 0 deletions src/Auth/ApiAuthenticate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
/**
* BEdita, API-first content management framework
* Copyright 2018 ChannelWeb Srl, Chialab Srl
*
* This file is part of BEdita: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
*/

namespace App\Auth;

use BEdita\WebTools\ApiClientProvider;
use Cake\Auth\BaseAuthenticate;
use Cake\Http\Response;
use Cake\Http\ServerRequest;
use Cake\Utility\Hash;

/**
* An authentication adapter for authenticating using BEdita 4 API /auth endpoint.
*
* @see https://docs.bedita.net/en/latest/authorization.html#authentication
*/
class ApiAuthenticate extends BaseAuthenticate
{
/**
* Default config for this object.
*
* - `fields` The fields to use to perform classic authentication.
*
* @var array
*/
protected $_defaultConfig = [
'fields' => [
'username' => 'username',
'password' => 'password',
],
];

/**
* {@inheritDoc}
*
* Perform authentication via /auth
*/
public function authenticate(ServerRequest $request, Response $response)
{
/** @var \BEdita\SDK\BEditaClient $apiClient */
$apiClient = ApiClientProvider::getApiClient();

$usernameField = (string)$this->getConfig('fields.username', 'username');
$passwordField = (string)$this->getConfig('fields.password', 'password');

$result = $apiClient->authenticate((string)$request->getData($usernameField), (string)$request->getData($passwordField));
if (empty($result['meta'])) {
return false;
}

$tokens = $result['meta'];
$result = $apiClient->get('/auth/user', null, ['Authorization' => sprintf('Bearer %s', $tokens['jwt'])]);
$roles = Hash::extract($result, 'included.{n}.attributes.name');

return $result['data'] + compact('tokens') + compact('roles');
}
}
4 changes: 2 additions & 2 deletions src/Controller/Admin/AdministrationBaseController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

use App\Controller\AppController;
use BEdita\SDK\BEditaClientException;
use Cake\Event\Event;
use Cake\Event\EventInterface;
use Cake\Http\Exception\UnauthorizedException;
use Cake\Http\Response;
use Cake\Utility\Hash;
Expand Down Expand Up @@ -81,7 +81,7 @@ public function initialize(): void
*
* {@inheritDoc}
*/
public function beforeFilter(Event $event): ?Response
public function beforeFilter(EventInterface $event): ?Response
{
$res = parent::beforeFilter($event);
if ($res !== null) {
Expand Down
Loading

0 comments on commit ecaee85

Please sign in to comment.