Example usecase: As an anonymous user, I want to retrieve a media entity from Drupal and include bundle id.

Using the jsonapi module, I find that only the entity label is returned. What gives?

The media module only allows access to the media_type label, unless the user role has the 'Administer media types' permission.

We don't want to give anonymous users the 'Administer media types' permission.

Solution:

Override the access control handler for the media_type entity. Give permission to view media_type entities if the user has permission to view media entities.

Implement hook_entity_type_alter() and add the class below in your module.

Now the full media_type entity is returned, including drupal_internal__id.


namespace Drupal\my_module\AccessControlHandler;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\media\MediaTypeAccessControlHandler;

/**
 * Access controller for the MediaType entity.
 *
 * @see \Drupal\media\Entity\MediaType.
 */
class OverrideMediaTypeAccessControlHandler extends MediaTypeAccessControlHandler {

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    /** @var \Drupal\media\Entity\MediaType. $entity */
    if ($operation === 'view') {
      return AccessResult::allowedIfHasPermission($account, 'view media');
    }
    return parent::checkAccess($entity, $operation, $account);
  }
}

Comments

Roensby created an issue. See original summary.

wim leers’s picture

Did you create a Support request to allow others with the same question to find the same answer, and did you mark it Fixed because you already figured out the answer?

If "yes & yes": 🙏 👏

That being said, if you can articulate your use case, I think the media.module maintainers would be happy to accept a patch to refine the MediaTypeAccessControlHandler :)

Roensby’s picture

wim leers’s picture

gabesullice’s picture

The proposed solution in this issue would add drupal_internal__id to the resource identifier in the relationship field that points to the media type. That would also be a way solve this issue, but in a more minimal way.

Although, I'm curious why the media resource object's type member (which is media--{bundle}) is not already enough.

Roensby’s picture

Thanks @gabesullice, apparently I couldn't see the forest for the trees. I'll just close the core issue, since this is obviously not the problem I thought it was.

wim leers’s picture

Oh, hah, I thought you needed some information stored on the MediaType entity :) Well, great, even simpler then!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.