0

Following the Lullabot article on how to embed anything in a wysiwyg with Entity Embed and friends we're using this to embed a custom entity type created with ECK (Entity Construction Kit).

The permissions for ECK require anonymous users have the "View My Entity" permission in order for it to appear in the embedded scenario. However ECK also provides a full page URL at /my_entity/{id}, but we want to restrict access and not index the full page, because the content will always be embedded inside other Articles.

I've already implemented the Metatag module for this entity to add the robots noindex meta tag. However the ideal case would be to restrict the ECK full page URL /my_entity/{id} to administrators only. How can this be done, when these entity types are dynamic and don't have a canonical route.

0

It turns out that though the entities created by ECK are dynamic, they do have route definitions, so we can use this to restrict access, in a hook_preprocess_page placed in a custom module. Also worth noting that the administrative list display at /admin/content/my_eck_entity is visible to anonymous users when you set the view my_eck_entity entities permission to anonymous users, so we must also look out for this route as well.

use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Prepares variables for page.html.twig.
 */
function mymodule_preprocess_page(&$variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();

  // Restrict access to ECK canonical full page display and the entity
  // administration list screen to content authors. Restricting full page
  // display helps to avoid mistakenly indexing the content in search engines
  // because these entities are only ever going to be seen by anonymous users
  // when embedded into other pages via WYSIWYG embed or rendered entities
  // from entity reference fields on other node types.
  $user = \Drupal::currentUser();
  $restricted_eck_entities = [
    'my_eck_entity', // Replace this with real entity type machine name!
  ];
  foreach ($restricted_eck_entities as $eck_entity) {
    if (
      (
        $route_name === "entity.$eck_entity.canonical"
        || $route_name === "eck.entity.$eck_entity.list"
      )
      && !(
        $user->hasPermission("create $eck_entity entities")
        || $user->hasPermission("edit $eck_entity entities")
      )
    ) {
      throw new AccessDeniedHttpException();
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.