מעבר משירות הקבוצות לשירות המתקדם של Cloud Identity Groups

שירות Cloud Identity Groups (CIG) Advanced מספק תכונות דומות ל-Groups Service API ואפשר להשתמש בו במקומו.

במאמר הזה מוסבר איך להשתמש בשיטות העזר שזמינות כדי להשיג יכולות שוות ערך באמצעות שירות CIG Advanced.

הגדרה

כדי להשתמש בשירות המתקדם של CIG, קודם צריך להפעיל אותו בפרויקט של הסקריפט.

כדי לקצר חלק מחתימות השיטות במדריך הזה, הגדרנו את המשתנה הבא:

const groups = CloudIdentityGroups.Groups;

‫GroupsApp Methods

השיטות הבאות של העזרה תואמות לאלה של שירות הקבוצות GroupsApp.

במדריך הזה, המונח קבוצה מתייחס לGroup Resource, ולא לאובייקט Group Class. ‫Group Resources הם אובייקטים של JavaScript שאין להם שיטות, אבל אפשר להשתמש בהם ב-CIG Advanced Service כדי לאחזר מידע דומה לזה שבאובייקטים של Group Class.

getGroupByEmail

/**
 * Given a group's email, returns that group's resource
 *
 * @param {String} email: The email address to lookup a group by
 * @return {Group} group: The group resource associated with the email
 */
function groupsAppGetGroupByEmail(email) {
  // Retrieve the name ID of the group
  const groupName = groups.lookup({
    'groupKey.id': email,
    'groupKey.namespace': ''  // Optional for google groups, dynamic groups, and security groups
                              // Necessary for identity-mapped groups (see https://developers.google.com/cloud-search/docs/guides/identity-mapping)
  }).name;

  // Retrieve the group resource
  return groups.get(groupName);
}

getGroups

השיטה הבאה מחזירה רשימה של משאבי חברות. כדי למצוא את מזהה השם של אלמנט, ניגשים לשדה group שלו. השיטה הזו שימושית להרבה שיטות של שירות מתקדם של CIG. באופן דומה, אפשר לגשת ל-groupKey.id של רכיב כדי למצוא את כתובת האימייל שלו.

/**
 * Retrieves all the membership relation resources to groups which you are a
 * direct member (or a pending member).
 *
 * @return {Array<MembershipRelation>} groups : List of direct memberships where
 * you are the member.
 */
function groupsAppGetGroups() {
  const myEmail = Session.getActiveUser().getEmail();
  let pageToken = '';
  let membershipList = [];

  do {
    const queryParams = {
      query:`member_key_id=='${myEmail}'`,
      pageToken:pageToken
    };
    const searchResult = groups.Memberships.searchDirectGroups('groups/-', queryParams);
    membershipList = membershipList.concat(searchResult.memberships);
    pageToken = searchResult.nextPageToken;
  } while (pageToken);

  return membershipList;
}

Group Methods

השיטות הבאות של העזרה תואמות לאלה של שירות הקבוצות Groups Class.

getEmail

/**
 * Gets a group's email address
 *
 * @param {Object} group: A group resource
 * @return {String} email: The email associated with the group resource.
 */
function getEmail(group) {
  return group.groupKey.id;
}

getGroups

בשיטה הבאה נעשה שימוש ב-Memberships.list, שמאחזרת את כל החברים בקבוצה שצוינה. הם יכולים לכלול חברות של משתמשים וגם של קבוצות.

כדי להעריך טוב יותר את השיטה של שירות הקבוצות getGroups אפשר לסנן את החברים לפי Type. אנחנו מקבלים גישה לשדה הזה על ידי מתן FULL View כפרמטר שאילתה ל-Memberships.list או על ידי ביצוע Memberships.lookup נפרד לכל חברות נתונה.

/**
 * Fetch a list of memberships with provided group as its parent
 *
 * @param {Group} group: A group resource
 * @return {Array<Membership>} membershipList: The memberships where the parent
 * is the provided group and member is a also a group.
 */
function getGroups(group) {
  let membershipList = [];
  let pageToken = '';

  do {
    // Fetch a page of memberships
    const queryParams = {
      view: 'FULL',
      pageToken: pageToken
    }
    const response = groups.Memberships.list(group.name, queryParams);

    // Filter non-group memberships
    const onlyGroupMemberships = response.memberships.filter(
      membership => membership.type == 'GROUP'
    );
    membershipList = membershipList.concat(onlyGroupMemberships);

    // Set up next page
    pageToken = response.nextPageToken;
  } while(pageToken);

  return membershipList;
}

getRole ו-getRoles

יכול להיות ששירות הקבוצות החזיר רק את התפקיד עם העדיפות הכי גבוהה ב-getRole(), אבל השדה roles במשאב החברות מכיל רכיב נפרד לכל תפקיד שהחבר עומד בדרישות שלו (לדוגמה: חבר, בעלים, אדמין).

/**
 * Retrieve the membership roles of a member to a group.
 *
 * @param {Group} containingGroup: The group whom the member belongs to
 * @param {String} email: The email address associated with a member that
 * belongs to the containingGroup
 * @return {Array<Role>} roles: List of roles the member holds with respect to
 * the containingGroup.
 */
function getRoleWithEmail(containingGroup, email) {
  // First fetch the membership
  const membershipName = groups.Memberships.lookup(containingGroup.name, { 'memberKey.id': email }).name;
  const membership = groups.Memberships.get(membershipName);

  // Then retrieve the role
  return membership.roles;
}

/**
 * Retrieve the membership roles of a member to a group.
 *
 * @param {Group} containingGroup: The group resource whom the member belongs to
 * @param {User} user: The user associated with a member that belongs to the
 * containingGroup
 * @return {Array<Role>} roles: List of roles the member holds with respect to
 * the containingGroup
 */
function getRoleWithUser(containingGroup, user) {
  return getRoleWithEmail(containingGroup, user.getEmail());
}

/**
 * Retrieve the membership roles of a group of members to a group
 *
 * @param {Group} containingGroup: The group resource to which roles are
 * relevant
 * @param {Array<User>} users: List of users to fetch roles from
 * @return {Array<Array<Role>>} roles: A list where every element is a list of
 * roles of member to the containingGroup
 */
function getRoles(containingGroup, users) {
  let roles = [];
  for (const user of users) {
    roles.push(getRoleWithUser(containingGroup, user));
  }
  return roles;
}

getUsers

בדומה לגישה שלנו ב-getGroups, אנחנו יכולים לאחזר את החברים בקבוצה באמצעות Memberships.list ולסנן את התוצאות כדי להשאיר רק את Type המבוקש.

/**
 * Given a group, retrieve its direct members and banned members of the group
 * that have a known corresponding Google Account.
 *
 * @param {Group} group: The group Resource whom the users being queried belong
 * to
 * @return {Array<String>} users: A list of emails associated with members of
 * the given group
 */
function getUsers(group) {
  let userList = [];
  let pageToken = '';

  do {
    // Fetch a page of memberships from the group
    const queryParams = {
      view: 'FULL',
      pageToken: pageToken
    }
    const listResponse = groups.Memberships.list(group.name, queryParams);

    // Filter non-users and keep member emails
    const users = listResponse.memberships
      .filter(membership => membership.type == 'USER')
      .map(membership => membership.preferredMemberKey.id);
    userList = userList.concat(users);

    // Prepare next page
    pageToken = listResponse.nextPageToken;
  } while (pageToken);

  return userList;
}

hasGroup ו-hasUser

גם שירות הקבוצות hasGroup וגם hasUser מאשרים אם ישות מסוימת היא חברה בקבוצה נתונה. מכיוון שגם קבוצה וגם משתמש יכולים להיות מיוצגים על ידי כתובת אימייל, אפשר להשתמש בשיטה הבאה כדי לוודא אם אחד מהם שייך לקבוצה מסוימת.

/**
 * Tests if the given email has an associated direct member to the given group.
 *
 * @param {Group} group: Group resource to which the entity is being checked as
 * a member
 * @param {String} email: Email that can represent a Group or User entity
 * @return {Boolean} isMember: Whether the entity is a direct member to the
 * group or not
 */
function checkDirectGroupMembership(group, email) {
  try {
    groups.Memberships.lookup(group.name, {'memberKey.id': email});

  } catch(e) {
    // Log failure if exception is not related to membership existence
    if (!e.message.includes('Membership does not exist.')) {
      console.error(e);
    }
    return false;
  }
  return true;
}