Skip to content

Commit

Permalink
Issue CollaboraOnline#27: Check Collabora access in the field formatter.
Browse files Browse the repository at this point in the history
  • Loading branch information
donquixote committed Sep 13, 2024
1 parent 93d12ed commit 2ff8140
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions src/Plugin/Field/FieldFormatter/CoolPreview.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@

namespace Drupal\collabora_online\Plugin\Field\FieldFormatter;

use Drupal\collabora_online\Access\CollaboraAccessCheck;
use Drupal\collabora_online\Cool\CoolUtils;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\media\MediaInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Plugin implementation of the 'collabora_preview' formatter.
Expand All @@ -27,6 +32,67 @@
* )
*/
class CoolPreview extends EntityReferenceFormatterBase {

/**
* Constructor.
*
* @param string $plugin_id
* Plugin id.
* @param array $plugin_definition
* Plugin definition of this field formatter.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* Field definition.
* @param array $settings
* Formatter settings.
* @param string $label
* Label for this field display.
* @param string $view_mode
* View mode.
* @param array $third_party_settings
* Third party settings.
*/
public function __construct(
string $plugin_id,
array $plugin_definition,
FieldDefinitionInterface $field_definition,
array $settings,
string $label,
string $view_mode,
array $third_party_settings,
private readonly CollaboraAccessCheck $accessCheck,
) {
parent::__construct(
$plugin_id,
$plugin_definition,
$field_definition,
$settings,
$label,
$view_mode,
$third_party_settings,
);
}

/**
* {@inheritdoc}
*/
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition,
): static {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get(CollaboraAccessCheck::class),
);
}

/**
* {@inheritdoc}
*/
Expand All @@ -48,6 +114,15 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
return [];
}

$access_result = $this->accessCheck->mediaAccess($media, 'preview');
(new CacheableMetadata())
->addCacheableDependency($access_result)
->applyTo($elements);

if (!$access_result->isAllowed()) {
return $elements;
}

foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$url = CoolUtils::getEditorUrl($media, false);

Expand Down

0 comments on commit 2ff8140

Please sign in to comment.