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
Comment #2
wim leersDid you create a to allow others with the same question to find the same answer, and did you mark it because you already figured out the answer?
If "yes & yes": 🙏 👏
That being said, if you can articulate your use case, I think the
media.modulemaintainers would be happy to accept a patch to refine theMediaTypeAccessControlHandler:)Comment #3
Roensby commentedhttps://www.drupal.org/project/drupal/issues/3040465
Comment #4
wim leers👍
Comment #5
gabesulliceThe proposed solution in this issue would add
drupal_internal__idto 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
typemember (which ismedia--{bundle}) is not already enough.Comment #6
Roensby commentedThanks @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.
Comment #7
wim leersOh, hah, I thought you needed some information stored on the
MediaTypeentity :) Well, great, even simpler then!