diff --git a/focal_point.routing.yml b/focal_point.routing.yml index 7d914ab..05ad4b4 100644 --- a/focal_point.routing.yml +++ b/focal_point.routing.yml @@ -4,4 +4,4 @@ focal_point.preview: _controller: '\Drupal\focal_point\Controller\FocalPointPreviewController::content' _title: 'Focal Point Preview' requirements: - _permission: 'access content' + _custom_access: '\Drupal\focal_point\Controller\FocalPointPreviewController::access' diff --git a/src/Controller/FocalPointPreviewController.php b/src/Controller/FocalPointPreviewController.php index e007d7d..c5c7416 100644 --- a/src/Controller/FocalPointPreviewController.php +++ b/src/Controller/FocalPointPreviewController.php @@ -5,8 +5,11 @@ namespace Drupal\focal_point\Controller; use Drupal\Core\Controller\ControllerBase; use Drupal\image\Entity\ImageStyle; use Drupal\file\Entity\File; +use Drupal\Core\Session\AccountInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; use Symfony\Component\Validator\Exception\InvalidArgumentException; +use Drupal\Core\Access\AccessResult; +use Drupal\Core\Entity\EntityStorageInterface; /** * Class FocalPointPreviewController. @@ -81,6 +84,43 @@ class FocalPointPreviewController extends ControllerBase { } /** + * Deny users access to the preview page unless they have permission to edit + * an entity (any entity) that references the current image being previewed. + * + * @param \Drupal\Core\Session\AccountInterface $account + * The current user. + * @param $fid + * The file id for the image being previewed from the URL. + * + * @return \Drupal\Core\Access\AccessResult + */ + public function access(AccountInterface $account, $fid) { + $access = AccessResult::forbidden(); + + // @todo: I should be able to use "magic args" to load the file directly. + $file = File::load($fid); + $image = \Drupal::service('image.factory')->get($file->getFileUri()); + if (!$image->isValid()) { + throw new InvalidArgumentException('The file with id = $fid is not an image.'); + } + + if (function_exists('file_get_file_references')) { + $references = file_get_file_references($file, NULL, EntityStorageInterface::FIELD_LOAD_REVISION, ''); + foreach ($references as $field_name => $data) { + foreach (array_keys($data) as $entity_type_id) { + if ($account->hasPermission($entity_type_id . ".edit")) { + $access = AccessResult::allowed(); + break; + } + } + } + + } + + return $access; + } + + /** * Build a list of image styles that include an effect defined by focal point. * * @return array