如何获取使用Google Apps脚本的G Suite用户列表? [英] How to get a list of G Suite users which are using Google Apps Script?
问题描述
我想了解一下,是否有机会获得使用Google Apps脚本的(一个域的)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?
推荐答案
检索脚本项目,您必须首先从
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
.
诀窍在于,脚本项目 file 的ID恰好与脚本ID (如果您查看CLASP项目的 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).
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
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).
其余的操作很容易:如果响应不为空,则用户会在某个时间点运行脚本项目(请注意,上面的实用程序默认将 start
和 end
时间戳参数设置为 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 Apps,附加组件和绑定项目(请参阅
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 Apps呈现的.它将始终在脚本项目所有者的权限下运行,因此您将不得不分别跟踪Web App的用户.
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脚本的G Suite用户列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!