EntityAccessControlHandler.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Field\FieldItemListInterface;
  5. use Drupal\Core\Field\FieldDefinitionInterface;
  6. use Drupal\Core\Language\LanguageInterface;
  7. use Drupal\Core\Session\AccountInterface;
  8. /**
  9. * Defines a default implementation for entity access control handler.
  10. */
  11. class EntityAccessControlHandler extends EntityHandlerBase implements EntityAccessControlHandlerInterface {
  12. /**
  13. * Stores calculated access check results.
  14. *
  15. * @var array
  16. */
  17. protected $accessCache = [];
  18. /**
  19. * The entity type ID of the access control handler instance.
  20. *
  21. * @var string
  22. */
  23. protected $entityTypeId;
  24. /**
  25. * Information about the entity type.
  26. *
  27. * @var \Drupal\Core\Entity\EntityTypeInterface
  28. */
  29. protected $entityType;
  30. /**
  31. * Allows to grant access to just the labels.
  32. *
  33. * By default, the "view label" operation falls back to "view". Set this to
  34. * TRUE to allow returning different access when just listing entity labels.
  35. *
  36. * @var bool
  37. */
  38. protected $viewLabelOperation = FALSE;
  39. /**
  40. * Constructs an access control handler instance.
  41. *
  42. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  43. * The entity type definition.
  44. */
  45. public function __construct(EntityTypeInterface $entity_type) {
  46. $this->entityTypeId = $entity_type->id();
  47. $this->entityType = $entity_type;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function access(EntityInterface $entity, $operation, AccountInterface $account = NULL, $return_as_object = FALSE) {
  53. $account = $this->prepareUser($account);
  54. $langcode = $entity->language()->getId();
  55. if ($operation === 'view label' && $this->viewLabelOperation == FALSE) {
  56. $operation = 'view';
  57. }
  58. // If an entity does not have a UUID, either from not being set or from not
  59. // having them, use the 'entity type:ID' pattern as the cache $cid.
  60. $cid = $entity->uuid() ?: $entity->getEntityTypeId() . ':' . $entity->id();
  61. // If the entity is revisionable, then append the revision ID to allow
  62. // individual revisions to have specific access control and be cached
  63. // separately.
  64. if ($entity instanceof RevisionableInterface) {
  65. /** @var $entity \Drupal\Core\Entity\RevisionableInterface */
  66. $cid .= ':' . $entity->getRevisionId();
  67. }
  68. if (($return = $this->getCache($cid, $operation, $langcode, $account)) !== NULL) {
  69. // Cache hit, no work necessary.
  70. return $return_as_object ? $return : $return->isAllowed();
  71. }
  72. // Invoke hook_entity_access() and hook_ENTITY_TYPE_access(). Hook results
  73. // take precedence over overridden implementations of
  74. // EntityAccessControlHandler::checkAccess(). Entities that have checks that
  75. // need to be done before the hook is invoked should do so by overriding
  76. // this method.
  77. // We grant access to the entity if both of these conditions are met:
  78. // - No modules say to deny access.
  79. // - At least one module says to grant access.
  80. $access = array_merge(
  81. $this->moduleHandler()->invokeAll('entity_access', [$entity, $operation, $account]),
  82. $this->moduleHandler()->invokeAll($entity->getEntityTypeId() . '_access', [$entity, $operation, $account])
  83. );
  84. $return = $this->processAccessHookResults($access);
  85. // Also execute the default access check except when the access result is
  86. // already forbidden, as in that case, it can not be anything else.
  87. if (!$return->isForbidden()) {
  88. $return = $return->orIf($this->checkAccess($entity, $operation, $account));
  89. }
  90. $result = $this->setCache($return, $cid, $operation, $langcode, $account);
  91. return $return_as_object ? $result : $result->isAllowed();
  92. }
  93. /**
  94. * We grant access to the entity if both of these conditions are met:
  95. * - No modules say to deny access.
  96. * - At least one module says to grant access.
  97. *
  98. * @param \Drupal\Core\Access\AccessResultInterface[] $access
  99. * An array of access results of the fired access hook.
  100. *
  101. * @return \Drupal\Core\Access\AccessResultInterface
  102. * The combined result of the various access checks' results. All their
  103. * cacheability metadata is merged as well.
  104. *
  105. * @see \Drupal\Core\Access\AccessResultInterface::orIf()
  106. */
  107. protected function processAccessHookResults(array $access) {
  108. // No results means no opinion.
  109. if (empty($access)) {
  110. return AccessResult::neutral();
  111. }
  112. /** @var \Drupal\Core\Access\AccessResultInterface $result */
  113. $result = array_shift($access);
  114. foreach ($access as $other) {
  115. $result = $result->orIf($other);
  116. }
  117. return $result;
  118. }
  119. /**
  120. * Performs access checks.
  121. *
  122. * This method is supposed to be overwritten by extending classes that
  123. * do their own custom access checking.
  124. *
  125. * @param \Drupal\Core\Entity\EntityInterface $entity
  126. * The entity for which to check access.
  127. * @param string $operation
  128. * The entity operation. Usually one of 'view', 'view label', 'update' or
  129. * 'delete'.
  130. * @param \Drupal\Core\Session\AccountInterface $account
  131. * The user for which to check access.
  132. *
  133. * @return \Drupal\Core\Access\AccessResultInterface
  134. * The access result.
  135. */
  136. protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
  137. if ($operation == 'delete' && $entity->isNew()) {
  138. return AccessResult::forbidden()->addCacheableDependency($entity);
  139. }
  140. if ($admin_permission = $this->entityType->getAdminPermission()) {
  141. return AccessResult::allowedIfHasPermission($account, $admin_permission);
  142. }
  143. else {
  144. // No opinion.
  145. return AccessResult::neutral();
  146. }
  147. }
  148. /**
  149. * Tries to retrieve a previously cached access value from the static cache.
  150. *
  151. * @param string $cid
  152. * Unique string identifier for the entity/operation, for example the
  153. * entity UUID or a custom string.
  154. * @param string $operation
  155. * The entity operation. Usually one of 'view', 'update', 'create' or
  156. * 'delete'.
  157. * @param string $langcode
  158. * The language code for which to check access.
  159. * @param \Drupal\Core\Session\AccountInterface $account
  160. * The user for which to check access.
  161. *
  162. * @return \Drupal\Core\Access\AccessResultInterface|null
  163. * The cached AccessResult, or NULL if there is no record for the given
  164. * user, operation, langcode and entity in the cache.
  165. */
  166. protected function getCache($cid, $operation, $langcode, AccountInterface $account) {
  167. // Return from cache if a value has been set for it previously.
  168. if (isset($this->accessCache[$account->id()][$cid][$langcode][$operation])) {
  169. return $this->accessCache[$account->id()][$cid][$langcode][$operation];
  170. }
  171. }
  172. /**
  173. * Statically caches whether the given user has access.
  174. *
  175. * @param \Drupal\Core\Access\AccessResultInterface $access
  176. * The access result.
  177. * @param string $cid
  178. * Unique string identifier for the entity/operation, for example the
  179. * entity UUID or a custom string.
  180. * @param string $operation
  181. * The entity operation. Usually one of 'view', 'update', 'create' or
  182. * 'delete'.
  183. * @param string $langcode
  184. * The language code for which to check access.
  185. * @param \Drupal\Core\Session\AccountInterface $account
  186. * The user for which to check access.
  187. *
  188. * @return \Drupal\Core\Access\AccessResultInterface
  189. * Whether the user has access, plus cacheability metadata.
  190. */
  191. protected function setCache($access, $cid, $operation, $langcode, AccountInterface $account) {
  192. // Save the given value in the static cache and directly return it.
  193. return $this->accessCache[$account->id()][$cid][$langcode][$operation] = $access;
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function resetCache() {
  199. $this->accessCache = [];
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function createAccess($entity_bundle = NULL, AccountInterface $account = NULL, array $context = [], $return_as_object = FALSE) {
  205. $account = $this->prepareUser($account);
  206. $context += [
  207. 'entity_type_id' => $this->entityTypeId,
  208. 'langcode' => LanguageInterface::LANGCODE_DEFAULT,
  209. ];
  210. $cid = $entity_bundle ? 'create:' . $entity_bundle : 'create';
  211. if (($access = $this->getCache($cid, 'create', $context['langcode'], $account)) !== NULL) {
  212. // Cache hit, no work necessary.
  213. return $return_as_object ? $access : $access->isAllowed();
  214. }
  215. // Invoke hook_entity_create_access() and hook_ENTITY_TYPE_create_access().
  216. // Hook results take precedence over overridden implementations of
  217. // EntityAccessControlHandler::checkCreateAccess(). Entities that have
  218. // checks that need to be done before the hook is invoked should do so by
  219. // overriding this method.
  220. // We grant access to the entity if both of these conditions are met:
  221. // - No modules say to deny access.
  222. // - At least one module says to grant access.
  223. $access = array_merge(
  224. $this->moduleHandler()->invokeAll('entity_create_access', [$account, $context, $entity_bundle]),
  225. $this->moduleHandler()->invokeAll($this->entityTypeId . '_create_access', [$account, $context, $entity_bundle])
  226. );
  227. $return = $this->processAccessHookResults($access);
  228. // Also execute the default access check except when the access result is
  229. // already forbidden, as in that case, it can not be anything else.
  230. if (!$return->isForbidden()) {
  231. $return = $return->orIf($this->checkCreateAccess($account, $context, $entity_bundle));
  232. }
  233. $result = $this->setCache($return, $cid, 'create', $context['langcode'], $account);
  234. return $return_as_object ? $result : $result->isAllowed();
  235. }
  236. /**
  237. * Performs create access checks.
  238. *
  239. * This method is supposed to be overwritten by extending classes that
  240. * do their own custom access checking.
  241. *
  242. * @param \Drupal\Core\Session\AccountInterface $account
  243. * The user for which to check access.
  244. * @param array $context
  245. * An array of key-value pairs to pass additional context when needed.
  246. * @param string|null $entity_bundle
  247. * (optional) The bundle of the entity. Required if the entity supports
  248. * bundles, defaults to NULL otherwise.
  249. *
  250. * @return \Drupal\Core\Access\AccessResultInterface
  251. * The access result.
  252. */
  253. protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
  254. if ($admin_permission = $this->entityType->getAdminPermission()) {
  255. return AccessResult::allowedIfHasPermission($account, $admin_permission);
  256. }
  257. else {
  258. // No opinion.
  259. return AccessResult::neutral();
  260. }
  261. }
  262. /**
  263. * Loads the current account object, if it does not exist yet.
  264. *
  265. * @param \Drupal\Core\Session\AccountInterface $account
  266. * The account interface instance.
  267. *
  268. * @return \Drupal\Core\Session\AccountInterface
  269. * Returns the current account object.
  270. */
  271. protected function prepareUser(AccountInterface $account = NULL) {
  272. if (!$account) {
  273. $account = \Drupal::currentUser();
  274. }
  275. return $account;
  276. }
  277. /**
  278. * {@inheritdoc}
  279. */
  280. public function fieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account = NULL, FieldItemListInterface $items = NULL, $return_as_object = FALSE) {
  281. $account = $this->prepareUser($account);
  282. // Get the default access restriction that lives within this field.
  283. $default = $items ? $items->defaultAccess($operation, $account) : AccessResult::allowed();
  284. // Explicitly disallow changing the entity ID and entity UUID.
  285. $entity = $items ? $items->getEntity() : NULL;
  286. if ($operation === 'edit' && $entity) {
  287. if ($field_definition->getName() === $this->entityType->getKey('id')) {
  288. // String IDs can be set when creating the entity.
  289. if (!($entity->isNew() && $field_definition->getType() === 'string')) {
  290. return $return_as_object ? AccessResult::forbidden('The entity ID cannot be changed.')->addCacheableDependency($entity) : FALSE;
  291. }
  292. }
  293. elseif ($field_definition->getName() === $this->entityType->getKey('uuid')) {
  294. // UUIDs can be set when creating an entity.
  295. if (!$entity->isNew()) {
  296. return $return_as_object ? AccessResult::forbidden('The entity UUID cannot be changed.')->addCacheableDependency($entity) : FALSE;
  297. }
  298. }
  299. }
  300. // Get the default access restriction as specified by the access control
  301. // handler.
  302. $entity_default = $this->checkFieldAccess($operation, $field_definition, $account, $items);
  303. // Combine default access, denying access wins.
  304. $default = $default->andIf($entity_default);
  305. // Invoke hook and collect grants/denies for field access from other
  306. // modules. Our default access flag is masked under the ':default' key.
  307. $grants = [':default' => $default];
  308. $hook_implementations = $this->moduleHandler()->getImplementations('entity_field_access');
  309. foreach ($hook_implementations as $module) {
  310. $grants = array_merge($grants, [$module => $this->moduleHandler()->invoke($module, 'entity_field_access', [$operation, $field_definition, $account, $items])]);
  311. }
  312. // Also allow modules to alter the returned grants/denies.
  313. $context = [
  314. 'operation' => $operation,
  315. 'field_definition' => $field_definition,
  316. 'items' => $items,
  317. 'account' => $account,
  318. ];
  319. $this->moduleHandler()->alter('entity_field_access', $grants, $context);
  320. $result = $this->processAccessHookResults($grants);
  321. return $return_as_object ? $result : $result->isAllowed();
  322. }
  323. /**
  324. * Default field access as determined by this access control handler.
  325. *
  326. * @param string $operation
  327. * The operation access should be checked for.
  328. * Usually one of "view" or "edit".
  329. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  330. * The field definition.
  331. * @param \Drupal\Core\Session\AccountInterface $account
  332. * The user session for which to check access.
  333. * @param \Drupal\Core\Field\FieldItemListInterface $items
  334. * (optional) The field values for which to check access, or NULL if access
  335. * is checked for the field definition, without any specific value
  336. * available. Defaults to NULL.
  337. *
  338. * @return \Drupal\Core\Access\AccessResultInterface
  339. * The access result.
  340. */
  341. protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  342. return AccessResult::allowed();
  343. }
  344. }