I want to create a page that should only be viewable by logged in users. Via Protecting files | Kirby CMS I can only save the images for one page. However, I would like to secure all images and all other assets from unauthorized access (they should be displayed normally for logged-in users and not be offered as a download). How do I do that?
This should work:
Plugin:
<?php
use Kirby\Cms\Response;
Kirby::plugin('cookbook/files-firewall', [
'routes' => [
[
'pattern' => 'content/downloads/(:any)',
'action' => function ($filename) {
if (kirby()->user() &&
$file = page('downloads')?->files()?->findBy('filename', $filename)) {
return Response::file($file->root());
}
return false;
},
],
],
'components' => [
'file::url' => function (Kirby $kirby, $file) {
if ($file->template() === 'protected') {
return $kirby->url() . '/content/' . $file->page()->id() . '/' . $file->filename();
}
return $kirby->nativeComponent('file::url')($kirby, $file);
},
'file::version' => function ($kirby, Kirby\Cms\File $file, array $options = []) {
static $original;
// if the file is protected, return the original file
if ($file->template() === 'protected') {
return $file;
}
// if static $original is null, get the original component
if ($original === null) {
$original = $kirby->nativeComponent('file::version');
}
// and return it with the given options
return $original($kirby, $file, $options);
},
],
]);
Template:
<?php snippet('header') ?>
<section>
<h1 class="h1"><?= $page->title()->html() ?></h1>
<ul class="file-list">
<?php foreach( $page->files()->template('protected') as $file ) : ?>
<li><?= $file ?></li>
<?php endforeach ?>
</ul>
</section>
<?php snippet('footer') ?>
Note that you cannot use thumbs for images in this case.