本文介绍了如何获取使用 Google Apps Script 的 G Suite 用户列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,是否有机会获得使用 Google Apps Script 的 G Suite 用户(一个域的)列表?

I would like to find out, is there any chance to get a list of G Suite users (of one domain) who are using Google Apps Script?

推荐答案

在您检索 脚本项目 来自您用户的 Google 云端硬盘,您必须首先从 Apps 脚本 API.目前,获得一个项目的唯一方法是一个一个地进行,提供带有 scriptId 的请求.

After you retrieve the list of script projects from Google Drives of your users, you will have to first request project metadata for them from the Apps Script API. Presently, the only way to get a project is to go one by one, supplying requests with scriptId.

诀窍是脚本项目文件的Id恰好与脚本ID相同(如果你查看CLASP项目文件的源代码code>list 命令,你会看到他们利用这一事实来显示项目 ID).

The trick is that the Id of the script project file happens to be the the same as script Id (if you look at the source code of the CLASP project's list command, you will see that they utilize this fact to display project Ids).

要获取 Project 资源,我们需要调用 get 方法:

To acquire a Project resource, we need to call the get method:

GET https://script.googleapis.com/v1/projects/{scriptId}

下面是一个用于从 API 检索单个 Project 资源的简单实用程序.请注意,您的清单文件必须至少包含 https://www.googleapis.com/auth/script.projects.readonly 范围,否则 API 将返回 403代码> 响应代码.

Below is a simple utility for retrieving a single Project resource from the API. Note that your manifest file will have to include at least the https://www.googleapis.com/auth/script.projects.readonly scope, otherwise the API will return a 403 response code.

/**
 * @typedef {{
 *  domain : string,
 *  email : string,
 *  name : string
 * }} GSuiteUser
 *
 * @typedef {{
 *  scriptId : string,
 *  title : string,
 *  createTime : string,
 *  updateTime : string,
 *  creator : GSuiteUser,
 *  lastModifyUser : GSuiteUser
 * }} ScriptProject
 *
 * @summary gets script project metadata
 * @param {{
 *  id : string,
 *  token : string
 * }}
 * @returns {ScriptProject}
 */
const getProject = ({
  id = ScriptApp.getScriptId(),
  token = ScriptApp.getOAuthToken()
}) => {

  const uri = `https://script.googleapis.com/v1/projects/${id}`;

  /** @type {GoogleAppsScript.URL_Fetch.URLFetchRequestOptions} */
  const params = {
    contentType : "application/json",
    headers : {
      Authorization: `Bearer ${token}`
    },
    muteHttpExceptions : true,
    method : "get"
  };

  const response = UrlFetchApp.fetch(uri, params);

  const successChecker = getSuccessChecker();

  const success = successChecker(response);

  if(!success) {
    return {};
  }

  return JSON.parse(response.getContentText());
};

将其映射到您使用 ziganotschka 的方法获得的脚本文件列表上,您将获得有关项目的详细信息.接下来,如果使用是指运行项目,则可以调用processes.list API 方法:

Map it over the list of script files you obtained using ziganotschka's method, and you will get detailed info about the projects. Next, if by using you mean running projects, you can invoke the processes.list API method instead:

GET https://script.googleapis.com/v1/processes

所需的 OAuth 范围是 https://www.googleapis.com/auth/script.processes.

Required OAuth scope is https://www.googleapis.com/auth/script.processes.

/**
 * @typedef {{
 *  projectName : string,
 *  functionName : string,
 *  processType : string,
 *  processStatus : string,
 *  userAccessLevel : string,
 *  startTime : string,
 *  duration : string
 * }} ScriptProcess
 *
 * @summary lists script processes for a user
 * @param {{
 *  id : (string|"any"),
 *  pageSize : (number|50),
 *  token : string,
 *  start : (Date|undefined),
 *  end : (Date|undefined),
 *  statuses : string[],
 *  types : string[]
 * }}
 * @returns {ScriptProcess[]}
 */
const listScriptProcesses = ({
  id = ScriptApp.getScriptId(),
  token = ScriptApp.getOAuthToken(),
  pageSize = 50,
  start, end,
  statuses = [],
  types = []
} = {}) => {

  const query = [
    `pageSize=${pageSize}`,
    `userProcessFilter.startTime=${toZuluTimestamp(start)}`,
    `userProcessFilter.endTime=${toZuluTimestamp(end)}`
  ];

  id !== "any" && query.push(`userProcessFilter.scriptId=${id}`);
  types.length && query.push(`userProcessFilter.types=${types.join(",")}`);
  statuses.length && query.push(`userProcessFilter.statuses=${statuses.join(",")}`);

  const uri = `https://script.googleapis.com/v1/processes?${query.join("&")}`;

  /** @type {GoogleAppsScript.URL_Fetch.URLFetchRequestOptions} */
  const params = {
    contentType: "application/json",
    headers: {
      Authorization: `Bearer ${token}`
    },
    muteHttpExceptions: true,
    method: "get"
  };

  const response = UrlFetchApp.fetch(uri, params);
  const content = response.getContentText();

  const successChecker = getSuccessChecker();
  const success = successChecker(response);

  if (!success) {
    console.warn(response.getResponseCode(), content);
    return [];
  }

  const { processes = [] } = JSON.parse(content);

  return processes;
};

作为响应,您将代表获取有关脚本执行的元数据,该用户的凭据是通过不记名令牌传递的(您需要为每个用户提供一个服务帐户).

In response, you will get metadata about script executions on behalf of the user whose credentials are passed with the bearer token (you will need a service account for each user).

剩下的很简单:如果响应不是空的,那么用户在某个时间点运行了一个脚本项目(注意上面的实用程序默认 startend 时间戳参数到 now).如果您提供 any 作为脚本 ID,则请求将返回代表用户执行的每个.

The rest is easy: if the response is not empty, then the user ran a script project at some point in time (note that the utility above defaults both start and end timestamp parameters to now). If you supply any as the script Id, the request will return every execution made on behalf of the user.

该方法的另一个好处是返回每种类型的脚本项目执行,包括 Web 应用程序、附加组件和绑定项目(请参阅 ProcessType 枚举了解详情).

An added benefit of the approach is that every type of script project execution is returned, including Web Apps, Add-ons, and bound projects (see ProcessType enum for details).

这种方法的唯一困难在于部署为像我一样执行"的 Web 应用程序.它将始终在脚本项目所有者的权限下运行,因此您必须单独跟踪 Web 应用程序的用户.

The only difficulty with this approach is presented by Web Apps deployed to "execute as me" which will always run under the authority of the script project owner, so you will have to track the users of the Web App separately.

以上代码段使用以下实用程序脚本:

Snippets above use the following utility scripts:

/**
 * @summary checks HTTPResponse for being successful
 * @param {GoogleAppsScript.URL_Fetch.HTTPResponse} resp
 * @returns {boolean}
 */
const getSuccessChecker = ({ successOn = [200] } = {}) => (resp) => {
    const code = resp.getResponseCode();
    return successOn.some(c => c === code);
};
/**
 * @summary converts input into RFC3339 UTC "Zulu" format
 * @param {Date|number|string} [date]
 * @returns {string}
 */
const toZuluTimestamp = (date = Date.now()) => new Date(date).toISOString().replace('Z','000000Z');


您需要启用 V8 运行时启用上述代码段的工作(或将它们转换为 ES5 语法).


You will need to enable V8 runtime enabled for the snippets above to work (or transpile them to ES5 syntax).

这篇关于如何获取使用 Google Apps Script 的 G Suite 用户列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 00:16
查看更多