You are here

function apigee_edge_teams_api_product_access in Apigee Edge 8

Implements hook_ENTITY_TYPE_access().

Grant "view" and "view label" access to team members based on their teams' API Product access.

File

modules/apigee_edge_teams/apigee_edge_teams.module, line 246
Copyright 2018 Google Inc.

Code

function apigee_edge_teams_api_product_access(EntityInterface $entity, $operation, AccountInterface $account) {

  /** @var \Drupal\apigee_edge\Entity\ApiProductInterface $entity */

  // The "assign" in not in this list, because it is handled by team API Product
  // access manager service directly. Team members should not be able to
  // assign API products to their developer apps just because they have access
  // to do that when they are creating team app for a team.
  if (!in_array($operation, [
    'view',
    'view label',
  ])) {
    return AccessResult::neutral(sprintf('%s is not supported by %s.', $operation, __FUNCTION__));
  }
  if ($account
    ->isAnonymous()) {
    return AccessResult::neutral('Anonymous user can not be member of a team.');
  }

  /** @var \Drupal\apigee_edge_teams\TeamMemberApiProductAccessHandlerInterface $access_checker */
  $access_checker = \Drupal::service('apigee_edge_teams.team_member_api_product_access_handler');

  /** @var \Drupal\apigee_edge_teams\TeamMembershipManagerInterface $team_membership_manager */
  $team_membership_manager = \Drupal::service('apigee_edge_teams.team_membership_manager');
  try {
    $developer_team_ids = $team_membership_manager
      ->getTeams($account
      ->getEmail());
  } catch (DeveloperDoesNotExistException $e) {
    return AccessResult::neutral($e
      ->getMessage());
  }
  if (empty($developer_team_ids)) {
    $result = AccessResult::neutral("{$account->getEmail()} is not member of any team.");

    // If developer's team membership changes access must be re-evaluated.
    // @see \Drupal\apigee_edge_teams\TeamMembershipManager

    /** @var \Drupal\apigee_edge\Entity\Storage\DeveloperStorageInterface $developer_storage */
    $developer_storage = \Drupal::entityTypeManager()
      ->getStorage('developer');
    $developer = $developer_storage
      ->load($account
      ->getEmail());
    if ($developer) {
      $result
        ->addCacheableDependency($developer);
    }
  }
  else {

    /** @var \Drupal\apigee_edge_teams\Entity\Storage\TeamStorageInterface $team_storage */
    $team_storage = \Drupal::entityTypeManager()
      ->getStorage('team');

    /** @var \Drupal\apigee_edge_teams\Entity\TeamInterface $team */
    $teams = $team_storage
      ->loadMultiple($developer_team_ids);
    foreach ($teams as $team) {
      $result = $access_checker
        ->access($entity, $operation, $team, $account, TRUE);
      if ($result
        ->isAllowed()) {
        break;
      }
    }
  }

  // $result is always defined.
  return $result;
}