beebmx / kirby-middleware
Middleware provides a powerful mechanism for inspecting and filtering requests entering in your Kirby site.
Package info
github.com/beebmx/kirby-middleware
Type:kirby-plugin
pkg:composer/beebmx/kirby-middleware
Fund package maintenance!
Requires
- php: ^8.4
- beebmx/pipeline: ^1.0
- getkirby/composer-installer: ^1.2.1
- laravel/serializable-closure: ^2.2
Requires (Dev)
- getkirby/cms: ^4.0 || ^5.0 || ^6.0
- laravel/pint: ^1.0
- pestphp/pest: ^5.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Middleware for Kirby
Middleware provides a powerful mechanism for inspecting and filtering requests entering your Kirby site.
Overview
- 1. Compatibility
- 2. Installation
- 3. Usage
- 4. Middleware
- 5. Options
- 6. Facades
- 7. Plugins
- 8. Roadmap
- 9. License
- 10. Credits
Compatibility
| Version | Kirby 4 | Kirby 5 | Kirby 6 | PHP |
|---|---|---|---|---|
| 2.x | ✅ | ✅ | ✅ | 8.4+ |
| 1.2 – 1.3 | ✅ | ✅ | ❌ | 8.2+ |
| 1.0 – 1.1 | ✅ | ❌ | ❌ | 8.2+ |
Version 2.0.0 adds Kirby 6 and PHP 8.6 support while retaining Kirby 4 and 5 support. The supported PHP versions also depend on Kirby: Kirby 4 supports PHP up to 8.4, Kirby 5 up to 8.5, and Kirby 6 up to 8.6. Projects on PHP 8.2 or 8.3 can continue using Middleware 1.x.
Installation
Download
Download and copy this repository to /site/plugins/kirby-middleware.
Composer
composer require beebmx/kirby-middleware
Upgrading to 2.0
Upgrade your site to PHP 8.4 or newer, then run:
composer require beebmx/kirby-middleware:^2.0
The beebmx.middleware configuration prefix introduced in 1.3.0 remains the same.
When upgrading a site to Kirby 6, follow the Kirby 6 site migration guide.
Custom middleware that throws Kirby exceptions should use named arguments on Kirby 5 and 6,
as shown below. Kirby 4 uses the legacy array syntax.
The global middleware now includes ValidatePostSize and
ConvertEmptyStringsToNull. Empty inputs are now null
instead of '', so review any code that compares inputs with ''. You can keep specific inputs
as empty strings with the empty exceptions, or remove the middleware entirely:
use Beebmx\KirbyMiddleware\Facades\Middleware; use Beebmx\KirbyMiddleware\Middlewares\ConvertEmptyStringsToNull; Middleware::remove(ConvertEmptyStringsToNull::class);
Usage
Out of the box, you don't need to do anything to start using (except for installation).
When you install the Middleware package, it comes with two ways of management middlewares, global middlewares and groups of middlewares.
Global middlewares
This middleware will always be triggered in every Page by the Middleware handler.
Out of the box it comes with these middlewares, run in this order:
ValidatePostSizerejects requests whose body is larger than PHP'spost_max_size.TrimStringsremoves surrounding spaces from theRequestinputs.ConvertEmptyStringsToNullturns empty inputs intonull.
Note
To access to this request, you should call the Beebmx\KirbyMiddleware\Request instance.
The Kirby\Http\Request instance will never be modified.
You can access to the Request instance transformed with:
use Beebmx\KirbyMiddleware\Request; $request = Request::instance();
You can add features to the global middleware in your config.php file:
'beebmx.middleware' => [ 'global' => [ MyOwnGlobalMiddleware::class, ], ],
Note
You can add as much middleware as requested.
They can be a class or a Closure.
TrimStrings
TrimStrings clean all the inputs in the request, but sometimes you need to ignore some inputs to be trimmed; you can skip it with:
'beebmx.middleware' => [ 'exceptions' => [ 'trim' => [ 'password', 'password_confirmation', ], ], ],
And you can recover those inputs with the Request instance in your controllers, models or any place required with:
use Beebmx\KirbyMiddleware\Request; Request::instance()->get('yourInput')
Or for your convinience you can use the facade:
use Beebmx\KirbyMiddleware\Facades\Request; Request::get('yourInput')
ConvertEmptyStringsToNull
ConvertEmptyStringsToNull runs after TrimStrings, so inputs that only contain spaces become null too.
To keep some inputs as empty strings, skip them with:
'beebmx.middleware' => [ 'exceptions' => [ 'empty' => [ 'nickname', ], ], ],
Or statically, for example in a plugin:
use Beebmx\KirbyMiddleware\Middlewares\ConvertEmptyStringsToNull; ConvertEmptyStringsToNull::except(['nickname']);
ValidatePostSize
When a request body is larger than PHP's post_max_size, PHP silently discards every input and file.
Without this middleware, such a request would reach your controllers empty (or fail with a misleading
CSRF token mismatch). ValidatePostSize throws a Beebmx\KirbyMiddleware\Exception\PostTooLargeException
instead, which Kirby renders as an error page with a 413 status code.
The check is skipped when post_max_size is 0 (unlimited).
Group middlewares
The group middlewares will depend on routes to be triggered. By default, the group middleware comes with the web, auth and guest middleware, it brings a ValidateCsrfToken middlewares.
You can set the routes by adding the routes values in your config.php file:
'beebmx.middleware' => [ 'routes' => [ 'web' => [ 'blog/(:any)', 'content/(:alpha)', 'page/(:num)', ] ], ],
Note
You can add a pattern like any Kirby route
By default, the web group comes with the (:all) route.
The auth and guest middlewares are inactive by default, but you can customize the routes to enable them.
And of course, you can add more features to the web middleware in your config.php file:
'beebmx.middleware' => [ 'web' => [ MyOwnMiddleware::class, ], ],
If the web group is not what you need, you can add a new group of middleware. You can add it within the config.php file:
'beebmx.middleware' => [ 'groups' => [ MyOwnMiddlewareGroup::class, ], ],
The Middleware Group should looks like:
use Beebmx\KirbyMiddleware\MiddlewareGroups\MiddlewareGroup; class MyOwnMiddlewareGroup extends MiddlewareGroup { public string $name = 'review'; public string|array|null $routes = [ 'blog/(:any)', 'content/(:alpha)', ]; public array $group = [ ReviewBlogMiddleware::class, ReviewContentMiddleware::class, ReviewByAuthorMiddleware::class, ]; }
Important
All the group middleware classes should extend Beebmx\KirbyMiddleware\MiddlewareGroups\MiddlewareGroup class.
ValidateCsrfToken
When you use an HTML form with POST, PUT, PATCH, or DELETE in your template, you should include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request.
<form method="POST" action="myPage"> <input type="hidden" name="_token" value="<?= csrf() ?>" /> </form>
Note
Besides _token, the field can also be named csrf, csrf-token, x-csrf or x-csrf-token.
For JavaScript requests, you can send the token in an X-CSRF, X-CSRF-Token or X-XSRF-Token header instead.
Sometimes you need to ignore some routes from the CSRF validation; you can skip it with:
'beebmx.middleware' => [ 'exceptions' => [ 'csrf' => [ 'payment', 'test', 'webhooks/*', ], ], ],
Use * as a wildcard to skip every path that starts with a prefix; webhooks/* skips webhooks/stripe and webhooks/github/push.
Security middlewares
Middleware comes with two (auth and guest) middlewares to improve your security flow based on user authentication.
Auth middleware
The auth middleware provides a starting point to validate if the user is authenticated and if the user is able to visit given routes. If not, it will redirect to some URL to perform a proper login.
Heres an example of it:
'beebmx.middleware' => [ 'routes' => [ 'auth' => [ 'dashboard', 'dashboard/(:all)', 'logout', ], ], 'redirections' => [ 'guest' => 'login', ], ],
Note
If the user is not authenticated, the middleware will redirect to a guest page.
Guest middleware
The guest middleware provides a starting point to validate if the visitor is a guest and is unauthenticated. If the user is authenticated, it will redirect to some URL to be inside a secured welcome page or dashboard.
Heres an example of it:
'beebmx.middleware' => [ 'routes' => [ 'guest' => [ 'login', ], ], 'redirections' => [ 'auth' => 'dashboard', ], ],
Note
If the user is authenticated, the middleware will redirect to a auth page.
Middleware
When you create a middleware, you can use a class or a Closure; it will depend on your needs and complexity.
Middleware class
When you create your own middleware class, it should look like:
use Beebmx\KirbyMiddleware\Request; use Closure; class ValidateSomeInformation { public function handle(Request $request, Closure $next) { // Perform action return $next($request); } }
As you can see, handle requires two parameters: a Request called $request and a Closure called $next.
The $request contains the current request made in Kirby. The middleware runs in the route:after hook,
once Kirby has resolved the page but before the page controller and template run. Pages returned by your own
routes are covered too; other custom routes are not.
The second parameter $next, you should call it at the end of the process to proceed to the next middleware validation with the $request.
If you need, some validations can prevent to continue with any other validation; you can throw an error or make a response redirection. Kirby then sends that error page or response instead of the page, without running its controller or template:
use Beebmx\KirbyMiddleware\Request; use Closure; use Kirby\Http\Response; class UserShouldBeAuthenticated { public function handle(Request $request, Closure $next) { if(empty($request->user())) { return Response::redirect('login') } return $next($request); } }
Or with an exception:
use Beebmx\KirbyMiddleware\Request; use Closure; use Kirby\Exception\ErrorPageException; class UserShouldBeAuthenticated { public function handle(Request $request, Closure $next) { if(empty($request->user())) { throw new ErrorPageException( fallback: 'Unauthorized', httpCode: 401, ); } return $next($request); } }
For Kirby 4, use the legacy constructor in the example above:
throw new ErrorPageException([ 'fallback' => 'Unauthorized', 'httpCode' => 401, ]);
Middleware shared between Kirby 4 and newer versions can select the constructor
with version_compare(\Kirby\Cms\App::version(), '5.0.0', '<').
Closure middleware
The easiest way to add a global, web, auth or guest middleware is with a Closure; when you add a closure, it should look like:
use Beebmx\KirbyMiddleware\Request; use Closure; 'beebmx.middleware' => [ 'web' => [ function (Request $request, Closure $next) { // Perform action return $next($request); }, ], ],
Important
Remember to call the $next closure to proceed to the next validation with the $request.
Options
| Option | Default | Type | Description |
|---|---|---|---|
| beebmx.middleware.enabled | true | bool |
Enable/Disable all Middleware. |
| beebmx.middleware.exceptions | [] | array |
Set exceptions for trim, empty and csrf middlewares. |
| beebmx.middleware.global | [] | array |
Add your own global middlewares. |
| beebmx.middleware.groups | [] | array |
Add your own groups middlewares. |
| beebmx.middleware.routes | [] | array |
Customize your group routes. |
| beebmx.middleware.web | [] | array |
Add your own web middlewares. |
| beebmx.middleware.auth | [] | array |
Add your own auth middlewares. |
| beebmx.middleware.guest | [] | array |
Add your own guest middlewares. |
| beebmx.middleware.redirections | [] | array |
Customize your redirections for auth and guest middlewares. |
Warning
Since version 1.3.0, Middleware changes the plugin prefix from beebmx.kirby-middleware to beebmx.middleware.
Disable middleware
You can completly disable all middleware validations updating the enable value in the config.php file:
'beebmx.middleware' => [ 'enabled' => false, ],
Facades
There are some facades to simplify the use of this plugin:
| Facade | Class | Instance of |
|---|---|---|
| Beebmx\KirbyMiddleware\Facades\Middleware | Beebmx\KirbyMiddleware\Middleware | Middleware::instance() |
| Beebmx\KirbyMiddleware\Facades\Pipeline | Beebmx\Pipeline\Pipeline | new Pipeline |
| Beebmx\KirbyMiddleware\Facades\Request | Beebmx\KirbyMiddleware\Request | Request::instance() |
Plugins
If you are creating your own plugin, and it's required to use some type of request manipulation, Middleware is also for you.
Installation
First, you need to inform Middleware than you have some global middleware or group middleware to register.
The easyest way to do this, is with a hook
use Kirby\Cms\App as Kirby; use Beebmx\KirbyMiddleware\Facades\Middleware; Kirby::plugin('beebmx/kirby-security', [ 'hooks' => [ 'system.loadPlugins:after' => function () { Middleware::appendToGroup('security', [ ValidateUser::class, ValidateUserRole::class, ValidateUserTeam::class, ]); }, ], ]);
Global methods
You can add your own validations to the global middleware. To achieve this, you have several methods.
Append
The append method adds the middleware to the end of the global middleware.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::append(ValidateVisitor::class);
Prepend
The prepend method adds the middleware to the beginning of the global middleware.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::prepend(ValidateVisitor::class);
getGlobalMiddleware
The getGlobalMiddleware method returns an array of all the global middleware registered.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::getGlobalMiddleware();
Group methods
You can add your own validations to the groups middleware. To achieve this, you have several methods.
Append
The appendToGroup method adds the middleware to the end of the groups middlewares.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::appendToGroup('security', [ ValidateUser::class, ValidateUserRole::class, ValidateUserTeam::class, ]);
prependToGroup
The prependToGroup method adds the middleware to the beginning of the groups middlewares.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::prependToGroup('security', [ ValidateUser::class, ValidateUserRole::class, ValidateUserTeam::class, ]);
removeFromGroup
The removeFromGroup method removes some middleware from a specific group middleware.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::removeFromGroup('security', ValidateVisitor::class);
addClassToGroup
The addClassToGroup method adds a Middleware Group class to the groups middlewares.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::addClassToGroup(SecurityMiddlewareGroup::class);
getMiddlewareGroups
The getMiddlewareGroups method returns an array of all the groups middleware registered.
use Beebmx\KirbyMiddleware\Facades\Middleware; Middleware::getMiddlewareGroups();
Authenticate middleware
You can customize the Authenticate middleware without using options, but hook system.loadPlugins:after.
redirectUsing
To set the route to redirect if the user is not authenticated.
use Beebmx\KirbyMiddleware\Middlewares\Authenticate; Authenticate::redirectUsing('login');
setRoutes
If you want to set the routes for the AuthMiddlewareGroup.
use Beebmx\KirbyMiddleware\MiddlewareGroups\AuthMiddlewareGroup; AuthMiddlewareGroup::setRoutes([ 'dashboard', 'logout', ]);
RedirectIfAuthenticated middleware
You can customize the RedirectIfAuthenticated middleware without using options, but hook system.loadPlugins:after.
redirectUsing
To set the route to redirect if the user is authenticated.
use Beebmx\KirbyMiddleware\Middlewares\RedirectIfAuthenticated; RedirectIfAuthenticated::redirectUsing('dashboard');
setRoutes
If you want to set the routes for the GuestMiddlewareGroup.
use Beebmx\KirbyMiddleware\MiddlewareGroups\GuestMiddlewareGroup; GuestMiddlewareGroup::MiddlewareGroup::setRoutes([ 'login', ]);
Important
Remember, all the group middleware classes should extend Beebmx\KirbyMiddleware\MiddlewareGroups\MiddlewareGroup class.
Roadmap
- Custom hooks
License
Licensed under the MIT.
Credits
- Fernando Gutierrez @beebmx
- All Contributors