Find list of Members in group using google api services

我的梦境 提交于 2020-01-15 08:43:22

问题


<?php
include_once "templates/base.php";
session_start();

require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');

$client_id = '*******';
$client_secret = '*******';
$redirect_uri = '*********';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

$client->addScope("https://www.googleapis.com/auth/admin.directory.group");

$directory = new Google_Service_Directory($client);

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

if ($client->getAccessToken())
{
    $groupKey = "MY_EMAIL";
    $group = $directory->members->listMembers($groupKey);

    $_SESSION['access_token'] = $client->getAccessToken();
}

echo pageHeader("Group Members");

if (strpos($client_id, "googleusercontent") == false) {
  echo missingClientSecretsWarning();
  exit;
}
?>
<div class="box">
      <div class="request">
        <?php 
        if (isset($authUrl)) {
          echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
        } else {
          echo "<a class='logout' href='?logout'>Logout</a>";
        }
        ?>
      </div>

      <div class="shortened">
        <?php
        if (isset($group)) {
          var_dump($group);
        }
        ?>
      </div>
</div>

I have implemented this example in my local system to find all members of groups using google api client php. but i dont know why when i m connect to google using auth and allow permission to access directory, when redirect its not return list.

So please help me and suggest me where i m doing wrong in this code.

I m using Email as my groupKey.


回答1:


Here is some code I wrote that I think might help you. This code will pull a listing of all the groups you have read access to and their memberships.

When pulling the groups, I check if the variable nextPageToken is set. If this is set, it means you have reached the 200 max limit result set. If nextPageToken is set, the code will continue to loop and grab the next set until nextPageToken is blank.

I make use of the batch class in the first pass at getting group memberships to speed things up. After the first pass, I again then check for the existence of the nextPageToken variable and continue to loop until all members are returned.

After the script runs, an array called $lists is populated with all the groups and their respective memberships.

<?php
  $start = microtime(true);

  require_once('/path/to/google-api-php-client/src/Google/autoload.php');
  $service_account_name = 'your service account address'; //Email Address
  $key_file_location = '/path/to/your.p12'; //key.p12

  $client = new Google_Client();
  $client->setApplicationName("Client_Library_Examples");
  $dir = new Google_Service_Directory($client);
  $domain = 'yourdomain.com';

  if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
  }

  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/admin.directory.group.readonly'),
    $key
  );

  $cred->sub = "admin@yourdomain.com"; // a privilidged users email address
  $client->setAssertionCredentials($cred);
  if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  $_SESSION['service_token'] = $client->getAccessToken();

  // Get all of our groups
  $googleGroups = $dir->groups->listGroups(array('domain'=>$domain));
  $groups = $googleGroups->getGroups();

  // if we have a paginated result set, continue doing a lookup until we are at the end
  while (isset($googleGroups->nextPageToken) && ($googleGroups->nextPageToken != '')) {
    $googleGroups = $dir->groups->listGroups(array('domain'=>$domain,'pageToken'=>$googleGroups->nextPageToken));
    $groups = array_merge($groups, $googleGroups->getGroups());
  }

  // Ok, we have all our groups. Now lets build an array that we can use later to populate with group members
  $lists = array();
  foreach ($groups as $key=>$val) {
    $lists[$val->id] = array('id'=>$val->id,'description'=>$val->description,'email'=>$val->email,'name'=>$val->name,'members'=>'');
  }

  // Doing a batch query for all members of the groups to reduce execution time
  $client->setUseBatch(true);
  $batch = new Google_Http_Batch($client);
  foreach ($groups as $k=>$v) {
    $members = $dir->members->listMembers($v->email);
    $batch->add($members, $v->id);
  }

  // execute our batch query
  $results = $batch->execute();

  // turn off batch queries now so we can query for more members in the case of paginated result sets
  $client->setUseBatch(False);
  foreach ($results as $k=>$v) {
    $all = $v->getMembers();
    $id = substr($k, 9); // the array key is in the form of response-XXX, lets get rid of the response- bit

    while (isset($v->nextPageToken) && ($v->nextPageToken != '')) {
      $members = $dir->members->listMembers($lists[$id]['email'],array("pageToken"=>$v->nextPageToken));
      $v->nextPageToken = $members->nextPageToken;
      $all = array_merge($all, $members->getMembers());
    }

    foreach ($all as $key=>$val) {
      $lists[$id]['members'][] = $val->email;
    }

  }

  $time_elapsed_secs = microtime(true) - $start;
  print "\n\n" . $time_elapsed_secs . "\n\n";



回答2:


https://developers.google.com/admin-sdk/directory/v1/reference/members/list

You can check this link and this is the "GET" for it

GET https://www.googleapis.com/admin/directory/v1/groups/groupKey/members



来源:https://stackoverflow.com/questions/31891762/find-list-of-members-in-group-using-google-api-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!