function UserAccessControlHandler::checkAccess
Same name in other branches
- 9 core/modules/user/src/UserAccessControlHandler.php \Drupal\user\UserAccessControlHandler::checkAccess()
- 8.9.x core/modules/user/src/UserAccessControlHandler.php \Drupal\user\UserAccessControlHandler::checkAccess()
- 11.x core/modules/user/src/UserAccessControlHandler.php \Drupal\user\UserAccessControlHandler::checkAccess()
Overrides EntityAccessControlHandler::checkAccess
File
-
core/
modules/ user/ src/ UserAccessControlHandler.php, line 30
Class
- UserAccessControlHandler
- Defines the access control handler for the user entity type.
Namespace
Drupal\userCode
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\user\UserInterface $entity*/
// We don't treat the user label as privileged information, so this check
// has to be the first one in order to allow labels for all users to be
// viewed, including the special anonymous user.
if ($operation === 'view label') {
return AccessResult::allowed();
}
// The anonymous user's profile can neither be viewed, updated nor deleted.
if ($entity->isAnonymous()) {
return AccessResult::forbidden();
}
// Administrators can view/update/delete all user profiles.
if ($account->hasPermission('administer users')) {
return AccessResult::allowed()->cachePerPermissions();
}
switch ($operation) {
case 'view':
// Only allow view access if the account is active.
$result = AccessResult::allowedIfHasPermission($account, 'access user profiles');
if ($result->isAllowed()) {
$result = $result->andIf(AccessResult::allowedIf($entity->isActive())
->addCacheableDependency($entity));
if ($result instanceof AccessResultReasonInterface) {
$result->setReason("The 'access user profiles' permission is required and the user must be active.");
}
if ($result->isAllowed()) {
return $result;
}
}
// Users can view own profiles at all times.
return $result->orIf(AccessResult::allowedIf($account->id() == $entity->id())
->addCacheContexts([
'user',
]));
case 'update':
// Users can always edit their own account.
$access_result = AccessResult::allowedIf($account->id() == $entity->id())
->cachePerUser();
if (!$access_result->isAllowed() && $access_result instanceof AccessResultReasonInterface) {
$access_result->setReason("Users can only update their own account, unless they have the 'administer users' permission.");
}
return $access_result;
case 'delete':
// Users with 'cancel account' permission can cancel their own account.
return AccessResult::allowedIfHasPermission($account, 'cancel account')->andIf(AccessResult::allowedIf($account->id() == $entity->id())
->cachePerUser());
}
// No opinion.
return AccessResult::neutral();
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.